babylon.viewer.max.js 6.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151
  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 = 19);
  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__(22); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(23); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(24); } 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. /** @hidden */
  523. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  524. // Rebuild shaders source code
  525. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  526. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  527. vertexCode = prefix + vertexCode;
  528. fragmentCode = prefix + fragmentCode;
  529. // Number lines of shaders source code
  530. var i = 2;
  531. var regex = /\n/gm;
  532. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  533. i = 2;
  534. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  535. // Dump shaders name and formatted source code
  536. if (this.name.vertexElement) {
  537. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  538. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  539. }
  540. else if (this.name.vertex) {
  541. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  542. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  543. }
  544. else {
  545. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  546. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  547. }
  548. };
  549. ;
  550. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  551. var preparedSourceCode = this._processPrecision(sourceCode);
  552. if (this._engine.webGLVersion == 1) {
  553. callback(preparedSourceCode);
  554. return;
  555. }
  556. // Already converted
  557. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  558. callback(preparedSourceCode.replace("#version 300 es", ""));
  559. return;
  560. }
  561. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  562. // Remove extensions
  563. // #extension GL_OES_standard_derivatives : enable
  564. // #extension GL_EXT_shader_texture_lod : enable
  565. // #extension GL_EXT_frag_depth : enable
  566. // #extension GL_EXT_draw_buffers : require
  567. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  568. var result = preparedSourceCode.replace(regex, "");
  569. // Migrate to GLSL v300
  570. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  571. result = result.replace(/attribute[ \t]/g, "in ");
  572. result = result.replace(/[ \t]attribute/g, " in");
  573. if (isFragment) {
  574. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  576. result = result.replace(/texture2D\s*\(/g, "texture(");
  577. result = result.replace(/textureCube\s*\(/g, "texture(");
  578. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  579. result = result.replace(/gl_FragColor/g, "glFragColor");
  580. result = result.replace(/gl_FragData/g, "glFragData");
  581. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  582. }
  583. callback(result);
  584. };
  585. Effect.prototype._processIncludes = function (sourceCode, callback) {
  586. var _this = this;
  587. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  588. var match = regex.exec(sourceCode);
  589. var returnValue = new String(sourceCode);
  590. while (match != null) {
  591. var includeFile = match[1];
  592. // Uniform declaration
  593. if (includeFile.indexOf("__decl__") !== -1) {
  594. includeFile = includeFile.replace(/__decl__/, "");
  595. if (this._engine.supportsUniformBuffers) {
  596. includeFile = includeFile.replace(/Vertex/, "Ubo");
  597. includeFile = includeFile.replace(/Fragment/, "Ubo");
  598. }
  599. includeFile = includeFile + "Declaration";
  600. }
  601. if (Effect.IncludesShadersStore[includeFile]) {
  602. // Substitution
  603. var includeContent = Effect.IncludesShadersStore[includeFile];
  604. if (match[2]) {
  605. var splits = match[3].split(",");
  606. for (var index = 0; index < splits.length; index += 2) {
  607. var source = new RegExp(splits[index], "g");
  608. var dest = splits[index + 1];
  609. includeContent = includeContent.replace(source, dest);
  610. }
  611. }
  612. if (match[4]) {
  613. var indexString = match[5];
  614. if (indexString.indexOf("..") !== -1) {
  615. var indexSplits = indexString.split("..");
  616. var minIndex = parseInt(indexSplits[0]);
  617. var maxIndex = parseInt(indexSplits[1]);
  618. var sourceIncludeContent = includeContent.slice(0);
  619. includeContent = "";
  620. if (isNaN(maxIndex)) {
  621. maxIndex = this._indexParameters[indexSplits[1]];
  622. }
  623. for (var i = minIndex; i < maxIndex; i++) {
  624. if (!this._engine.supportsUniformBuffers) {
  625. // Ubo replacement
  626. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  627. return p1 + "{X}";
  628. });
  629. }
  630. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  631. }
  632. }
  633. else {
  634. if (!this._engine.supportsUniformBuffers) {
  635. // Ubo replacement
  636. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  637. return p1 + "{X}";
  638. });
  639. }
  640. includeContent = includeContent.replace(/\{X\}/g, indexString);
  641. }
  642. }
  643. // Replace
  644. returnValue = returnValue.replace(match[0], includeContent);
  645. }
  646. else {
  647. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  648. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  649. Effect.IncludesShadersStore[includeFile] = fileContent;
  650. _this._processIncludes(returnValue, callback);
  651. });
  652. return;
  653. }
  654. match = regex.exec(sourceCode);
  655. }
  656. callback(returnValue);
  657. };
  658. Effect.prototype._processPrecision = function (source) {
  659. if (source.indexOf("precision highp float") === -1) {
  660. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  661. source = "precision mediump float;\n" + source;
  662. }
  663. else {
  664. source = "precision highp float;\n" + source;
  665. }
  666. }
  667. else {
  668. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  669. source = source.replace("precision highp float", "precision mediump float");
  670. }
  671. }
  672. return source;
  673. };
  674. /**
  675. * Recompiles the webGL program
  676. * @param vertexSourceCode The source code for the vertex shader.
  677. * @param fragmentSourceCode The source code for the fragment shader.
  678. * @param onCompiled Callback called when completed.
  679. * @param onError Callback called on error.
  680. */
  681. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  682. var _this = this;
  683. this._isReady = false;
  684. this._vertexSourceCodeOverride = vertexSourceCode;
  685. this._fragmentSourceCodeOverride = fragmentSourceCode;
  686. this.onError = function (effect, error) {
  687. if (onError) {
  688. onError(error);
  689. }
  690. };
  691. this.onCompiled = function () {
  692. var scenes = _this.getEngine().scenes;
  693. for (var i = 0; i < scenes.length; i++) {
  694. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  695. }
  696. if (onCompiled) {
  697. onCompiled(_this._program);
  698. }
  699. };
  700. this._fallbacks = null;
  701. this._prepareEffect();
  702. };
  703. /**
  704. * Gets the uniform locations of the the specified variable names
  705. * @param names THe names of the variables to lookup.
  706. * @returns Array of locations in the same order as variable names.
  707. */
  708. Effect.prototype.getSpecificUniformLocations = function (names) {
  709. var engine = this._engine;
  710. return engine.getUniforms(this._program, names);
  711. };
  712. /**
  713. * Prepares the effect
  714. */
  715. Effect.prototype._prepareEffect = function () {
  716. var attributesNames = this._attributesNames;
  717. var defines = this.defines;
  718. var fallbacks = this._fallbacks;
  719. this._valueCache = {};
  720. var previousProgram = this._program;
  721. try {
  722. var engine = this._engine;
  723. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  724. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  725. }
  726. else {
  727. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  728. }
  729. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  730. if (engine.supportsUniformBuffers) {
  731. for (var name in this._uniformBuffersNames) {
  732. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  733. }
  734. }
  735. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  736. this._attributes = engine.getAttributes(this._program, attributesNames);
  737. var index;
  738. for (index = 0; index < this._samplers.length; index++) {
  739. var sampler = this.getUniform(this._samplers[index]);
  740. if (sampler == null) {
  741. this._samplers.splice(index, 1);
  742. index--;
  743. }
  744. }
  745. engine.bindSamplers(this);
  746. this._compilationError = "";
  747. this._isReady = true;
  748. if (this.onCompiled) {
  749. this.onCompiled(this);
  750. }
  751. this.onCompileObservable.notifyObservers(this);
  752. this.onCompileObservable.clear();
  753. // Unbind mesh reference in fallbacks
  754. if (this._fallbacks) {
  755. this._fallbacks.unBindMesh();
  756. }
  757. if (previousProgram) {
  758. this.getEngine()._deleteProgram(previousProgram);
  759. }
  760. }
  761. catch (e) {
  762. this._compilationError = e.message;
  763. // Let's go through fallbacks then
  764. BABYLON.Tools.Error("Unable to compile effect:");
  765. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  766. return " " + uniform;
  767. }));
  768. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  769. return " " + attribute;
  770. }));
  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. if (x === void 0) { x = 0; }
  2299. if (y === void 0) { y = 0; }
  2300. this.x = x;
  2301. this.y = y;
  2302. }
  2303. /**
  2304. * Gets a string with the Vector2 coordinates
  2305. * @returns a string with the Vector2 coordinates
  2306. */
  2307. Vector2.prototype.toString = function () {
  2308. return "{X: " + this.x + " Y:" + this.y + "}";
  2309. };
  2310. /**
  2311. * Gets class name
  2312. * @returns the string "Vector2"
  2313. */
  2314. Vector2.prototype.getClassName = function () {
  2315. return "Vector2";
  2316. };
  2317. /**
  2318. * Gets current vector hash code
  2319. * @returns the Vector2 hash code as a number
  2320. */
  2321. Vector2.prototype.getHashCode = function () {
  2322. var hash = this.x || 0;
  2323. hash = (hash * 397) ^ (this.y || 0);
  2324. return hash;
  2325. };
  2326. // Operators
  2327. /**
  2328. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2329. * @param array defines the source array
  2330. * @param index defines the offset in source array
  2331. * @returns the current Vector2
  2332. */
  2333. Vector2.prototype.toArray = function (array, index) {
  2334. if (index === void 0) { index = 0; }
  2335. array[index] = this.x;
  2336. array[index + 1] = this.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Copy the current vector to an array
  2341. * @returns a new array with 2 elements: the Vector2 coordinates.
  2342. */
  2343. Vector2.prototype.asArray = function () {
  2344. var result = new Array();
  2345. this.toArray(result, 0);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2350. * @param source defines the source Vector2
  2351. * @returns the current updated Vector2
  2352. */
  2353. Vector2.prototype.copyFrom = function (source) {
  2354. this.x = source.x;
  2355. this.y = source.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Sets the Vector2 coordinates with the given floats
  2360. * @param x defines the first coordinate
  2361. * @param y defines the second coordinate
  2362. * @returns the current updated Vector2
  2363. */
  2364. Vector2.prototype.copyFromFloats = function (x, y) {
  2365. this.x = x;
  2366. this.y = y;
  2367. return this;
  2368. };
  2369. /**
  2370. * Sets the Vector2 coordinates with the given floats
  2371. * @param x defines the first coordinate
  2372. * @param y defines the second coordinate
  2373. * @returns the current updated Vector2
  2374. */
  2375. Vector2.prototype.set = function (x, y) {
  2376. return this.copyFromFloats(x, y);
  2377. };
  2378. /**
  2379. * Add another vector with the current one
  2380. * @param otherVector defines the other vector
  2381. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2382. */
  2383. Vector2.prototype.add = function (otherVector) {
  2384. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2385. };
  2386. /**
  2387. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2388. * @param otherVector defines the other vector
  2389. * @param result defines the target vector
  2390. * @returns the unmodified current Vector2
  2391. */
  2392. Vector2.prototype.addToRef = function (otherVector, result) {
  2393. result.x = this.x + otherVector.x;
  2394. result.y = this.y + otherVector.y;
  2395. return this;
  2396. };
  2397. /**
  2398. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2399. * @param otherVector defines the other vector
  2400. * @returns the current updated Vector2
  2401. */
  2402. Vector2.prototype.addInPlace = function (otherVector) {
  2403. this.x += otherVector.x;
  2404. this.y += otherVector.y;
  2405. return this;
  2406. };
  2407. /**
  2408. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2409. * @param otherVector defines the other vector
  2410. * @returns a new Vector2
  2411. */
  2412. Vector2.prototype.addVector3 = function (otherVector) {
  2413. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2414. };
  2415. /**
  2416. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2417. * @param otherVector defines the other vector
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.subtract = function (otherVector) {
  2421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2422. };
  2423. /**
  2424. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2425. * @param otherVector defines the other vector
  2426. * @param result defines the target vector
  2427. * @returns the unmodified current Vector2
  2428. */
  2429. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2430. result.x = this.x - otherVector.x;
  2431. result.y = this.y - otherVector.y;
  2432. return this;
  2433. };
  2434. /**
  2435. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2436. * @param otherVector defines the other vector
  2437. * @returns the current updated Vector2
  2438. */
  2439. Vector2.prototype.subtractInPlace = function (otherVector) {
  2440. this.x -= otherVector.x;
  2441. this.y -= otherVector.y;
  2442. return this;
  2443. };
  2444. /**
  2445. * Multiplies in place the current Vector2 coordinates by the given ones
  2446. * @param otherVector defines the other vector
  2447. * @returns the current updated Vector2
  2448. */
  2449. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2450. this.x *= otherVector.x;
  2451. this.y *= otherVector.y;
  2452. return this;
  2453. };
  2454. /**
  2455. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2456. * @param otherVector defines the other vector
  2457. * @returns a new Vector2
  2458. */
  2459. Vector2.prototype.multiply = function (otherVector) {
  2460. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2461. };
  2462. /**
  2463. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2464. * @param otherVector defines the other vector
  2465. * @param result defines the target vector
  2466. * @returns the unmodified current Vector2
  2467. */
  2468. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2469. result.x = this.x * otherVector.x;
  2470. result.y = this.y * otherVector.y;
  2471. return this;
  2472. };
  2473. /**
  2474. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2475. * @param x defines the first coordinate
  2476. * @param y defines the second coordinate
  2477. * @returns a new Vector2
  2478. */
  2479. Vector2.prototype.multiplyByFloats = function (x, y) {
  2480. return new Vector2(this.x * x, this.y * y);
  2481. };
  2482. /**
  2483. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2484. * @param otherVector defines the other vector
  2485. * @returns a new Vector2
  2486. */
  2487. Vector2.prototype.divide = function (otherVector) {
  2488. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2489. };
  2490. /**
  2491. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2492. * @param otherVector defines the other vector
  2493. * @param result defines the target vector
  2494. * @returns the unmodified current Vector2
  2495. */
  2496. Vector2.prototype.divideToRef = function (otherVector, result) {
  2497. result.x = this.x / otherVector.x;
  2498. result.y = this.y / otherVector.y;
  2499. return this;
  2500. };
  2501. /**
  2502. * Divides the current Vector3 coordinates by the given ones
  2503. * @param otherVector defines the other vector
  2504. * @returns the current updated Vector2
  2505. */
  2506. Vector2.prototype.divideInPlace = function (otherVector) {
  2507. return this.divideToRef(otherVector, this);
  2508. };
  2509. /**
  2510. * Gets a new Vector2 with current Vector2 negated coordinates
  2511. * @returns a new Vector2
  2512. */
  2513. Vector2.prototype.negate = function () {
  2514. return new Vector2(-this.x, -this.y);
  2515. };
  2516. /**
  2517. * Multiply the Vector2 coordinates by scale
  2518. * @param scale defines the scaling factor
  2519. * @returns the current updated Vector2
  2520. */
  2521. Vector2.prototype.scaleInPlace = function (scale) {
  2522. this.x *= scale;
  2523. this.y *= scale;
  2524. return this;
  2525. };
  2526. /**
  2527. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2528. * @param scale defines the scaling factor
  2529. * @returns a new Vector2
  2530. */
  2531. Vector2.prototype.scale = function (scale) {
  2532. var result = new Vector2(0, 0);
  2533. this.scaleToRef(scale, result);
  2534. return result;
  2535. };
  2536. /**
  2537. * Scale the current Vector2 values by a factor to a given Vector2
  2538. * @param scale defines the scale factor
  2539. * @param result defines the Vector2 object where to store the result
  2540. * @returns the unmodified current Vector2
  2541. */
  2542. Vector2.prototype.scaleToRef = function (scale, result) {
  2543. result.x = this.x * scale;
  2544. result.y = this.y * scale;
  2545. return this;
  2546. };
  2547. /**
  2548. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2549. * @param scale defines the scale factor
  2550. * @param result defines the Vector2 object where to store the result
  2551. * @returns the unmodified current Vector2
  2552. */
  2553. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2554. result.x += this.x * scale;
  2555. result.y += this.y * scale;
  2556. return this;
  2557. };
  2558. /**
  2559. * Gets a boolean if two vectors are equals
  2560. * @param otherVector defines the other vector
  2561. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2562. */
  2563. Vector2.prototype.equals = function (otherVector) {
  2564. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2565. };
  2566. /**
  2567. * Gets a boolean if two vectors are equals (using an epsilon value)
  2568. * @param otherVector defines the other vector
  2569. * @param epsilon defines the minimal distance to consider equality
  2570. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2571. */
  2572. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2573. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2574. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * 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".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. 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);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. if (other.x < this.x)
  3174. this.x = other.x;
  3175. if (other.y < this.y)
  3176. this.y = other.y;
  3177. if (other.z < this.z)
  3178. this.z = other.z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3183. * @param other defines the second operand
  3184. * @returns the current updated Vector3
  3185. */
  3186. Vector3.prototype.maximizeInPlace = function (other) {
  3187. if (other.x > this.x)
  3188. this.x = other.x;
  3189. if (other.y > this.y)
  3190. this.y = other.y;
  3191. if (other.z > this.z)
  3192. this.z = other.z;
  3193. return this;
  3194. };
  3195. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3196. /**
  3197. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3198. */
  3199. get: function () {
  3200. var absX = Math.abs(this.x);
  3201. var absY = Math.abs(this.y);
  3202. if (absX !== absY) {
  3203. return true;
  3204. }
  3205. var absZ = Math.abs(this.z);
  3206. if (absX !== absZ) {
  3207. return true;
  3208. }
  3209. if (absY !== absZ) {
  3210. return true;
  3211. }
  3212. return false;
  3213. },
  3214. enumerable: true,
  3215. configurable: true
  3216. });
  3217. // Properties
  3218. /**
  3219. * Gets the length of the Vector3
  3220. * @returns the length of the Vecto3
  3221. */
  3222. Vector3.prototype.length = function () {
  3223. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3224. };
  3225. /**
  3226. * Gets the squared length of the Vector3
  3227. * @returns squared length of the Vector3
  3228. */
  3229. Vector3.prototype.lengthSquared = function () {
  3230. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3231. };
  3232. /**
  3233. * Normalize the current Vector3.
  3234. * Please note that this is an in place operation.
  3235. * @returns the current updated Vector3
  3236. */
  3237. Vector3.prototype.normalize = function () {
  3238. var len = this.length();
  3239. if (len === 0 || len === 1.0)
  3240. return this;
  3241. var num = 1.0 / len;
  3242. this.x *= num;
  3243. this.y *= num;
  3244. this.z *= num;
  3245. return this;
  3246. };
  3247. /**
  3248. * Normalize the current Vector3 to a new vector
  3249. * @returns the new Vector3
  3250. */
  3251. Vector3.prototype.normalizeToNew = function () {
  3252. var normalized = new Vector3(0, 0, 0);
  3253. this.normalizeToRef(normalized);
  3254. return normalized;
  3255. };
  3256. /**
  3257. * Normalize the current Vector3 to the reference
  3258. * @param reference define the Vector3 to update
  3259. * @returns the updated Vector3
  3260. */
  3261. Vector3.prototype.normalizeToRef = function (reference) {
  3262. var len = this.length();
  3263. if (len === 0 || len === 1.0) {
  3264. reference.set(this.x, this.y, this.z);
  3265. return reference;
  3266. }
  3267. var scale = 1.0 / len;
  3268. this.scaleToRef(scale, reference);
  3269. return reference;
  3270. };
  3271. /**
  3272. * Creates a new Vector3 copied from the current Vector3
  3273. * @returns the new Vector3
  3274. */
  3275. Vector3.prototype.clone = function () {
  3276. return new Vector3(this.x, this.y, this.z);
  3277. };
  3278. /**
  3279. * Copies the given vector coordinates to the current Vector3 ones
  3280. * @param source defines the source Vector3
  3281. * @returns the current updated Vector3
  3282. */
  3283. Vector3.prototype.copyFrom = function (source) {
  3284. this.x = source.x;
  3285. this.y = source.y;
  3286. this.z = source.z;
  3287. return this;
  3288. };
  3289. /**
  3290. * Copies the given floats to the current Vector3 coordinates
  3291. * @param x defines the x coordinate of the operand
  3292. * @param y defines the y coordinate of the operand
  3293. * @param z defines the z coordinate of the operand
  3294. * @returns the current updated Vector3
  3295. */
  3296. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3297. this.x = x;
  3298. this.y = y;
  3299. this.z = z;
  3300. return this;
  3301. };
  3302. /**
  3303. * Copies the given floats to the current Vector3 coordinates
  3304. * @param x defines the x coordinate of the operand
  3305. * @param y defines the y coordinate of the operand
  3306. * @param z defines the z coordinate of the operand
  3307. * @returns the current updated Vector3
  3308. */
  3309. Vector3.prototype.set = function (x, y, z) {
  3310. return this.copyFromFloats(x, y, z);
  3311. };
  3312. // Statics
  3313. /**
  3314. * Get the clip factor between two vectors
  3315. * @param vector0 defines the first operand
  3316. * @param vector1 defines the second operand
  3317. * @param axis defines the axis to use
  3318. * @param size defines the size along the axis
  3319. * @returns the clip factor
  3320. */
  3321. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3322. var d0 = Vector3.Dot(vector0, axis) - size;
  3323. var d1 = Vector3.Dot(vector1, axis) - size;
  3324. var s = d0 / (d0 - d1);
  3325. return s;
  3326. };
  3327. /**
  3328. * Get angle between two vectors
  3329. * @param vector0 angle between vector0 and vector1
  3330. * @param vector1 angle between vector0 and vector1
  3331. * @param normal direction of the normal
  3332. * @return the angle between vector0 and vector1
  3333. */
  3334. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3335. var v0 = vector0.clone().normalize();
  3336. var v1 = vector1.clone().normalize();
  3337. var dot = Vector3.Dot(v0, v1);
  3338. var n = Vector3.Cross(v0, v1);
  3339. if (Vector3.Dot(n, normal) > 0) {
  3340. return Math.acos(dot);
  3341. }
  3342. return -Math.acos(dot);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set from the index "offset" of the given array
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @returns the new Vector3
  3349. */
  3350. Vector3.FromArray = function (array, offset) {
  3351. if (!offset) {
  3352. offset = 0;
  3353. }
  3354. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3355. };
  3356. /**
  3357. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3358. * This function is deprecated. Use FromArray instead
  3359. * @param array defines the source array
  3360. * @param offset defines the offset in the source array
  3361. * @returns the new Vector3
  3362. */
  3363. Vector3.FromFloatArray = function (array, offset) {
  3364. return Vector3.FromArray(array, offset);
  3365. };
  3366. /**
  3367. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3368. * @param array defines the source array
  3369. * @param offset defines the offset in the source array
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.FromArrayToRef = function (array, offset, result) {
  3373. result.x = array[offset];
  3374. result.y = array[offset + 1];
  3375. result.z = array[offset + 2];
  3376. };
  3377. /**
  3378. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3379. * This function is deprecated. Use FromArrayToRef instead.
  3380. * @param array defines the source array
  3381. * @param offset defines the offset in the source array
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3385. return Vector3.FromArrayToRef(array, offset, result);
  3386. };
  3387. /**
  3388. * Sets the given vector "result" with the given floats.
  3389. * @param x defines the x coordinate of the source
  3390. * @param y defines the y coordinate of the source
  3391. * @param z defines the z coordinate of the source
  3392. * @param result defines the Vector3 where to store the result
  3393. */
  3394. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3395. result.x = x;
  3396. result.y = y;
  3397. result.z = z;
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3401. * @returns a new empty Vector3
  3402. */
  3403. Vector3.Zero = function () {
  3404. return new Vector3(0.0, 0.0, 0.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3408. * @returns a new unit Vector3
  3409. */
  3410. Vector3.One = function () {
  3411. return new Vector3(1.0, 1.0, 1.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3415. * @returns a new up Vector3
  3416. */
  3417. Vector3.Up = function () {
  3418. return new Vector3(0.0, 1.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3422. * @returns a new down Vector3
  3423. */
  3424. Vector3.Down = function () {
  3425. return new Vector3(0.0, -1.0, 0.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3429. * @returns a new forward Vector3
  3430. */
  3431. Vector3.Forward = function () {
  3432. return new Vector3(0.0, 0.0, 1.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3436. * @returns a new right Vector3
  3437. */
  3438. Vector3.Right = function () {
  3439. return new Vector3(1.0, 0.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3443. * @returns a new left Vector3
  3444. */
  3445. Vector3.Left = function () {
  3446. return new Vector3(-1.0, 0.0, 0.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set 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. * @returns the transformed Vector3
  3454. */
  3455. Vector3.TransformCoordinates = function (vector, transformation) {
  3456. var result = Vector3.Zero();
  3457. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3458. return result;
  3459. };
  3460. /**
  3461. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3462. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3463. * @param vector defines the Vector3 to transform
  3464. * @param transformation defines the transformation matrix
  3465. * @param result defines the Vector3 where to store the result
  3466. */
  3467. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3468. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3469. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3470. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3471. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3472. result.x = x / w;
  3473. result.y = y / w;
  3474. result.z = z / w;
  3475. };
  3476. /**
  3477. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3478. * This method computes tranformed coordinates only, not transformed direction vectors
  3479. * @param x define the x coordinate of the source vector
  3480. * @param y define the y coordinate of the source vector
  3481. * @param z define the z coordinate of the source vector
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3486. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3487. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3488. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3489. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3490. result.x = rx / rw;
  3491. result.y = ry / rw;
  3492. result.z = rz / rw;
  3493. };
  3494. /**
  3495. * Returns a new Vector3 set 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. * @returns the new Vector3
  3500. */
  3501. Vector3.TransformNormal = function (vector, transformation) {
  3502. var result = Vector3.Zero();
  3503. Vector3.TransformNormalToRef(vector, transformation, result);
  3504. return result;
  3505. };
  3506. /**
  3507. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3508. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3509. * @param vector defines the Vector3 to transform
  3510. * @param transformation defines the transformation matrix
  3511. * @param result defines the Vector3 where to store the result
  3512. */
  3513. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3514. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3515. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3516. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3517. result.x = x;
  3518. result.y = y;
  3519. result.z = z;
  3520. };
  3521. /**
  3522. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3523. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3524. * @param x define the x coordinate of the source vector
  3525. * @param y define the y coordinate of the source vector
  3526. * @param z define the z coordinate of the source vector
  3527. * @param transformation defines the transformation matrix
  3528. * @param result defines the Vector3 where to store the result
  3529. */
  3530. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3531. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3532. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3533. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3537. * @param value1 defines the first control point
  3538. * @param value2 defines the second control point
  3539. * @param value3 defines the third control point
  3540. * @param value4 defines the fourth control point
  3541. * @param amount defines the amount on the spline to use
  3542. * @returns the new Vector3
  3543. */
  3544. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3545. var squared = amount * amount;
  3546. var cubed = amount * squared;
  3547. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3548. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3549. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3550. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3551. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3552. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3553. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3554. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3555. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3556. return new Vector3(x, y, z);
  3557. };
  3558. /**
  3559. * 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"
  3560. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3561. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3562. * @param value defines the current value
  3563. * @param min defines the lower range value
  3564. * @param max defines the upper range value
  3565. * @returns the new Vector3
  3566. */
  3567. Vector3.Clamp = function (value, min, max) {
  3568. var x = value.x;
  3569. x = (x > max.x) ? max.x : x;
  3570. x = (x < min.x) ? min.x : x;
  3571. var y = value.y;
  3572. y = (y > max.y) ? max.y : y;
  3573. y = (y < min.y) ? min.y : y;
  3574. var z = value.z;
  3575. z = (z > max.z) ? max.z : z;
  3576. z = (z < min.z) ? min.z : z;
  3577. return new Vector3(x, y, z);
  3578. };
  3579. /**
  3580. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3581. * @param value1 defines the first control point
  3582. * @param tangent1 defines the first tangent vector
  3583. * @param value2 defines the second control point
  3584. * @param tangent2 defines the second tangent vector
  3585. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3589. var squared = amount * amount;
  3590. var cubed = amount * squared;
  3591. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3592. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3593. var part3 = (cubed - (2.0 * squared)) + amount;
  3594. var part4 = cubed - squared;
  3595. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3596. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3597. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3598. return new Vector3(x, y, z);
  3599. };
  3600. /**
  3601. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "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. * @returns the new Vector3
  3606. */
  3607. Vector3.Lerp = function (start, end, amount) {
  3608. var result = new Vector3(0, 0, 0);
  3609. Vector3.LerpToRef(start, end, amount, result);
  3610. return result;
  3611. };
  3612. /**
  3613. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3614. * @param start defines the start value
  3615. * @param end defines the end value
  3616. * @param amount max defines amount between both (between 0 and 1)
  3617. * @param result defines the Vector3 where to store the result
  3618. */
  3619. Vector3.LerpToRef = function (start, end, amount, result) {
  3620. result.x = start.x + ((end.x - start.x) * amount);
  3621. result.y = start.y + ((end.y - start.y) * amount);
  3622. result.z = start.z + ((end.z - start.z) * amount);
  3623. };
  3624. /**
  3625. * Returns the dot product (float) between the vectors "left" and "right"
  3626. * @param left defines the left operand
  3627. * @param right defines the right operand
  3628. * @returns the dot product
  3629. */
  3630. Vector3.Dot = function (left, right) {
  3631. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3632. };
  3633. /**
  3634. * Returns a new Vector3 as the cross product of the vectors "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. * @returns the cross product
  3639. */
  3640. Vector3.Cross = function (left, right) {
  3641. var result = Vector3.Zero();
  3642. Vector3.CrossToRef(left, right, result);
  3643. return result;
  3644. };
  3645. /**
  3646. * Sets the given vector "result" with the cross product of "left" and "right"
  3647. * The cross product is then orthogonal to both "left" and "right"
  3648. * @param left defines the left operand
  3649. * @param right defines the right operand
  3650. * @param result defines the Vector3 where to store the result
  3651. */
  3652. Vector3.CrossToRef = function (left, right, result) {
  3653. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3654. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3655. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3656. result.copyFrom(MathTmp.Vector3[0]);
  3657. };
  3658. /**
  3659. * Returns a new Vector3 as the normalization of the given vector
  3660. * @param vector defines the Vector3 to normalize
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Normalize = function (vector) {
  3664. var result = Vector3.Zero();
  3665. Vector3.NormalizeToRef(vector, result);
  3666. return result;
  3667. };
  3668. /**
  3669. * Sets the given vector "result" with the normalization of the given first vector
  3670. * @param vector defines the Vector3 to normalize
  3671. * @param result defines the Vector3 where to store the result
  3672. */
  3673. Vector3.NormalizeToRef = function (vector, result) {
  3674. result.copyFrom(vector);
  3675. result.normalize();
  3676. };
  3677. /**
  3678. * Project a Vector3 onto screen space
  3679. * @param vector defines the Vector3 to project
  3680. * @param world defines the world matrix to use
  3681. * @param transform defines the transform (view x projection) matrix to use
  3682. * @param viewport defines the screen viewport to use
  3683. * @returns the new Vector3
  3684. */
  3685. Vector3.Project = function (vector, world, transform, viewport) {
  3686. var cw = viewport.width;
  3687. var ch = viewport.height;
  3688. var cx = viewport.x;
  3689. var cy = viewport.y;
  3690. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3691. 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);
  3692. var matrix = MathTmp.Matrix[0];
  3693. world.multiplyToRef(transform, matrix);
  3694. matrix.multiplyToRef(viewportMatrix, matrix);
  3695. return Vector3.TransformCoordinates(vector, matrix);
  3696. };
  3697. /**
  3698. * Unproject from screen space to object space
  3699. * @param source defines the screen space Vector3 to use
  3700. * @param viewportWidth defines the current width of the viewport
  3701. * @param viewportHeight defines the current height of the viewport
  3702. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3703. * @param transform defines the transform (view x projection) matrix to use
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3707. var matrix = MathTmp.Matrix[0];
  3708. world.multiplyToRef(transform, matrix);
  3709. matrix.invert();
  3710. source.x = source.x / viewportWidth * 2 - 1;
  3711. source.y = -(source.y / viewportHeight * 2 - 1);
  3712. var vector = Vector3.TransformCoordinates(source, matrix);
  3713. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3714. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3715. vector = vector.scale(1.0 / num);
  3716. }
  3717. return vector;
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param source defines the screen space Vector3 to use
  3722. * @param viewportWidth defines the current width of the viewport
  3723. * @param viewportHeight defines the current height of the viewport
  3724. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3725. * @param view defines the view matrix to use
  3726. * @param projection defines the projection matrix to use
  3727. * @returns the new Vector3
  3728. */
  3729. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3730. var result = Vector3.Zero();
  3731. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3732. return result;
  3733. };
  3734. /**
  3735. * Unproject from screen space to object space
  3736. * @param source defines the screen space Vector3 to use
  3737. * @param viewportWidth defines the current width of the viewport
  3738. * @param viewportHeight defines the current height of the viewport
  3739. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3740. * @param view defines the view matrix to use
  3741. * @param projection defines the projection matrix to use
  3742. * @param result defines the Vector3 where to store the result
  3743. */
  3744. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3745. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3746. };
  3747. /**
  3748. * Unproject from screen space to object space
  3749. * @param sourceX defines the screen space x coordinate to use
  3750. * @param sourceY defines the screen space y coordinate to use
  3751. * @param sourceZ defines the screen space z coordinate to use
  3752. * @param viewportWidth defines the current width of the viewport
  3753. * @param viewportHeight defines the current height of the viewport
  3754. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3755. * @param view defines the view matrix to use
  3756. * @param projection defines the projection matrix to use
  3757. * @param result defines the Vector3 where to store the result
  3758. */
  3759. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3760. var matrix = MathTmp.Matrix[0];
  3761. world.multiplyToRef(view, matrix);
  3762. matrix.multiplyToRef(projection, matrix);
  3763. matrix.invert();
  3764. var screenSource = MathTmp.Vector3[0];
  3765. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3766. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3767. screenSource.z = 2 * sourceZ - 1.0;
  3768. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3769. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3770. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3771. result.scaleInPlace(1.0 / num);
  3772. }
  3773. };
  3774. /**
  3775. * Gets the minimal coordinate values between two Vector3
  3776. * @param left defines the first operand
  3777. * @param right defines the second operand
  3778. * @returns the new Vector3
  3779. */
  3780. Vector3.Minimize = function (left, right) {
  3781. var min = left.clone();
  3782. min.minimizeInPlace(right);
  3783. return min;
  3784. };
  3785. /**
  3786. * Gets the maximal coordinate values between two Vector3
  3787. * @param left defines the first operand
  3788. * @param right defines the second operand
  3789. * @returns the new Vector3
  3790. */
  3791. Vector3.Maximize = function (left, right) {
  3792. var max = left.clone();
  3793. max.maximizeInPlace(right);
  3794. return max;
  3795. };
  3796. /**
  3797. * Returns the distance between the vectors "value1" and "value2"
  3798. * @param value1 defines the first operand
  3799. * @param value2 defines the second operand
  3800. * @returns the distance
  3801. */
  3802. Vector3.Distance = function (value1, value2) {
  3803. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3804. };
  3805. /**
  3806. * Returns the squared distance between the vectors "value1" and "value2"
  3807. * @param value1 defines the first operand
  3808. * @param value2 defines the second operand
  3809. * @returns the squared distance
  3810. */
  3811. Vector3.DistanceSquared = function (value1, value2) {
  3812. var x = value1.x - value2.x;
  3813. var y = value1.y - value2.y;
  3814. var z = value1.z - value2.z;
  3815. return (x * x) + (y * y) + (z * z);
  3816. };
  3817. /**
  3818. * Returns a new Vector3 located at the center between "value1" and "value2"
  3819. * @param value1 defines the first operand
  3820. * @param value2 defines the second operand
  3821. * @returns the new Vector3
  3822. */
  3823. Vector3.Center = function (value1, value2) {
  3824. var center = value1.add(value2);
  3825. center.scaleInPlace(0.5);
  3826. return center;
  3827. };
  3828. /**
  3829. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3830. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3831. * to something in order to rotate it from its local system to the given target system
  3832. * Note: axis1, axis2 and axis3 are normalized during this operation
  3833. * @param axis1 defines the first axis
  3834. * @param axis2 defines the second axis
  3835. * @param axis3 defines the third axis
  3836. * @returns a new Vector3
  3837. */
  3838. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3839. var rotation = Vector3.Zero();
  3840. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3841. return rotation;
  3842. };
  3843. /**
  3844. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3845. * @param axis1 defines the first axis
  3846. * @param axis2 defines the second axis
  3847. * @param axis3 defines the third axis
  3848. * @param ref defines the Vector3 where to store the result
  3849. */
  3850. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3851. var quat = MathTmp.Quaternion[0];
  3852. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3853. quat.toEulerAnglesToRef(ref);
  3854. };
  3855. return Vector3;
  3856. }());
  3857. BABYLON.Vector3 = Vector3;
  3858. //Vector4 class created for EulerAngle class conversion to Quaternion
  3859. var Vector4 = /** @class */ (function () {
  3860. /**
  3861. * Creates a Vector4 object from the given floats.
  3862. */
  3863. function Vector4(x, y, z, w) {
  3864. this.x = x;
  3865. this.y = y;
  3866. this.z = z;
  3867. this.w = w;
  3868. }
  3869. /**
  3870. * Returns the string with the Vector4 coordinates.
  3871. */
  3872. Vector4.prototype.toString = function () {
  3873. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3874. };
  3875. /**
  3876. * Returns the string "Vector4".
  3877. */
  3878. Vector4.prototype.getClassName = function () {
  3879. return "Vector4";
  3880. };
  3881. /**
  3882. * Returns the Vector4 hash code.
  3883. */
  3884. Vector4.prototype.getHashCode = function () {
  3885. var hash = this.x || 0;
  3886. hash = (hash * 397) ^ (this.y || 0);
  3887. hash = (hash * 397) ^ (this.z || 0);
  3888. hash = (hash * 397) ^ (this.w || 0);
  3889. return hash;
  3890. };
  3891. // Operators
  3892. /**
  3893. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3894. */
  3895. Vector4.prototype.asArray = function () {
  3896. var result = new Array();
  3897. this.toArray(result, 0);
  3898. return result;
  3899. };
  3900. /**
  3901. * Populates the given array from the given index with the Vector4 coordinates.
  3902. * Returns the Vector4.
  3903. */
  3904. Vector4.prototype.toArray = function (array, index) {
  3905. if (index === undefined) {
  3906. index = 0;
  3907. }
  3908. array[index] = this.x;
  3909. array[index + 1] = this.y;
  3910. array[index + 2] = this.z;
  3911. array[index + 3] = this.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Adds the given vector to the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.addInPlace = function (otherVector) {
  3919. this.x += otherVector.x;
  3920. this.y += otherVector.y;
  3921. this.z += otherVector.z;
  3922. this.w += otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3927. */
  3928. Vector4.prototype.add = function (otherVector) {
  3929. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3930. };
  3931. /**
  3932. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.addToRef = function (otherVector, result) {
  3936. result.x = this.x + otherVector.x;
  3937. result.y = this.y + otherVector.y;
  3938. result.z = this.z + otherVector.z;
  3939. result.w = this.w + otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Subtract in place the given vector from the current Vector4.
  3944. * Returns the updated Vector4.
  3945. */
  3946. Vector4.prototype.subtractInPlace = function (otherVector) {
  3947. this.x -= otherVector.x;
  3948. this.y -= otherVector.y;
  3949. this.z -= otherVector.z;
  3950. this.w -= otherVector.w;
  3951. return this;
  3952. };
  3953. /**
  3954. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3955. */
  3956. Vector4.prototype.subtract = function (otherVector) {
  3957. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3958. };
  3959. /**
  3960. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3961. * Returns the current Vector4.
  3962. */
  3963. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3964. result.x = this.x - otherVector.x;
  3965. result.y = this.y - otherVector.y;
  3966. result.z = this.z - otherVector.z;
  3967. result.w = this.w - otherVector.w;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3972. */
  3973. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3974. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3975. };
  3976. /**
  3977. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3981. result.x = this.x - x;
  3982. result.y = this.y - y;
  3983. result.z = this.z - z;
  3984. result.w = this.w - w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3989. */
  3990. Vector4.prototype.negate = function () {
  3991. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3992. };
  3993. /**
  3994. * Multiplies the current Vector4 coordinates by scale (float).
  3995. * Returns the updated Vector4.
  3996. */
  3997. Vector4.prototype.scaleInPlace = function (scale) {
  3998. this.x *= scale;
  3999. this.y *= scale;
  4000. this.z *= scale;
  4001. this.w *= scale;
  4002. return this;
  4003. };
  4004. /**
  4005. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4006. */
  4007. Vector4.prototype.scale = function (scale) {
  4008. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4009. };
  4010. /**
  4011. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4012. * Returns the current Vector4.
  4013. */
  4014. Vector4.prototype.scaleToRef = function (scale, result) {
  4015. result.x = this.x * scale;
  4016. result.y = this.y * scale;
  4017. result.z = this.z * scale;
  4018. result.w = this.w * scale;
  4019. return this;
  4020. };
  4021. /**
  4022. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4023. * @param scale defines the scale factor
  4024. * @param result defines the Vector4 object where to store the result
  4025. * @returns the unmodified current Vector4
  4026. */
  4027. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4028. result.x += this.x * scale;
  4029. result.y += this.y * scale;
  4030. result.z += this.z * scale;
  4031. result.w += this.w * scale;
  4032. return this;
  4033. };
  4034. /**
  4035. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4036. */
  4037. Vector4.prototype.equals = function (otherVector) {
  4038. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4039. };
  4040. /**
  4041. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4042. */
  4043. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4044. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4045. return otherVector
  4046. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4047. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4048. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4049. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4050. };
  4051. /**
  4052. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4053. */
  4054. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4055. return this.x === x && this.y === y && this.z === z && this.w === w;
  4056. };
  4057. /**
  4058. * Multiplies in place the current Vector4 by the given one.
  4059. * Returns the updated Vector4.
  4060. */
  4061. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4062. this.x *= otherVector.x;
  4063. this.y *= otherVector.y;
  4064. this.z *= otherVector.z;
  4065. this.w *= otherVector.w;
  4066. return this;
  4067. };
  4068. /**
  4069. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4070. */
  4071. Vector4.prototype.multiply = function (otherVector) {
  4072. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4073. };
  4074. /**
  4075. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4076. * Returns the current Vector4.
  4077. */
  4078. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4079. result.x = this.x * otherVector.x;
  4080. result.y = this.y * otherVector.y;
  4081. result.z = this.z * otherVector.z;
  4082. result.w = this.w * otherVector.w;
  4083. return this;
  4084. };
  4085. /**
  4086. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4087. */
  4088. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4089. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4090. };
  4091. /**
  4092. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4093. */
  4094. Vector4.prototype.divide = function (otherVector) {
  4095. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4096. };
  4097. /**
  4098. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4099. * Returns the current Vector4.
  4100. */
  4101. Vector4.prototype.divideToRef = function (otherVector, result) {
  4102. result.x = this.x / otherVector.x;
  4103. result.y = this.y / otherVector.y;
  4104. result.z = this.z / otherVector.z;
  4105. result.w = this.w / otherVector.w;
  4106. return this;
  4107. };
  4108. /**
  4109. * Divides the current Vector3 coordinates by the given ones.
  4110. * @returns the updated Vector3.
  4111. */
  4112. Vector4.prototype.divideInPlace = function (otherVector) {
  4113. return this.divideToRef(otherVector, this);
  4114. };
  4115. /**
  4116. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4117. * @param other defines the second operand
  4118. * @returns the current updated Vector4
  4119. */
  4120. Vector4.prototype.minimizeInPlace = function (other) {
  4121. if (other.x < this.x)
  4122. this.x = other.x;
  4123. if (other.y < this.y)
  4124. this.y = other.y;
  4125. if (other.z < this.z)
  4126. this.z = other.z;
  4127. if (other.w < this.w)
  4128. this.w = other.w;
  4129. return this;
  4130. };
  4131. /**
  4132. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4133. * @param other defines the second operand
  4134. * @returns the current updated Vector4
  4135. */
  4136. Vector4.prototype.maximizeInPlace = function (other) {
  4137. if (other.x > this.x)
  4138. this.x = other.x;
  4139. if (other.y > this.y)
  4140. this.y = other.y;
  4141. if (other.z > this.z)
  4142. this.z = other.z;
  4143. if (other.w > this.w)
  4144. this.w = other.w;
  4145. return this;
  4146. };
  4147. // Properties
  4148. /**
  4149. * Returns the Vector4 length (float).
  4150. */
  4151. Vector4.prototype.length = function () {
  4152. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4153. };
  4154. /**
  4155. * Returns the Vector4 squared length (float).
  4156. */
  4157. Vector4.prototype.lengthSquared = function () {
  4158. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4159. };
  4160. // Methods
  4161. /**
  4162. * Normalizes in place the Vector4.
  4163. * Returns the updated Vector4.
  4164. */
  4165. Vector4.prototype.normalize = function () {
  4166. var len = this.length();
  4167. if (len === 0)
  4168. return this;
  4169. var num = 1.0 / len;
  4170. this.x *= num;
  4171. this.y *= num;
  4172. this.z *= num;
  4173. this.w *= num;
  4174. return this;
  4175. };
  4176. /**
  4177. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4178. */
  4179. Vector4.prototype.toVector3 = function () {
  4180. return new Vector3(this.x, this.y, this.z);
  4181. };
  4182. /**
  4183. * Returns a new Vector4 copied from the current one.
  4184. */
  4185. Vector4.prototype.clone = function () {
  4186. return new Vector4(this.x, this.y, this.z, this.w);
  4187. };
  4188. /**
  4189. * Updates the current Vector4 with the given one coordinates.
  4190. * Returns the updated Vector4.
  4191. */
  4192. Vector4.prototype.copyFrom = function (source) {
  4193. this.x = source.x;
  4194. this.y = source.y;
  4195. this.z = source.z;
  4196. this.w = source.w;
  4197. return this;
  4198. };
  4199. /**
  4200. * Updates the current Vector4 coordinates with the given floats.
  4201. * Returns the updated Vector4.
  4202. */
  4203. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4204. this.x = x;
  4205. this.y = y;
  4206. this.z = z;
  4207. this.w = w;
  4208. return this;
  4209. };
  4210. /**
  4211. * Updates the current Vector4 coordinates with the given floats.
  4212. * Returns the updated Vector4.
  4213. */
  4214. Vector4.prototype.set = function (x, y, z, w) {
  4215. return this.copyFromFloats(x, y, z, w);
  4216. };
  4217. // Statics
  4218. /**
  4219. * Returns a new Vector4 set from the starting index of the given array.
  4220. */
  4221. Vector4.FromArray = function (array, offset) {
  4222. if (!offset) {
  4223. offset = 0;
  4224. }
  4225. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4226. };
  4227. /**
  4228. * Updates the given vector "result" from the starting index of the given array.
  4229. */
  4230. Vector4.FromArrayToRef = function (array, offset, result) {
  4231. result.x = array[offset];
  4232. result.y = array[offset + 1];
  4233. result.z = array[offset + 2];
  4234. result.w = array[offset + 3];
  4235. };
  4236. /**
  4237. * Updates the given vector "result" from the starting index of the given Float32Array.
  4238. */
  4239. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4240. Vector4.FromArrayToRef(array, offset, result);
  4241. };
  4242. /**
  4243. * Updates the given vector "result" coordinates from the given floats.
  4244. */
  4245. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4246. result.x = x;
  4247. result.y = y;
  4248. result.z = z;
  4249. result.w = w;
  4250. };
  4251. /**
  4252. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4253. */
  4254. Vector4.Zero = function () {
  4255. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4256. };
  4257. /**
  4258. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4259. */
  4260. Vector4.One = function () {
  4261. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4262. };
  4263. /**
  4264. * Returns a new normalized Vector4 from the given one.
  4265. */
  4266. Vector4.Normalize = function (vector) {
  4267. var result = Vector4.Zero();
  4268. Vector4.NormalizeToRef(vector, result);
  4269. return result;
  4270. };
  4271. /**
  4272. * Updates the given vector "result" from the normalization of the given one.
  4273. */
  4274. Vector4.NormalizeToRef = function (vector, result) {
  4275. result.copyFrom(vector);
  4276. result.normalize();
  4277. };
  4278. Vector4.Minimize = function (left, right) {
  4279. var min = left.clone();
  4280. min.minimizeInPlace(right);
  4281. return min;
  4282. };
  4283. Vector4.Maximize = function (left, right) {
  4284. var max = left.clone();
  4285. max.maximizeInPlace(right);
  4286. return max;
  4287. };
  4288. /**
  4289. * Returns the distance (float) between the vectors "value1" and "value2".
  4290. */
  4291. Vector4.Distance = function (value1, value2) {
  4292. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4293. };
  4294. /**
  4295. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4296. */
  4297. Vector4.DistanceSquared = function (value1, value2) {
  4298. var x = value1.x - value2.x;
  4299. var y = value1.y - value2.y;
  4300. var z = value1.z - value2.z;
  4301. var w = value1.w - value2.w;
  4302. return (x * x) + (y * y) + (z * z) + (w * w);
  4303. };
  4304. /**
  4305. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4306. */
  4307. Vector4.Center = function (value1, value2) {
  4308. var center = value1.add(value2);
  4309. center.scaleInPlace(0.5);
  4310. return center;
  4311. };
  4312. /**
  4313. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4314. * This methods computes transformed normalized direction vectors only.
  4315. */
  4316. Vector4.TransformNormal = function (vector, transformation) {
  4317. var result = Vector4.Zero();
  4318. Vector4.TransformNormalToRef(vector, transformation, result);
  4319. return result;
  4320. };
  4321. /**
  4322. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4323. * This methods computes transformed normalized direction vectors only.
  4324. */
  4325. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4326. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4327. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4328. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4329. result.x = x;
  4330. result.y = y;
  4331. result.z = z;
  4332. result.w = vector.w;
  4333. };
  4334. /**
  4335. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4336. * This methods computes transformed normalized direction vectors only.
  4337. */
  4338. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4339. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4340. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4341. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4342. result.w = w;
  4343. };
  4344. return Vector4;
  4345. }());
  4346. BABYLON.Vector4 = Vector4;
  4347. var Size = /** @class */ (function () {
  4348. /**
  4349. * Creates a Size object from the given width and height (floats).
  4350. */
  4351. function Size(width, height) {
  4352. this.width = width;
  4353. this.height = height;
  4354. }
  4355. // Returns a string with the Size width and height.
  4356. Size.prototype.toString = function () {
  4357. return "{W: " + this.width + ", H: " + this.height + "}";
  4358. };
  4359. /**
  4360. * Returns the string "Size"
  4361. */
  4362. Size.prototype.getClassName = function () {
  4363. return "Size";
  4364. };
  4365. /**
  4366. * Returns the Size hash code.
  4367. */
  4368. Size.prototype.getHashCode = function () {
  4369. var hash = this.width || 0;
  4370. hash = (hash * 397) ^ (this.height || 0);
  4371. return hash;
  4372. };
  4373. /**
  4374. * Updates the current size from the given one.
  4375. * Returns the updated Size.
  4376. */
  4377. Size.prototype.copyFrom = function (src) {
  4378. this.width = src.width;
  4379. this.height = src.height;
  4380. };
  4381. /**
  4382. * Updates in place the current Size from the given floats.
  4383. * Returns the updated Size.
  4384. */
  4385. Size.prototype.copyFromFloats = function (width, height) {
  4386. this.width = width;
  4387. this.height = height;
  4388. return this;
  4389. };
  4390. /**
  4391. * Updates in place the current Size from the given floats.
  4392. * Returns the updated Size.
  4393. */
  4394. Size.prototype.set = function (width, height) {
  4395. return this.copyFromFloats(width, height);
  4396. };
  4397. /**
  4398. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4399. */
  4400. Size.prototype.multiplyByFloats = function (w, h) {
  4401. return new Size(this.width * w, this.height * h);
  4402. };
  4403. /**
  4404. * Returns a new Size copied from the given one.
  4405. */
  4406. Size.prototype.clone = function () {
  4407. return new Size(this.width, this.height);
  4408. };
  4409. /**
  4410. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4411. */
  4412. Size.prototype.equals = function (other) {
  4413. if (!other) {
  4414. return false;
  4415. }
  4416. return (this.width === other.width) && (this.height === other.height);
  4417. };
  4418. Object.defineProperty(Size.prototype, "surface", {
  4419. /**
  4420. * Returns the surface of the Size : width * height (float).
  4421. */
  4422. get: function () {
  4423. return this.width * this.height;
  4424. },
  4425. enumerable: true,
  4426. configurable: true
  4427. });
  4428. /**
  4429. * Returns a new Size set to (0.0, 0.0)
  4430. */
  4431. Size.Zero = function () {
  4432. return new Size(0.0, 0.0);
  4433. };
  4434. /**
  4435. * Returns a new Size set as the addition result of the current Size and the given one.
  4436. */
  4437. Size.prototype.add = function (otherSize) {
  4438. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4439. return r;
  4440. };
  4441. /**
  4442. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4443. */
  4444. Size.prototype.subtract = function (otherSize) {
  4445. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4446. return r;
  4447. };
  4448. /**
  4449. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4450. */
  4451. Size.Lerp = function (start, end, amount) {
  4452. var w = start.width + ((end.width - start.width) * amount);
  4453. var h = start.height + ((end.height - start.height) * amount);
  4454. return new Size(w, h);
  4455. };
  4456. return Size;
  4457. }());
  4458. BABYLON.Size = Size;
  4459. /**
  4460. * Class used to store quaternion data
  4461. * @see https://en.wikipedia.org/wiki/Quaternion
  4462. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4463. */
  4464. var Quaternion = /** @class */ (function () {
  4465. /**
  4466. * Creates a new Quaternion from the given floats
  4467. * @param x defines the first component (0 by default)
  4468. * @param y defines the second component (0 by default)
  4469. * @param z defines the third component (0 by default)
  4470. * @param w defines the fourth component (1.0 by default)
  4471. */
  4472. function Quaternion(
  4473. /** defines the first component (0 by default) */
  4474. x,
  4475. /** defines the second component (0 by default) */
  4476. y,
  4477. /** defines the third component (0 by default) */
  4478. z,
  4479. /** defines the fourth component (1.0 by default) */
  4480. w) {
  4481. if (x === void 0) { x = 0.0; }
  4482. if (y === void 0) { y = 0.0; }
  4483. if (z === void 0) { z = 0.0; }
  4484. if (w === void 0) { w = 1.0; }
  4485. this.x = x;
  4486. this.y = y;
  4487. this.z = z;
  4488. this.w = w;
  4489. }
  4490. /**
  4491. * Gets a string representation for the current quaternion
  4492. * @returns a string with the Quaternion coordinates
  4493. */
  4494. Quaternion.prototype.toString = function () {
  4495. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4496. };
  4497. /**
  4498. * Gets the class name of the quaternion
  4499. * @returns the string "Quaternion"
  4500. */
  4501. Quaternion.prototype.getClassName = function () {
  4502. return "Quaternion";
  4503. };
  4504. /**
  4505. * Gets a hash code for this quaternion
  4506. * @returns the quaternion hash code
  4507. */
  4508. Quaternion.prototype.getHashCode = function () {
  4509. var hash = this.x || 0;
  4510. hash = (hash * 397) ^ (this.y || 0);
  4511. hash = (hash * 397) ^ (this.z || 0);
  4512. hash = (hash * 397) ^ (this.w || 0);
  4513. return hash;
  4514. };
  4515. /**
  4516. * Copy the quaternion to an array
  4517. * @returns a new array populated with 4 elements from the quaternion coordinates
  4518. */
  4519. Quaternion.prototype.asArray = function () {
  4520. return [this.x, this.y, this.z, this.w];
  4521. };
  4522. /**
  4523. * Check if two quaternions are equals
  4524. * @param otherQuaternion defines the second operand
  4525. * @return true if the current quaternion and the given one coordinates are strictly equals
  4526. */
  4527. Quaternion.prototype.equals = function (otherQuaternion) {
  4528. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4529. };
  4530. /**
  4531. * Clone the current quaternion
  4532. * @returns a new quaternion copied from the current one
  4533. */
  4534. Quaternion.prototype.clone = function () {
  4535. return new Quaternion(this.x, this.y, this.z, this.w);
  4536. };
  4537. /**
  4538. * Copy a quaternion to the current one
  4539. * @param other defines the other quaternion
  4540. * @returns the updated current quaternion
  4541. */
  4542. Quaternion.prototype.copyFrom = function (other) {
  4543. this.x = other.x;
  4544. this.y = other.y;
  4545. this.z = other.z;
  4546. this.w = other.w;
  4547. return this;
  4548. };
  4549. /**
  4550. * Updates the current quaternion with the given float coordinates
  4551. * @param x defines the x coordinate
  4552. * @param y defines the y coordinate
  4553. * @param z defines the z coordinate
  4554. * @param w defines the w coordinate
  4555. * @returns the updated current quaternion
  4556. */
  4557. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4558. this.x = x;
  4559. this.y = y;
  4560. this.z = z;
  4561. this.w = w;
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion from the given float coordinates
  4566. * @param x defines the x coordinate
  4567. * @param y defines the y coordinate
  4568. * @param z defines the z coordinate
  4569. * @param w defines the w coordinate
  4570. * @returns the updated current quaternion
  4571. */
  4572. Quaternion.prototype.set = function (x, y, z, w) {
  4573. return this.copyFromFloats(x, y, z, w);
  4574. };
  4575. /**
  4576. * Adds two quaternions
  4577. * @param other defines the second operand
  4578. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4579. */
  4580. Quaternion.prototype.add = function (other) {
  4581. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4582. };
  4583. /**
  4584. * Add a quaternion to the current one
  4585. * @param other defines the quaternion to add
  4586. * @returns the current quaternion
  4587. */
  4588. Quaternion.prototype.addInPlace = function (other) {
  4589. this.x += other.x;
  4590. this.y += other.y;
  4591. this.z += other.z;
  4592. this.w += other.w;
  4593. return this;
  4594. };
  4595. /**
  4596. * Subtract two quaternions
  4597. * @param other defines the second operand
  4598. * @returns a new quaternion as the subtraction result of the given one from the current one
  4599. */
  4600. Quaternion.prototype.subtract = function (other) {
  4601. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4602. };
  4603. /**
  4604. * Multiplies the current quaternion by a scale factor
  4605. * @param value defines the scale factor
  4606. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4607. */
  4608. Quaternion.prototype.scale = function (value) {
  4609. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4610. };
  4611. /**
  4612. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4613. * @param scale defines the scale factor
  4614. * @param result defines the Quaternion object where to store the result
  4615. * @returns the unmodified current quaternion
  4616. */
  4617. Quaternion.prototype.scaleToRef = function (scale, result) {
  4618. result.x = this.x * scale;
  4619. result.y = this.y * scale;
  4620. result.z = this.z * scale;
  4621. result.w = this.w * scale;
  4622. return this;
  4623. };
  4624. /**
  4625. * Multiplies in place the current quaternion by a scale factor
  4626. * @param value defines the scale factor
  4627. * @returns the current modified quaternion
  4628. */
  4629. Quaternion.prototype.scaleInPlace = function (value) {
  4630. this.x *= value;
  4631. this.y *= value;
  4632. this.z *= value;
  4633. this.w *= value;
  4634. return this;
  4635. };
  4636. /**
  4637. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4638. * @param scale defines the scale factor
  4639. * @param result defines the Quaternion object where to store the result
  4640. * @returns the unmodified current quaternion
  4641. */
  4642. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4643. result.x += this.x * scale;
  4644. result.y += this.y * scale;
  4645. result.z += this.z * scale;
  4646. result.w += this.w * scale;
  4647. return this;
  4648. };
  4649. /**
  4650. * Multiplies two quaternions
  4651. * @param q1 defines the second operand
  4652. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4653. */
  4654. Quaternion.prototype.multiply = function (q1) {
  4655. var result = new Quaternion(0, 0, 0, 1.0);
  4656. this.multiplyToRef(q1, result);
  4657. return result;
  4658. };
  4659. /**
  4660. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4661. * @param q1 defines the second operand
  4662. * @param result defines the target quaternion
  4663. * @returns the current quaternion
  4664. */
  4665. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4666. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4667. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4668. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4669. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4670. result.copyFromFloats(x, y, z, w);
  4671. return this;
  4672. };
  4673. /**
  4674. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4675. * @param q1 defines the second operand
  4676. * @returns the currentupdated quaternion
  4677. */
  4678. Quaternion.prototype.multiplyInPlace = function (q1) {
  4679. this.multiplyToRef(q1, this);
  4680. return this;
  4681. };
  4682. /**
  4683. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4684. * @param ref defines the target quaternion
  4685. * @returns the current quaternion
  4686. */
  4687. Quaternion.prototype.conjugateToRef = function (ref) {
  4688. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4689. return this;
  4690. };
  4691. /**
  4692. * Conjugates in place (1-q) the current quaternion
  4693. * @returns the current updated quaternion
  4694. */
  4695. Quaternion.prototype.conjugateInPlace = function () {
  4696. this.x *= -1;
  4697. this.y *= -1;
  4698. this.z *= -1;
  4699. return this;
  4700. };
  4701. /**
  4702. * Conjugates in place (1-q) the current quaternion
  4703. * @returns a new quaternion
  4704. */
  4705. Quaternion.prototype.conjugate = function () {
  4706. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4707. return result;
  4708. };
  4709. /**
  4710. * Gets length of current quaternion
  4711. * @returns the quaternion length (float)
  4712. */
  4713. Quaternion.prototype.length = function () {
  4714. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4715. };
  4716. /**
  4717. * Normalize in place the current quaternion
  4718. * @returns the current updated quaternion
  4719. */
  4720. Quaternion.prototype.normalize = function () {
  4721. var length = 1.0 / this.length();
  4722. this.x *= length;
  4723. this.y *= length;
  4724. this.z *= length;
  4725. this.w *= length;
  4726. return this;
  4727. };
  4728. /**
  4729. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4730. * @param order is a reserved parameter and is ignore for now
  4731. * @returns a new Vector3 containing the Euler angles
  4732. */
  4733. Quaternion.prototype.toEulerAngles = function (order) {
  4734. if (order === void 0) { order = "YZX"; }
  4735. var result = Vector3.Zero();
  4736. this.toEulerAnglesToRef(result, order);
  4737. return result;
  4738. };
  4739. /**
  4740. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4741. * @param result defines the vector which will be filled with the Euler angles
  4742. * @param order is a reserved parameter and is ignore for now
  4743. * @returns the current unchanged quaternion
  4744. */
  4745. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4746. if (order === void 0) { order = "YZX"; }
  4747. var qz = this.z;
  4748. var qx = this.x;
  4749. var qy = this.y;
  4750. var qw = this.w;
  4751. var sqw = qw * qw;
  4752. var sqz = qz * qz;
  4753. var sqx = qx * qx;
  4754. var sqy = qy * qy;
  4755. var zAxisY = qy * qz - qx * qw;
  4756. var limit = .4999999;
  4757. if (zAxisY < -limit) {
  4758. result.y = 2 * Math.atan2(qy, qw);
  4759. result.x = Math.PI / 2;
  4760. result.z = 0;
  4761. }
  4762. else if (zAxisY > limit) {
  4763. result.y = 2 * Math.atan2(qy, qw);
  4764. result.x = -Math.PI / 2;
  4765. result.z = 0;
  4766. }
  4767. else {
  4768. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4769. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4770. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4771. }
  4772. return this;
  4773. };
  4774. /**
  4775. * Updates the given rotation matrix with the current quaternion values
  4776. * @param result defines the target matrix
  4777. * @returns the current unchanged quaternion
  4778. */
  4779. Quaternion.prototype.toRotationMatrix = function (result) {
  4780. var xx = this.x * this.x;
  4781. var yy = this.y * this.y;
  4782. var zz = this.z * this.z;
  4783. var xy = this.x * this.y;
  4784. var zw = this.z * this.w;
  4785. var zx = this.z * this.x;
  4786. var yw = this.y * this.w;
  4787. var yz = this.y * this.z;
  4788. var xw = this.x * this.w;
  4789. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4790. result.m[1] = 2.0 * (xy + zw);
  4791. result.m[2] = 2.0 * (zx - yw);
  4792. result.m[3] = 0;
  4793. result.m[4] = 2.0 * (xy - zw);
  4794. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4795. result.m[6] = 2.0 * (yz + xw);
  4796. result.m[7] = 0;
  4797. result.m[8] = 2.0 * (zx + yw);
  4798. result.m[9] = 2.0 * (yz - xw);
  4799. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4800. result.m[11] = 0;
  4801. result.m[12] = 0;
  4802. result.m[13] = 0;
  4803. result.m[14] = 0;
  4804. result.m[15] = 1.0;
  4805. result._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Updates the current quaternion from the given rotation matrix values
  4810. * @param matrix defines the source matrix
  4811. * @returns the current updated quaternion
  4812. */
  4813. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4814. Quaternion.FromRotationMatrixToRef(matrix, this);
  4815. return this;
  4816. };
  4817. // Statics
  4818. /**
  4819. * Creates a new quaternion from a rotation matrix
  4820. * @param matrix defines the source matrix
  4821. * @returns a new quaternion created from the given rotation matrix values
  4822. */
  4823. Quaternion.FromRotationMatrix = function (matrix) {
  4824. var result = new Quaternion();
  4825. Quaternion.FromRotationMatrixToRef(matrix, result);
  4826. return result;
  4827. };
  4828. /**
  4829. * Updates the given quaternion with the given rotation matrix values
  4830. * @param matrix defines the source matrix
  4831. * @param result defines the target quaternion
  4832. */
  4833. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4834. var data = matrix.m;
  4835. var m11 = data[0], m12 = data[4], m13 = data[8];
  4836. var m21 = data[1], m22 = data[5], m23 = data[9];
  4837. var m31 = data[2], m32 = data[6], m33 = data[10];
  4838. var trace = m11 + m22 + m33;
  4839. var s;
  4840. if (trace > 0) {
  4841. s = 0.5 / Math.sqrt(trace + 1.0);
  4842. result.w = 0.25 / s;
  4843. result.x = (m32 - m23) * s;
  4844. result.y = (m13 - m31) * s;
  4845. result.z = (m21 - m12) * s;
  4846. }
  4847. else if (m11 > m22 && m11 > m33) {
  4848. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4849. result.w = (m32 - m23) / s;
  4850. result.x = 0.25 * s;
  4851. result.y = (m12 + m21) / s;
  4852. result.z = (m13 + m31) / s;
  4853. }
  4854. else if (m22 > m33) {
  4855. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4856. result.w = (m13 - m31) / s;
  4857. result.x = (m12 + m21) / s;
  4858. result.y = 0.25 * s;
  4859. result.z = (m23 + m32) / s;
  4860. }
  4861. else {
  4862. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4863. result.w = (m21 - m12) / s;
  4864. result.x = (m13 + m31) / s;
  4865. result.y = (m23 + m32) / s;
  4866. result.z = 0.25 * s;
  4867. }
  4868. };
  4869. /**
  4870. * Returns the dot product (float) between the quaternions "left" and "right"
  4871. * @param left defines the left operand
  4872. * @param right defines the right operand
  4873. * @returns the dot product
  4874. */
  4875. Quaternion.Dot = function (left, right) {
  4876. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4877. };
  4878. /**
  4879. * Checks if the two quaternions are close to each other
  4880. * @param quat0 defines the first quaternion to check
  4881. * @param quat1 defines the second quaternion to check
  4882. * @returns true if the two quaternions are close to each other
  4883. */
  4884. Quaternion.AreClose = function (quat0, quat1) {
  4885. var dot = Quaternion.Dot(quat0, quat1);
  4886. return dot >= 0;
  4887. };
  4888. /**
  4889. * Creates an empty quaternion
  4890. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4891. */
  4892. Quaternion.Zero = function () {
  4893. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4894. };
  4895. /**
  4896. * Inverse a given quaternion
  4897. * @param q defines the source quaternion
  4898. * @returns a new quaternion as the inverted current quaternion
  4899. */
  4900. Quaternion.Inverse = function (q) {
  4901. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4902. };
  4903. /**
  4904. * Creates an identity quaternion
  4905. * @returns the identity quaternion
  4906. */
  4907. Quaternion.Identity = function () {
  4908. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4909. };
  4910. /**
  4911. * Gets a boolean indicating if the given quaternion is identity
  4912. * @param quaternion defines the quaternion to check
  4913. * @returns true if the quaternion is identity
  4914. */
  4915. Quaternion.IsIdentity = function (quaternion) {
  4916. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4917. };
  4918. /**
  4919. * Creates a quaternion from a rotation around an axis
  4920. * @param axis defines the axis to use
  4921. * @param angle defines the angle to use
  4922. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4923. */
  4924. Quaternion.RotationAxis = function (axis, angle) {
  4925. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4926. };
  4927. /**
  4928. * Creates a rotation around an axis and stores it into the given quaternion
  4929. * @param axis defines the axis to use
  4930. * @param angle defines the angle to use
  4931. * @param result defines the target quaternion
  4932. * @returns the target quaternion
  4933. */
  4934. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4935. var sin = Math.sin(angle / 2);
  4936. axis.normalize();
  4937. result.w = Math.cos(angle / 2);
  4938. result.x = axis.x * sin;
  4939. result.y = axis.y * sin;
  4940. result.z = axis.z * sin;
  4941. return result;
  4942. };
  4943. /**
  4944. * Creates a new quaternion from data stored into an array
  4945. * @param array defines the data source
  4946. * @param offset defines the offset in the source array where the data starts
  4947. * @returns a new quaternion
  4948. */
  4949. Quaternion.FromArray = function (array, offset) {
  4950. if (!offset) {
  4951. offset = 0;
  4952. }
  4953. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4954. };
  4955. /**
  4956. * Creates a new quaternion from the given Euler float angles (y, x, z)
  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. * @returns the new quaternion
  4961. */
  4962. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4963. var q = new Quaternion();
  4964. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4965. return q;
  4966. };
  4967. /**
  4968. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4969. * @param yaw defines the rotation around Y axis
  4970. * @param pitch defines the rotation around X axis
  4971. * @param roll defines the rotation around Z axis
  4972. * @param result defines the target quaternion
  4973. */
  4974. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4975. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4976. var halfRoll = roll * 0.5;
  4977. var halfPitch = pitch * 0.5;
  4978. var halfYaw = yaw * 0.5;
  4979. var sinRoll = Math.sin(halfRoll);
  4980. var cosRoll = Math.cos(halfRoll);
  4981. var sinPitch = Math.sin(halfPitch);
  4982. var cosPitch = Math.cos(halfPitch);
  4983. var sinYaw = Math.sin(halfYaw);
  4984. var cosYaw = Math.cos(halfYaw);
  4985. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4986. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4987. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4988. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  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. * @returns the new quaternion
  4996. */
  4997. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4998. var result = new Quaternion();
  4999. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5000. return result;
  5001. };
  5002. /**
  5003. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5004. * @param alpha defines the rotation around first axis
  5005. * @param beta defines the rotation around second axis
  5006. * @param gamma defines the rotation around third axis
  5007. * @param result defines the target quaternion
  5008. */
  5009. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5010. // Produces a quaternion from Euler angles in the z-x-z orientation
  5011. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5012. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5013. var halfBeta = beta * 0.5;
  5014. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5015. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5016. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5017. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5018. };
  5019. /**
  5020. * 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)
  5021. * @param axis1 defines the first axis
  5022. * @param axis2 defines the second axis
  5023. * @param axis3 defines the third axis
  5024. * @returns the new quaternion
  5025. */
  5026. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5027. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5028. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5029. return quat;
  5030. };
  5031. /**
  5032. * 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
  5033. * @param axis1 defines the first axis
  5034. * @param axis2 defines the second axis
  5035. * @param axis3 defines the third axis
  5036. * @param ref defines the target quaternion
  5037. */
  5038. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5039. var rotMat = MathTmp.Matrix[0];
  5040. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5041. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5042. };
  5043. /**
  5044. * Interpolates between two quaternions
  5045. * @param left defines first quaternion
  5046. * @param right defines second quaternion
  5047. * @param amount defines the gradient to use
  5048. * @returns the new interpolated quaternion
  5049. */
  5050. Quaternion.Slerp = function (left, right, amount) {
  5051. var result = Quaternion.Identity();
  5052. Quaternion.SlerpToRef(left, right, amount, result);
  5053. return result;
  5054. };
  5055. /**
  5056. * Interpolates between two quaternions and stores it into a target quaternion
  5057. * @param left defines first quaternion
  5058. * @param right defines second quaternion
  5059. * @param amount defines the gradient to use
  5060. * @param result defines the target quaternion
  5061. */
  5062. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5063. var num2;
  5064. var num3;
  5065. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5066. var flag = false;
  5067. if (num4 < 0) {
  5068. flag = true;
  5069. num4 = -num4;
  5070. }
  5071. if (num4 > 0.999999) {
  5072. num3 = 1 - amount;
  5073. num2 = flag ? -amount : amount;
  5074. }
  5075. else {
  5076. var num5 = Math.acos(num4);
  5077. var num6 = (1.0 / Math.sin(num5));
  5078. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5079. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5080. }
  5081. result.x = (num3 * left.x) + (num2 * right.x);
  5082. result.y = (num3 * left.y) + (num2 * right.y);
  5083. result.z = (num3 * left.z) + (num2 * right.z);
  5084. result.w = (num3 * left.w) + (num2 * right.w);
  5085. };
  5086. /**
  5087. * Interpolate between two quaternions using Hermite interpolation
  5088. * @param value1 defines first quaternion
  5089. * @param tangent1 defines the incoming tangent
  5090. * @param value2 defines second quaternion
  5091. * @param tangent2 defines the outgoing tangent
  5092. * @param amount defines the target quaternion
  5093. * @returns the new interpolated quaternion
  5094. */
  5095. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5096. var squared = amount * amount;
  5097. var cubed = amount * squared;
  5098. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5099. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5100. var part3 = (cubed - (2.0 * squared)) + amount;
  5101. var part4 = cubed - squared;
  5102. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5103. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5104. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5105. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5106. return new Quaternion(x, y, z, w);
  5107. };
  5108. return Quaternion;
  5109. }());
  5110. BABYLON.Quaternion = Quaternion;
  5111. /**
  5112. * Class used to store matrix data (4x4)
  5113. */
  5114. var Matrix = /** @class */ (function () {
  5115. /**
  5116. * Creates an empty matrix (filled with zeros)
  5117. */
  5118. function Matrix() {
  5119. this._isIdentity = false;
  5120. this._isIdentityDirty = true;
  5121. /**
  5122. * Gets or sets the internal data of the matrix
  5123. */
  5124. this.m = new Float32Array(16);
  5125. this._markAsUpdated();
  5126. }
  5127. /** @hidden */
  5128. Matrix.prototype._markAsUpdated = function () {
  5129. this.updateFlag = Matrix._updateFlagSeed++;
  5130. this._isIdentityDirty = true;
  5131. };
  5132. // Properties
  5133. /**
  5134. * Check if the current matrix is indentity
  5135. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5136. * @returns true is the matrix is the identity matrix
  5137. */
  5138. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5139. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5140. if (this._isIdentityDirty) {
  5141. this._isIdentityDirty = false;
  5142. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5143. this._isIdentity = false;
  5144. }
  5145. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5146. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5147. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5148. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5149. this._isIdentity = false;
  5150. }
  5151. else {
  5152. this._isIdentity = true;
  5153. }
  5154. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5155. this._isIdentity = false;
  5156. }
  5157. }
  5158. return this._isIdentity;
  5159. };
  5160. /**
  5161. * Gets the determinant of the matrix
  5162. * @returns the matrix determinant
  5163. */
  5164. Matrix.prototype.determinant = function () {
  5165. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5166. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5167. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5168. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5169. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5170. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5171. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5172. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5173. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5174. };
  5175. // Methods
  5176. /**
  5177. * Returns the matrix as a Float32Array
  5178. * @returns the matrix underlying array
  5179. */
  5180. Matrix.prototype.toArray = function () {
  5181. return this.m;
  5182. };
  5183. /**
  5184. * Returns the matrix as a Float32Array
  5185. * @returns the matrix underlying array.
  5186. */
  5187. Matrix.prototype.asArray = function () {
  5188. return this.toArray();
  5189. };
  5190. /**
  5191. * Inverts the current matrix in place
  5192. * @returns the current inverted matrix
  5193. */
  5194. Matrix.prototype.invert = function () {
  5195. this.invertToRef(this);
  5196. return this;
  5197. };
  5198. /**
  5199. * Sets all the matrix elements to zero
  5200. * @returns the current matrix
  5201. */
  5202. Matrix.prototype.reset = function () {
  5203. for (var index = 0; index < 16; index++) {
  5204. this.m[index] = 0.0;
  5205. }
  5206. this._markAsUpdated();
  5207. return this;
  5208. };
  5209. /**
  5210. * Adds the current matrix with a second one
  5211. * @param other defines the matrix to add
  5212. * @returns a new matrix as the addition of the current matrix and the given one
  5213. */
  5214. Matrix.prototype.add = function (other) {
  5215. var result = new Matrix();
  5216. this.addToRef(other, result);
  5217. return result;
  5218. };
  5219. /**
  5220. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5221. * @param other defines the matrix to add
  5222. * @param result defines the target matrix
  5223. * @returns the current matrix
  5224. */
  5225. Matrix.prototype.addToRef = function (other, result) {
  5226. for (var index = 0; index < 16; index++) {
  5227. result.m[index] = this.m[index] + other.m[index];
  5228. }
  5229. result._markAsUpdated();
  5230. return this;
  5231. };
  5232. /**
  5233. * Adds in place the given matrix to the current matrix
  5234. * @param other defines the second operand
  5235. * @returns the current updated matrix
  5236. */
  5237. Matrix.prototype.addToSelf = function (other) {
  5238. for (var index = 0; index < 16; index++) {
  5239. this.m[index] += other.m[index];
  5240. }
  5241. this._markAsUpdated();
  5242. return this;
  5243. };
  5244. /**
  5245. * Sets the given matrix to the current inverted Matrix
  5246. * @param other defines the target matrix
  5247. * @returns the unmodified current matrix
  5248. */
  5249. Matrix.prototype.invertToRef = function (other) {
  5250. var l1 = this.m[0];
  5251. var l2 = this.m[1];
  5252. var l3 = this.m[2];
  5253. var l4 = this.m[3];
  5254. var l5 = this.m[4];
  5255. var l6 = this.m[5];
  5256. var l7 = this.m[6];
  5257. var l8 = this.m[7];
  5258. var l9 = this.m[8];
  5259. var l10 = this.m[9];
  5260. var l11 = this.m[10];
  5261. var l12 = this.m[11];
  5262. var l13 = this.m[12];
  5263. var l14 = this.m[13];
  5264. var l15 = this.m[14];
  5265. var l16 = this.m[15];
  5266. var l17 = (l11 * l16) - (l12 * l15);
  5267. var l18 = (l10 * l16) - (l12 * l14);
  5268. var l19 = (l10 * l15) - (l11 * l14);
  5269. var l20 = (l9 * l16) - (l12 * l13);
  5270. var l21 = (l9 * l15) - (l11 * l13);
  5271. var l22 = (l9 * l14) - (l10 * l13);
  5272. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5273. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5274. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5275. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5276. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5277. var l28 = (l7 * l16) - (l8 * l15);
  5278. var l29 = (l6 * l16) - (l8 * l14);
  5279. var l30 = (l6 * l15) - (l7 * l14);
  5280. var l31 = (l5 * l16) - (l8 * l13);
  5281. var l32 = (l5 * l15) - (l7 * l13);
  5282. var l33 = (l5 * l14) - (l6 * l13);
  5283. var l34 = (l7 * l12) - (l8 * l11);
  5284. var l35 = (l6 * l12) - (l8 * l10);
  5285. var l36 = (l6 * l11) - (l7 * l10);
  5286. var l37 = (l5 * l12) - (l8 * l9);
  5287. var l38 = (l5 * l11) - (l7 * l9);
  5288. var l39 = (l5 * l10) - (l6 * l9);
  5289. other.m[0] = l23 * l27;
  5290. other.m[4] = l24 * l27;
  5291. other.m[8] = l25 * l27;
  5292. other.m[12] = l26 * l27;
  5293. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5294. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5295. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5296. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5297. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5298. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5299. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5300. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5301. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5302. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5303. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5304. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5305. other._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Inserts the translation vector (using 3 floats) in the current matrix
  5310. * @param x defines the 1st component of the translation
  5311. * @param y defines the 2nd component of the translation
  5312. * @param z defines the 3rd component of the translation
  5313. * @returns the current updated matrix
  5314. */
  5315. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5316. this.m[12] = x;
  5317. this.m[13] = y;
  5318. this.m[14] = z;
  5319. this._markAsUpdated();
  5320. return this;
  5321. };
  5322. /**
  5323. * Inserts the translation vector in the current matrix
  5324. * @param vector3 defines the translation to insert
  5325. * @returns the current updated matrix
  5326. */
  5327. Matrix.prototype.setTranslation = function (vector3) {
  5328. this.m[12] = vector3.x;
  5329. this.m[13] = vector3.y;
  5330. this.m[14] = vector3.z;
  5331. this._markAsUpdated();
  5332. return this;
  5333. };
  5334. /**
  5335. * Gets the translation value of the current matrix
  5336. * @returns a new Vector3 as the extracted translation from the matrix
  5337. */
  5338. Matrix.prototype.getTranslation = function () {
  5339. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5340. };
  5341. /**
  5342. * Fill a Vector3 with the extracted translation from the matrix
  5343. * @param result defines the Vector3 where to store the translation
  5344. * @returns the current matrix
  5345. */
  5346. Matrix.prototype.getTranslationToRef = function (result) {
  5347. result.x = this.m[12];
  5348. result.y = this.m[13];
  5349. result.z = this.m[14];
  5350. return this;
  5351. };
  5352. /**
  5353. * Remove rotation and scaling part from the matrix
  5354. * @returns the updated matrix
  5355. */
  5356. Matrix.prototype.removeRotationAndScaling = function () {
  5357. this.setRowFromFloats(0, 1, 0, 0, 0);
  5358. this.setRowFromFloats(1, 0, 1, 0, 0);
  5359. this.setRowFromFloats(2, 0, 0, 1, 0);
  5360. return this;
  5361. };
  5362. /**
  5363. * Multiply two matrices
  5364. * @param other defines the second operand
  5365. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5366. */
  5367. Matrix.prototype.multiply = function (other) {
  5368. var result = new Matrix();
  5369. this.multiplyToRef(other, result);
  5370. return result;
  5371. };
  5372. /**
  5373. * Copy the current matrix from the given one
  5374. * @param other defines the source matrix
  5375. * @returns the current updated matrix
  5376. */
  5377. Matrix.prototype.copyFrom = function (other) {
  5378. for (var index = 0; index < 16; index++) {
  5379. this.m[index] = other.m[index];
  5380. }
  5381. this._markAsUpdated();
  5382. return this;
  5383. };
  5384. /**
  5385. * Populates the given array from the starting index with the current matrix values
  5386. * @param array defines the target array
  5387. * @param offset defines the offset in the target array where to start storing values
  5388. * @returns the current matrix
  5389. */
  5390. Matrix.prototype.copyToArray = function (array, offset) {
  5391. if (offset === void 0) { offset = 0; }
  5392. for (var index = 0; index < 16; index++) {
  5393. array[offset + index] = this.m[index];
  5394. }
  5395. return this;
  5396. };
  5397. /**
  5398. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5399. * @param other defines the second operand
  5400. * @param result defines the matrix where to store the multiplication
  5401. * @returns the current matrix
  5402. */
  5403. Matrix.prototype.multiplyToRef = function (other, result) {
  5404. this.multiplyToArray(other, result.m, 0);
  5405. result._markAsUpdated();
  5406. return this;
  5407. };
  5408. /**
  5409. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5410. * @param other defines the second operand
  5411. * @param result defines the array where to store the multiplication
  5412. * @param offset defines the offset in the target array where to start storing values
  5413. * @returns the current matrix
  5414. */
  5415. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5416. var tm0 = this.m[0];
  5417. var tm1 = this.m[1];
  5418. var tm2 = this.m[2];
  5419. var tm3 = this.m[3];
  5420. var tm4 = this.m[4];
  5421. var tm5 = this.m[5];
  5422. var tm6 = this.m[6];
  5423. var tm7 = this.m[7];
  5424. var tm8 = this.m[8];
  5425. var tm9 = this.m[9];
  5426. var tm10 = this.m[10];
  5427. var tm11 = this.m[11];
  5428. var tm12 = this.m[12];
  5429. var tm13 = this.m[13];
  5430. var tm14 = this.m[14];
  5431. var tm15 = this.m[15];
  5432. var om0 = other.m[0];
  5433. var om1 = other.m[1];
  5434. var om2 = other.m[2];
  5435. var om3 = other.m[3];
  5436. var om4 = other.m[4];
  5437. var om5 = other.m[5];
  5438. var om6 = other.m[6];
  5439. var om7 = other.m[7];
  5440. var om8 = other.m[8];
  5441. var om9 = other.m[9];
  5442. var om10 = other.m[10];
  5443. var om11 = other.m[11];
  5444. var om12 = other.m[12];
  5445. var om13 = other.m[13];
  5446. var om14 = other.m[14];
  5447. var om15 = other.m[15];
  5448. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5449. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5450. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5451. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5452. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5453. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5454. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5455. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5456. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5457. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5458. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5459. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5460. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5461. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5462. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5463. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5464. return this;
  5465. };
  5466. /**
  5467. * Check equality between this matrix and a second one
  5468. * @param value defines the second matrix to compare
  5469. * @returns true is the current matrix and the given one values are strictly equal
  5470. */
  5471. Matrix.prototype.equals = function (value) {
  5472. return value &&
  5473. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5474. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5475. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5476. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5477. };
  5478. /**
  5479. * Clone the current matrix
  5480. * @returns a new matrix from the current matrix
  5481. */
  5482. Matrix.prototype.clone = function () {
  5483. 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]);
  5484. };
  5485. /**
  5486. * Returns the name of the current matrix class
  5487. * @returns the string "Matrix"
  5488. */
  5489. Matrix.prototype.getClassName = function () {
  5490. return "Matrix";
  5491. };
  5492. /**
  5493. * Gets the hash code of the current matrix
  5494. * @returns the hash code
  5495. */
  5496. Matrix.prototype.getHashCode = function () {
  5497. var hash = this.m[0] || 0;
  5498. for (var i = 1; i < 16; i++) {
  5499. hash = (hash * 397) ^ (this.m[i] || 0);
  5500. }
  5501. return hash;
  5502. };
  5503. /**
  5504. * Decomposes the current Matrix into a translation, rotation and scaling components
  5505. * @param scale defines the scale vector3 given as a reference to update
  5506. * @param rotation defines the rotation quaternion given as a reference to update
  5507. * @param translation defines the translation vector3 given as a reference to update
  5508. * @returns true if operation was successful
  5509. */
  5510. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5511. if (translation) {
  5512. translation.x = this.m[12];
  5513. translation.y = this.m[13];
  5514. translation.z = this.m[14];
  5515. }
  5516. scale = scale || MathTmp.Vector3[0];
  5517. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5518. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5519. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5520. if (this.determinant() <= 0) {
  5521. scale.y *= -1;
  5522. }
  5523. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5524. if (rotation) {
  5525. rotation.x = 0;
  5526. rotation.y = 0;
  5527. rotation.z = 0;
  5528. rotation.w = 1;
  5529. }
  5530. return false;
  5531. }
  5532. if (rotation) {
  5533. 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]);
  5534. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5535. }
  5536. return true;
  5537. };
  5538. /**
  5539. * Gets specific row of the matrix
  5540. * @param index defines the number of the row to get
  5541. * @returns the index-th row of the current matrix as a new Vector4
  5542. */
  5543. Matrix.prototype.getRow = function (index) {
  5544. if (index < 0 || index > 3) {
  5545. return null;
  5546. }
  5547. var i = index * 4;
  5548. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5549. };
  5550. /**
  5551. * Sets the index-th row of the current matrix to the vector4 values
  5552. * @param index defines the number of the row to set
  5553. * @param row defines the target vector4
  5554. * @returns the updated current matrix
  5555. */
  5556. Matrix.prototype.setRow = function (index, row) {
  5557. if (index < 0 || index > 3) {
  5558. return this;
  5559. }
  5560. var i = index * 4;
  5561. this.m[i + 0] = row.x;
  5562. this.m[i + 1] = row.y;
  5563. this.m[i + 2] = row.z;
  5564. this.m[i + 3] = row.w;
  5565. this._markAsUpdated();
  5566. return this;
  5567. };
  5568. /**
  5569. * Compute the transpose of the matrix
  5570. * @returns the new transposed matrix
  5571. */
  5572. Matrix.prototype.transpose = function () {
  5573. return Matrix.Transpose(this);
  5574. };
  5575. /**
  5576. * Compute the transpose of the matrix and store it in a given matrix
  5577. * @param result defines the target matrix
  5578. * @returns the current matrix
  5579. */
  5580. Matrix.prototype.transposeToRef = function (result) {
  5581. Matrix.TransposeToRef(this, result);
  5582. return this;
  5583. };
  5584. /**
  5585. * Sets the index-th row of the current matrix with the given 4 x float values
  5586. * @param index defines the row index
  5587. * @param x defines the x component to set
  5588. * @param y defines the y component to set
  5589. * @param z defines the z component to set
  5590. * @param w defines the w component to set
  5591. * @returns the updated current matrix
  5592. */
  5593. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5594. if (index < 0 || index > 3) {
  5595. return this;
  5596. }
  5597. var i = index * 4;
  5598. this.m[i + 0] = x;
  5599. this.m[i + 1] = y;
  5600. this.m[i + 2] = z;
  5601. this.m[i + 3] = w;
  5602. this._markAsUpdated();
  5603. return this;
  5604. };
  5605. /**
  5606. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5607. * @param scale defines the scale factor
  5608. * @returns a new matrix
  5609. */
  5610. Matrix.prototype.scale = function (scale) {
  5611. var result = new Matrix();
  5612. this.scaleToRef(scale, result);
  5613. return result;
  5614. };
  5615. /**
  5616. * Scale the current matrix values by a factor to a given result matrix
  5617. * @param scale defines the scale factor
  5618. * @param result defines the matrix to store the result
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.scaleToRef = function (scale, result) {
  5622. for (var index = 0; index < 16; index++) {
  5623. result.m[index] = this.m[index] * scale;
  5624. }
  5625. result._markAsUpdated();
  5626. return this;
  5627. };
  5628. /**
  5629. * Scale the current matrix values by a factor and add the result to a given matrix
  5630. * @param scale defines the scale factor
  5631. * @param result defines the Matrix to store the result
  5632. * @returns the current matrix
  5633. */
  5634. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5635. for (var index = 0; index < 16; index++) {
  5636. result.m[index] += this.m[index] * scale;
  5637. }
  5638. result._markAsUpdated();
  5639. return this;
  5640. };
  5641. /**
  5642. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5643. * @param ref matrix to store the result
  5644. */
  5645. Matrix.prototype.toNormalMatrix = function (ref) {
  5646. this.invertToRef(ref);
  5647. ref.transpose();
  5648. var m = ref.m;
  5649. 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);
  5650. };
  5651. /**
  5652. * Gets only rotation part of the current matrix
  5653. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5654. */
  5655. Matrix.prototype.getRotationMatrix = function () {
  5656. var result = Matrix.Identity();
  5657. this.getRotationMatrixToRef(result);
  5658. return result;
  5659. };
  5660. /**
  5661. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5662. * @param result defines the target matrix to store data to
  5663. * @returns the current matrix
  5664. */
  5665. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5666. var m = this.m;
  5667. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5668. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5669. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5670. if (this.determinant() <= 0) {
  5671. sy *= -1;
  5672. }
  5673. if (sx === 0 || sy === 0 || sz === 0) {
  5674. Matrix.IdentityToRef(result);
  5675. }
  5676. else {
  5677. 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);
  5678. }
  5679. return this;
  5680. };
  5681. // Statics
  5682. /**
  5683. * Creates a matrix from an array
  5684. * @param array defines the source array
  5685. * @param offset defines an offset in the source array
  5686. * @returns a new Matrix set from the starting index of the given array
  5687. */
  5688. Matrix.FromArray = function (array, offset) {
  5689. var result = new Matrix();
  5690. if (!offset) {
  5691. offset = 0;
  5692. }
  5693. Matrix.FromArrayToRef(array, offset, result);
  5694. return result;
  5695. };
  5696. /**
  5697. * Copy the content of an array into a given matrix
  5698. * @param array defines the source array
  5699. * @param offset defines an offset in the source array
  5700. * @param result defines the target matrix
  5701. */
  5702. Matrix.FromArrayToRef = function (array, offset, result) {
  5703. for (var index = 0; index < 16; index++) {
  5704. result.m[index] = array[index + offset];
  5705. }
  5706. result._markAsUpdated();
  5707. };
  5708. /**
  5709. * Stores an array into a matrix after having multiplied each component by a given factor
  5710. * @param array defines the source array
  5711. * @param offset defines the offset in the source array
  5712. * @param scale defines the scaling factor
  5713. * @param result defines the target matrix
  5714. */
  5715. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5716. for (var index = 0; index < 16; index++) {
  5717. result.m[index] = array[index + offset] * scale;
  5718. }
  5719. result._markAsUpdated();
  5720. };
  5721. /**
  5722. * Stores a list of values (16) inside a given matrix
  5723. * @param initialM11 defines 1st value of 1st row
  5724. * @param initialM12 defines 2nd value of 1st row
  5725. * @param initialM13 defines 3rd value of 1st row
  5726. * @param initialM14 defines 4th value of 1st row
  5727. * @param initialM21 defines 1st value of 2nd row
  5728. * @param initialM22 defines 2nd value of 2nd row
  5729. * @param initialM23 defines 3rd value of 2nd row
  5730. * @param initialM24 defines 4th value of 2nd row
  5731. * @param initialM31 defines 1st value of 3rd row
  5732. * @param initialM32 defines 2nd value of 3rd row
  5733. * @param initialM33 defines 3rd value of 3rd row
  5734. * @param initialM34 defines 4th value of 3rd row
  5735. * @param initialM41 defines 1st value of 4th row
  5736. * @param initialM42 defines 2nd value of 4th row
  5737. * @param initialM43 defines 3rd value of 4th row
  5738. * @param initialM44 defines 4th value of 4th row
  5739. * @param result defines the target matrix
  5740. */
  5741. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5742. result.m[0] = initialM11;
  5743. result.m[1] = initialM12;
  5744. result.m[2] = initialM13;
  5745. result.m[3] = initialM14;
  5746. result.m[4] = initialM21;
  5747. result.m[5] = initialM22;
  5748. result.m[6] = initialM23;
  5749. result.m[7] = initialM24;
  5750. result.m[8] = initialM31;
  5751. result.m[9] = initialM32;
  5752. result.m[10] = initialM33;
  5753. result.m[11] = initialM34;
  5754. result.m[12] = initialM41;
  5755. result.m[13] = initialM42;
  5756. result.m[14] = initialM43;
  5757. result.m[15] = initialM44;
  5758. result._markAsUpdated();
  5759. };
  5760. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5761. /**
  5762. * Gets an identity matrix that must not be updated
  5763. */
  5764. get: function () {
  5765. return Matrix._identityReadOnly;
  5766. },
  5767. enumerable: true,
  5768. configurable: true
  5769. });
  5770. /**
  5771. * Creates new matrix from a list of values (16)
  5772. * @param initialM11 defines 1st value of 1st row
  5773. * @param initialM12 defines 2nd value of 1st row
  5774. * @param initialM13 defines 3rd value of 1st row
  5775. * @param initialM14 defines 4th value of 1st row
  5776. * @param initialM21 defines 1st value of 2nd row
  5777. * @param initialM22 defines 2nd value of 2nd row
  5778. * @param initialM23 defines 3rd value of 2nd row
  5779. * @param initialM24 defines 4th value of 2nd row
  5780. * @param initialM31 defines 1st value of 3rd row
  5781. * @param initialM32 defines 2nd value of 3rd row
  5782. * @param initialM33 defines 3rd value of 3rd row
  5783. * @param initialM34 defines 4th value of 3rd row
  5784. * @param initialM41 defines 1st value of 4th row
  5785. * @param initialM42 defines 2nd value of 4th row
  5786. * @param initialM43 defines 3rd value of 4th row
  5787. * @param initialM44 defines 4th value of 4th row
  5788. * @returns the new matrix
  5789. */
  5790. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5791. var result = new Matrix();
  5792. result.m[0] = initialM11;
  5793. result.m[1] = initialM12;
  5794. result.m[2] = initialM13;
  5795. result.m[3] = initialM14;
  5796. result.m[4] = initialM21;
  5797. result.m[5] = initialM22;
  5798. result.m[6] = initialM23;
  5799. result.m[7] = initialM24;
  5800. result.m[8] = initialM31;
  5801. result.m[9] = initialM32;
  5802. result.m[10] = initialM33;
  5803. result.m[11] = initialM34;
  5804. result.m[12] = initialM41;
  5805. result.m[13] = initialM42;
  5806. result.m[14] = initialM43;
  5807. result.m[15] = initialM44;
  5808. return result;
  5809. };
  5810. /**
  5811. * Creates a new matrix 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. * @returns a new matrix
  5816. */
  5817. Matrix.Compose = function (scale, rotation, translation) {
  5818. var result = Matrix.Identity();
  5819. Matrix.ComposeToRef(scale, rotation, translation, result);
  5820. return result;
  5821. };
  5822. /**
  5823. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5824. * @param scale defines the scale vector3
  5825. * @param rotation defines the rotation quaternion
  5826. * @param translation defines the translation vector3
  5827. * @param result defines the target matrix
  5828. */
  5829. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5830. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5831. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5832. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5833. result.setTranslation(translation);
  5834. };
  5835. /**
  5836. * Creates a new identity matrix
  5837. * @returns a new identity matrix
  5838. */
  5839. Matrix.Identity = function () {
  5840. 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);
  5841. };
  5842. /**
  5843. * Creates a new identity matrix and stores the result in a given matrix
  5844. * @param result defines the target matrix
  5845. */
  5846. Matrix.IdentityToRef = function (result) {
  5847. 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);
  5848. };
  5849. /**
  5850. * Creates a new zero matrix
  5851. * @returns a new zero matrix
  5852. */
  5853. Matrix.Zero = function () {
  5854. 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);
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the X axis
  5858. * @param angle defines the angle (in radians) to use
  5859. * @return the new matrix
  5860. */
  5861. Matrix.RotationX = function (angle) {
  5862. var result = new Matrix();
  5863. Matrix.RotationXToRef(angle, result);
  5864. return result;
  5865. };
  5866. /**
  5867. * Creates a new matrix as the invert of a given matrix
  5868. * @param source defines the source matrix
  5869. * @returns the new matrix
  5870. */
  5871. Matrix.Invert = function (source) {
  5872. var result = new Matrix();
  5873. source.invertToRef(result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5878. * @param angle defines the angle (in radians) to use
  5879. * @param result defines the target matrix
  5880. */
  5881. Matrix.RotationXToRef = function (angle, result) {
  5882. var s = Math.sin(angle);
  5883. var c = Math.cos(angle);
  5884. result.m[0] = 1.0;
  5885. result.m[15] = 1.0;
  5886. result.m[5] = c;
  5887. result.m[10] = c;
  5888. result.m[9] = -s;
  5889. result.m[6] = s;
  5890. result.m[1] = 0.0;
  5891. result.m[2] = 0.0;
  5892. result.m[3] = 0.0;
  5893. result.m[4] = 0.0;
  5894. result.m[7] = 0.0;
  5895. result.m[8] = 0.0;
  5896. result.m[11] = 0.0;
  5897. result.m[12] = 0.0;
  5898. result.m[13] = 0.0;
  5899. result.m[14] = 0.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a new rotation matrix for "angle" radians around the Y axis
  5904. * @param angle defines the angle (in radians) to use
  5905. * @return the new matrix
  5906. */
  5907. Matrix.RotationY = function (angle) {
  5908. var result = new Matrix();
  5909. Matrix.RotationYToRef(angle, result);
  5910. return result;
  5911. };
  5912. /**
  5913. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5914. * @param angle defines the angle (in radians) to use
  5915. * @param result defines the target matrix
  5916. */
  5917. Matrix.RotationYToRef = function (angle, result) {
  5918. var s = Math.sin(angle);
  5919. var c = Math.cos(angle);
  5920. result.m[5] = 1.0;
  5921. result.m[15] = 1.0;
  5922. result.m[0] = c;
  5923. result.m[2] = -s;
  5924. result.m[8] = s;
  5925. result.m[10] = c;
  5926. result.m[1] = 0.0;
  5927. result.m[3] = 0.0;
  5928. result.m[4] = 0.0;
  5929. result.m[6] = 0.0;
  5930. result.m[7] = 0.0;
  5931. result.m[9] = 0.0;
  5932. result.m[11] = 0.0;
  5933. result.m[12] = 0.0;
  5934. result.m[13] = 0.0;
  5935. result.m[14] = 0.0;
  5936. result._markAsUpdated();
  5937. };
  5938. /**
  5939. * Creates a new rotation matrix for "angle" radians around the Z axis
  5940. * @param angle defines the angle (in radians) to use
  5941. * @return the new matrix
  5942. */
  5943. Matrix.RotationZ = function (angle) {
  5944. var result = new Matrix();
  5945. Matrix.RotationZToRef(angle, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5950. * @param angle defines the angle (in radians) to use
  5951. * @param result defines the target matrix
  5952. */
  5953. Matrix.RotationZToRef = function (angle, result) {
  5954. var s = Math.sin(angle);
  5955. var c = Math.cos(angle);
  5956. result.m[10] = 1.0;
  5957. result.m[15] = 1.0;
  5958. result.m[0] = c;
  5959. result.m[1] = s;
  5960. result.m[4] = -s;
  5961. result.m[5] = c;
  5962. result.m[2] = 0.0;
  5963. result.m[3] = 0.0;
  5964. result.m[6] = 0.0;
  5965. result.m[7] = 0.0;
  5966. result.m[8] = 0.0;
  5967. result.m[9] = 0.0;
  5968. result.m[11] = 0.0;
  5969. result.m[12] = 0.0;
  5970. result.m[13] = 0.0;
  5971. result.m[14] = 0.0;
  5972. result._markAsUpdated();
  5973. };
  5974. /**
  5975. * Creates a new rotation matrix for "angle" radians around the given axis
  5976. * @param axis defines the axis to use
  5977. * @param angle defines the angle (in radians) to use
  5978. * @return the new matrix
  5979. */
  5980. Matrix.RotationAxis = function (axis, angle) {
  5981. var result = Matrix.Zero();
  5982. Matrix.RotationAxisToRef(axis, angle, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5987. * @param axis defines the axis to use
  5988. * @param angle defines the angle (in radians) to use
  5989. * @param result defines the target matrix
  5990. */
  5991. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5992. var s = Math.sin(-angle);
  5993. var c = Math.cos(-angle);
  5994. var c1 = 1 - c;
  5995. axis.normalize();
  5996. result.m[0] = (axis.x * axis.x) * c1 + c;
  5997. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5998. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5999. result.m[3] = 0.0;
  6000. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6001. result.m[5] = (axis.y * axis.y) * c1 + c;
  6002. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6003. result.m[7] = 0.0;
  6004. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6005. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6006. result.m[10] = (axis.z * axis.z) * c1 + c;
  6007. result.m[11] = 0.0;
  6008. result.m[15] = 1.0;
  6009. result._markAsUpdated();
  6010. };
  6011. /**
  6012. * Creates a rotation 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. * @returns the new rotation matrix
  6017. */
  6018. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6019. var result = new Matrix();
  6020. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6021. return result;
  6022. };
  6023. /**
  6024. * Creates a rotation matrix and stores it in a given matrix
  6025. * @param yaw defines the yaw angle in radians (Y axis)
  6026. * @param pitch defines the pitch angle in radians (X axis)
  6027. * @param roll defines the roll angle in radians (X axis)
  6028. * @param result defines the target matrix
  6029. */
  6030. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6031. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6032. this._tempQuaternion.toRotationMatrix(result);
  6033. };
  6034. /**
  6035. * Creates a scaling 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. * @returns the new matrix
  6040. */
  6041. Matrix.Scaling = function (x, y, z) {
  6042. var result = Matrix.Zero();
  6043. Matrix.ScalingToRef(x, y, z, result);
  6044. return result;
  6045. };
  6046. /**
  6047. * Creates a scaling matrix and stores it in a given matrix
  6048. * @param x defines the scale factor on X axis
  6049. * @param y defines the scale factor on Y axis
  6050. * @param z defines the scale factor on Z axis
  6051. * @param result defines the target matrix
  6052. */
  6053. Matrix.ScalingToRef = function (x, y, z, result) {
  6054. result.m[0] = x;
  6055. result.m[1] = 0.0;
  6056. result.m[2] = 0.0;
  6057. result.m[3] = 0.0;
  6058. result.m[4] = 0.0;
  6059. result.m[5] = y;
  6060. result.m[6] = 0.0;
  6061. result.m[7] = 0.0;
  6062. result.m[8] = 0.0;
  6063. result.m[9] = 0.0;
  6064. result.m[10] = z;
  6065. result.m[11] = 0.0;
  6066. result.m[12] = 0.0;
  6067. result.m[13] = 0.0;
  6068. result.m[14] = 0.0;
  6069. result.m[15] = 1.0;
  6070. result._markAsUpdated();
  6071. };
  6072. /**
  6073. * Creates a translation 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. * @returns the new matrix
  6078. */
  6079. Matrix.Translation = function (x, y, z) {
  6080. var result = Matrix.Identity();
  6081. Matrix.TranslationToRef(x, y, z, result);
  6082. return result;
  6083. };
  6084. /**
  6085. * Creates a translation matrix and stores it in a given matrix
  6086. * @param x defines the translation on X axis
  6087. * @param y defines the translation on Y axis
  6088. * @param z defines the translationon Z axis
  6089. * @param result defines the target matrix
  6090. */
  6091. Matrix.TranslationToRef = function (x, y, z, result) {
  6092. 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);
  6093. };
  6094. /**
  6095. * Returns a new Matrix whose values are 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. * @returns the new matrix
  6100. */
  6101. Matrix.Lerp = function (startValue, endValue, gradient) {
  6102. var result = Matrix.Zero();
  6103. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6104. return result;
  6105. };
  6106. /**
  6107. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6108. * @param startValue defines the start value
  6109. * @param endValue defines the end value
  6110. * @param gradient defines the gradient factor
  6111. * @param result defines the Matrix object where to store data
  6112. */
  6113. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6114. for (var index = 0; index < 16; index++) {
  6115. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6116. }
  6117. result._markAsUpdated();
  6118. };
  6119. /**
  6120. * Builds a new matrix whose values are computed by:
  6121. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6122. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6123. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6124. * @param startValue defines the first matrix
  6125. * @param endValue defines the second matrix
  6126. * @param gradient defines the gradient between the two matrices
  6127. * @returns the new matrix
  6128. */
  6129. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6130. var result = Matrix.Zero();
  6131. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6132. return result;
  6133. };
  6134. /**
  6135. * Update a matrix to values which are computed by:
  6136. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6137. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6138. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6139. * @param startValue defines the first matrix
  6140. * @param endValue defines the second matrix
  6141. * @param gradient defines the gradient between the two matrices
  6142. * @param result defines the target matrix
  6143. */
  6144. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6145. var startScale = MathTmp.Vector3[0];
  6146. var startRotation = MathTmp.Quaternion[0];
  6147. var startTranslation = MathTmp.Vector3[1];
  6148. startValue.decompose(startScale, startRotation, startTranslation);
  6149. var endScale = MathTmp.Vector3[2];
  6150. var endRotation = MathTmp.Quaternion[1];
  6151. var endTranslation = MathTmp.Vector3[3];
  6152. endValue.decompose(endScale, endRotation, endTranslation);
  6153. var resultScale = MathTmp.Vector3[4];
  6154. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6155. var resultRotation = MathTmp.Quaternion[2];
  6156. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6157. var resultTranslation = MathTmp.Vector3[5];
  6158. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6159. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6160. };
  6161. /**
  6162. * 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"
  6163. * This function works in left handed mode
  6164. * @param eye defines the final position of the entity
  6165. * @param target defines where the entity should look at
  6166. * @param up defines the up vector for the entity
  6167. * @returns the new matrix
  6168. */
  6169. Matrix.LookAtLH = function (eye, target, up) {
  6170. var result = Matrix.Zero();
  6171. Matrix.LookAtLHToRef(eye, target, up, result);
  6172. return result;
  6173. };
  6174. /**
  6175. * 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".
  6176. * This function works in left handed mode
  6177. * @param eye defines the final position of the entity
  6178. * @param target defines where the entity should look at
  6179. * @param up defines the up vector for the entity
  6180. * @param result defines the target matrix
  6181. */
  6182. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6183. // Z axis
  6184. target.subtractToRef(eye, this._zAxis);
  6185. this._zAxis.normalize();
  6186. // X axis
  6187. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6188. if (this._xAxis.lengthSquared() === 0) {
  6189. this._xAxis.x = 1.0;
  6190. }
  6191. else {
  6192. this._xAxis.normalize();
  6193. }
  6194. // Y axis
  6195. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6196. this._yAxis.normalize();
  6197. // Eye angles
  6198. var ex = -Vector3.Dot(this._xAxis, eye);
  6199. var ey = -Vector3.Dot(this._yAxis, eye);
  6200. var ez = -Vector3.Dot(this._zAxis, eye);
  6201. 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);
  6202. };
  6203. /**
  6204. * 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"
  6205. * This function works in right handed mode
  6206. * @param eye defines the final position of the entity
  6207. * @param target defines where the entity should look at
  6208. * @param up defines the up vector for the entity
  6209. * @returns the new matrix
  6210. */
  6211. Matrix.LookAtRH = function (eye, target, up) {
  6212. var result = Matrix.Zero();
  6213. Matrix.LookAtRHToRef(eye, target, up, result);
  6214. return result;
  6215. };
  6216. /**
  6217. * 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".
  6218. * This function works in right handed mode
  6219. * @param eye defines the final position of the entity
  6220. * @param target defines where the entity should look at
  6221. * @param up defines the up vector for the entity
  6222. * @param result defines the target matrix
  6223. */
  6224. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6225. // Z axis
  6226. eye.subtractToRef(target, this._zAxis);
  6227. this._zAxis.normalize();
  6228. // X axis
  6229. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6230. if (this._xAxis.lengthSquared() === 0) {
  6231. this._xAxis.x = 1.0;
  6232. }
  6233. else {
  6234. this._xAxis.normalize();
  6235. }
  6236. // Y axis
  6237. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6238. this._yAxis.normalize();
  6239. // Eye angles
  6240. var ex = -Vector3.Dot(this._xAxis, eye);
  6241. var ey = -Vector3.Dot(this._yAxis, eye);
  6242. var ez = -Vector3.Dot(this._zAxis, eye);
  6243. 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);
  6244. };
  6245. /**
  6246. * Create a left-handed orthographic projection matrix
  6247. * @param width defines the viewport width
  6248. * @param height defines the viewport height
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a left-handed orthographic projection matrix
  6252. */
  6253. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Store a left-handed orthographic projection to a given matrix
  6260. * @param width defines the viewport width
  6261. * @param height defines the viewport height
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. */
  6266. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6267. var n = znear;
  6268. var f = zfar;
  6269. var a = 2.0 / width;
  6270. var b = 2.0 / height;
  6271. var c = 2.0 / (f - n);
  6272. var d = -(f + n) / (f - n);
  6273. 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);
  6274. };
  6275. /**
  6276. * Create a left-handed orthographic projection matrix
  6277. * @param left defines the viewport left coordinate
  6278. * @param right defines the viewport right coordinate
  6279. * @param bottom defines the viewport bottom coordinate
  6280. * @param top defines the viewport top coordinate
  6281. * @param znear defines the near clip plane
  6282. * @param zfar defines the far clip plane
  6283. * @returns a new matrix as a left-handed orthographic projection matrix
  6284. */
  6285. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6286. var matrix = Matrix.Zero();
  6287. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6288. return matrix;
  6289. };
  6290. /**
  6291. * Stores a left-handed orthographic projection into a given matrix
  6292. * @param left defines the viewport left coordinate
  6293. * @param right defines the viewport right coordinate
  6294. * @param bottom defines the viewport bottom coordinate
  6295. * @param top defines the viewport top coordinate
  6296. * @param znear defines the near clip plane
  6297. * @param zfar defines the far clip plane
  6298. * @param result defines the target matrix
  6299. */
  6300. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6301. var n = znear;
  6302. var f = zfar;
  6303. var a = 2.0 / (right - left);
  6304. var b = 2.0 / (top - bottom);
  6305. var c = 2.0 / (f - n);
  6306. var d = -(f + n) / (f - n);
  6307. var i0 = (left + right) / (left - right);
  6308. var i1 = (top + bottom) / (bottom - top);
  6309. 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);
  6310. };
  6311. /**
  6312. * Creates a right-handed orthographic projection matrix
  6313. * @param left defines the viewport left coordinate
  6314. * @param right defines the viewport right coordinate
  6315. * @param bottom defines the viewport bottom coordinate
  6316. * @param top defines the viewport top coordinate
  6317. * @param znear defines the near clip plane
  6318. * @param zfar defines the far clip plane
  6319. * @returns a new matrix as a right-handed orthographic projection matrix
  6320. */
  6321. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6322. var matrix = Matrix.Zero();
  6323. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6324. return matrix;
  6325. };
  6326. /**
  6327. * Stores a right-handed orthographic projection into a given matrix
  6328. * @param left defines the viewport left coordinate
  6329. * @param right defines the viewport right coordinate
  6330. * @param bottom defines the viewport bottom coordinate
  6331. * @param top defines the viewport top coordinate
  6332. * @param znear defines the near clip plane
  6333. * @param zfar defines the far clip plane
  6334. * @param result defines the target matrix
  6335. */
  6336. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6337. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6338. result.m[10] *= -1.0;
  6339. };
  6340. /**
  6341. * Creates a left-handed perspective projection matrix
  6342. * @param width defines the viewport width
  6343. * @param height defines the viewport height
  6344. * @param znear defines the near clip plane
  6345. * @param zfar defines the far clip plane
  6346. * @returns a new matrix as a left-handed perspective projection matrix
  6347. */
  6348. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6349. var matrix = Matrix.Zero();
  6350. var n = znear;
  6351. var f = zfar;
  6352. var a = 2.0 * n / width;
  6353. var b = 2.0 * n / height;
  6354. var c = (f + n) / (f - n);
  6355. var d = -2.0 * f * n / (f - n);
  6356. 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);
  6357. return matrix;
  6358. };
  6359. /**
  6360. * Creates a left-handed perspective projection matrix
  6361. * @param fov defines the horizontal field of view
  6362. * @param aspect defines the aspect ratio
  6363. * @param znear defines the near clip plane
  6364. * @param zfar defines the far clip plane
  6365. * @returns a new matrix as a left-handed perspective projection matrix
  6366. */
  6367. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6368. var matrix = Matrix.Zero();
  6369. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6370. return matrix;
  6371. };
  6372. /**
  6373. * Stores a left-handed perspective projection into a given matrix
  6374. * @param fov defines the horizontal field of view
  6375. * @param aspect defines the aspect ratio
  6376. * @param znear defines the near clip plane
  6377. * @param zfar defines the far clip plane
  6378. * @param result defines the target matrix
  6379. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6380. */
  6381. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6382. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6383. var n = znear;
  6384. var f = zfar;
  6385. var t = 1.0 / (Math.tan(fov * 0.5));
  6386. var a = isVerticalFovFixed ? (t / aspect) : t;
  6387. var b = isVerticalFovFixed ? t : (t * aspect);
  6388. var c = (f + n) / (f - n);
  6389. var d = -2.0 * f * n / (f - n);
  6390. 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);
  6391. };
  6392. /**
  6393. * Creates a right-handed perspective projection matrix
  6394. * @param fov defines the horizontal field of view
  6395. * @param aspect defines the aspect ratio
  6396. * @param znear defines the near clip plane
  6397. * @param zfar defines the far clip plane
  6398. * @returns a new matrix as a right-handed perspective projection matrix
  6399. */
  6400. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6401. var matrix = Matrix.Zero();
  6402. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6403. return matrix;
  6404. };
  6405. /**
  6406. * Stores a right-handed perspective projection into a given matrix
  6407. * @param fov defines the horizontal field of view
  6408. * @param aspect defines the aspect ratio
  6409. * @param znear defines the near clip plane
  6410. * @param zfar defines the far clip plane
  6411. * @param result defines the target matrix
  6412. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6413. */
  6414. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6415. //alternatively this could be expressed as:
  6416. // m = PerspectiveFovLHToRef
  6417. // m[10] *= -1.0;
  6418. // m[11] *= -1.0;
  6419. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6420. var n = znear;
  6421. var f = zfar;
  6422. var t = 1.0 / (Math.tan(fov * 0.5));
  6423. var a = isVerticalFovFixed ? (t / aspect) : t;
  6424. var b = isVerticalFovFixed ? t : (t * aspect);
  6425. var c = -(f + n) / (f - n);
  6426. var d = -2 * f * n / (f - n);
  6427. 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);
  6428. };
  6429. /**
  6430. * Stores a perspective projection for WebVR info a given matrix
  6431. * @param fov defines the field of view
  6432. * @param znear defines the near clip plane
  6433. * @param zfar defines the far clip plane
  6434. * @param result defines the target matrix
  6435. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6436. */
  6437. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6438. if (rightHanded === void 0) { rightHanded = false; }
  6439. var rightHandedFactor = rightHanded ? -1 : 1;
  6440. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6441. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6442. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6443. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6444. var xScale = 2.0 / (leftTan + rightTan);
  6445. var yScale = 2.0 / (upTan + downTan);
  6446. result.m[0] = xScale;
  6447. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6448. result.m[5] = yScale;
  6449. result.m[6] = result.m[7] = 0.0;
  6450. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6451. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6452. result.m[10] = -zfar / (znear - zfar);
  6453. result.m[11] = 1.0 * rightHandedFactor;
  6454. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6455. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6456. result._markAsUpdated();
  6457. };
  6458. /**
  6459. * Computes a complete transformation matrix
  6460. * @param viewport defines the viewport to use
  6461. * @param world defines the world matrix
  6462. * @param view defines the view matrix
  6463. * @param projection defines the projection matrix
  6464. * @param zmin defines the near clip plane
  6465. * @param zmax defines the far clip plane
  6466. * @returns the transformation matrix
  6467. */
  6468. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6469. var cw = viewport.width;
  6470. var ch = viewport.height;
  6471. var cx = viewport.x;
  6472. var cy = viewport.y;
  6473. 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);
  6474. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6475. };
  6476. /**
  6477. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6478. * @param matrix defines the matrix to use
  6479. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6480. */
  6481. Matrix.GetAsMatrix2x2 = function (matrix) {
  6482. return new Float32Array([
  6483. matrix.m[0], matrix.m[1],
  6484. matrix.m[4], matrix.m[5]
  6485. ]);
  6486. };
  6487. /**
  6488. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6489. * @param matrix defines the matrix to use
  6490. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6491. */
  6492. Matrix.GetAsMatrix3x3 = function (matrix) {
  6493. return new Float32Array([
  6494. matrix.m[0], matrix.m[1], matrix.m[2],
  6495. matrix.m[4], matrix.m[5], matrix.m[6],
  6496. matrix.m[8], matrix.m[9], matrix.m[10]
  6497. ]);
  6498. };
  6499. /**
  6500. * Compute the transpose of a given matrix
  6501. * @param matrix defines the matrix to transpose
  6502. * @returns the new matrix
  6503. */
  6504. Matrix.Transpose = function (matrix) {
  6505. var result = new Matrix();
  6506. Matrix.TransposeToRef(matrix, result);
  6507. return result;
  6508. };
  6509. /**
  6510. * Compute the transpose of a matrix and store it in a target matrix
  6511. * @param matrix defines the matrix to transpose
  6512. * @param result defines the target matrix
  6513. */
  6514. Matrix.TransposeToRef = function (matrix, result) {
  6515. result.m[0] = matrix.m[0];
  6516. result.m[1] = matrix.m[4];
  6517. result.m[2] = matrix.m[8];
  6518. result.m[3] = matrix.m[12];
  6519. result.m[4] = matrix.m[1];
  6520. result.m[5] = matrix.m[5];
  6521. result.m[6] = matrix.m[9];
  6522. result.m[7] = matrix.m[13];
  6523. result.m[8] = matrix.m[2];
  6524. result.m[9] = matrix.m[6];
  6525. result.m[10] = matrix.m[10];
  6526. result.m[11] = matrix.m[14];
  6527. result.m[12] = matrix.m[3];
  6528. result.m[13] = matrix.m[7];
  6529. result.m[14] = matrix.m[11];
  6530. result.m[15] = matrix.m[15];
  6531. };
  6532. /**
  6533. * Computes a reflection matrix from a plane
  6534. * @param plane defines the reflection plane
  6535. * @returns a new matrix
  6536. */
  6537. Matrix.Reflection = function (plane) {
  6538. var matrix = new Matrix();
  6539. Matrix.ReflectionToRef(plane, matrix);
  6540. return matrix;
  6541. };
  6542. /**
  6543. * Computes a reflection matrix from a plane
  6544. * @param plane defines the reflection plane
  6545. * @param result defines the target matrix
  6546. */
  6547. Matrix.ReflectionToRef = function (plane, result) {
  6548. plane.normalize();
  6549. var x = plane.normal.x;
  6550. var y = plane.normal.y;
  6551. var z = plane.normal.z;
  6552. var temp = -2 * x;
  6553. var temp2 = -2 * y;
  6554. var temp3 = -2 * z;
  6555. result.m[0] = (temp * x) + 1;
  6556. result.m[1] = temp2 * x;
  6557. result.m[2] = temp3 * x;
  6558. result.m[3] = 0.0;
  6559. result.m[4] = temp * y;
  6560. result.m[5] = (temp2 * y) + 1;
  6561. result.m[6] = temp3 * y;
  6562. result.m[7] = 0.0;
  6563. result.m[8] = temp * z;
  6564. result.m[9] = temp2 * z;
  6565. result.m[10] = (temp3 * z) + 1;
  6566. result.m[11] = 0.0;
  6567. result.m[12] = temp * plane.d;
  6568. result.m[13] = temp2 * plane.d;
  6569. result.m[14] = temp3 * plane.d;
  6570. result.m[15] = 1.0;
  6571. result._markAsUpdated();
  6572. };
  6573. /**
  6574. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6575. * @param xaxis defines the value of the 1st axis
  6576. * @param yaxis defines the value of the 2nd axis
  6577. * @param zaxis defines the value of the 3rd axis
  6578. * @param result defines the target matrix
  6579. */
  6580. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6581. result.m[0] = xaxis.x;
  6582. result.m[1] = xaxis.y;
  6583. result.m[2] = xaxis.z;
  6584. result.m[3] = 0.0;
  6585. result.m[4] = yaxis.x;
  6586. result.m[5] = yaxis.y;
  6587. result.m[6] = yaxis.z;
  6588. result.m[7] = 0.0;
  6589. result.m[8] = zaxis.x;
  6590. result.m[9] = zaxis.y;
  6591. result.m[10] = zaxis.z;
  6592. result.m[11] = 0.0;
  6593. result.m[12] = 0.0;
  6594. result.m[13] = 0.0;
  6595. result.m[14] = 0.0;
  6596. result.m[15] = 1.0;
  6597. result._markAsUpdated();
  6598. };
  6599. /**
  6600. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6601. * @param quat defines the quaternion to use
  6602. * @param result defines the target matrix
  6603. */
  6604. Matrix.FromQuaternionToRef = function (quat, result) {
  6605. var xx = quat.x * quat.x;
  6606. var yy = quat.y * quat.y;
  6607. var zz = quat.z * quat.z;
  6608. var xy = quat.x * quat.y;
  6609. var zw = quat.z * quat.w;
  6610. var zx = quat.z * quat.x;
  6611. var yw = quat.y * quat.w;
  6612. var yz = quat.y * quat.z;
  6613. var xw = quat.x * quat.w;
  6614. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6615. result.m[1] = 2.0 * (xy + zw);
  6616. result.m[2] = 2.0 * (zx - yw);
  6617. result.m[3] = 0.0;
  6618. result.m[4] = 2.0 * (xy - zw);
  6619. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6620. result.m[6] = 2.0 * (yz + xw);
  6621. result.m[7] = 0.0;
  6622. result.m[8] = 2.0 * (zx + yw);
  6623. result.m[9] = 2.0 * (yz - xw);
  6624. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6625. result.m[11] = 0.0;
  6626. result.m[12] = 0.0;
  6627. result.m[13] = 0.0;
  6628. result.m[14] = 0.0;
  6629. result.m[15] = 1.0;
  6630. result._markAsUpdated();
  6631. };
  6632. Matrix._tempQuaternion = new Quaternion();
  6633. Matrix._xAxis = Vector3.Zero();
  6634. Matrix._yAxis = Vector3.Zero();
  6635. Matrix._zAxis = Vector3.Zero();
  6636. Matrix._updateFlagSeed = 0;
  6637. Matrix._identityReadOnly = Matrix.Identity();
  6638. return Matrix;
  6639. }());
  6640. BABYLON.Matrix = Matrix;
  6641. var Plane = /** @class */ (function () {
  6642. /**
  6643. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6644. */
  6645. function Plane(a, b, c, d) {
  6646. this.normal = new Vector3(a, b, c);
  6647. this.d = d;
  6648. }
  6649. /**
  6650. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6651. */
  6652. Plane.prototype.asArray = function () {
  6653. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6654. };
  6655. // Methods
  6656. /**
  6657. * Returns a new plane copied from the current Plane.
  6658. */
  6659. Plane.prototype.clone = function () {
  6660. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6661. };
  6662. /**
  6663. * Returns the string "Plane".
  6664. */
  6665. Plane.prototype.getClassName = function () {
  6666. return "Plane";
  6667. };
  6668. /**
  6669. * Returns the Plane hash code.
  6670. */
  6671. Plane.prototype.getHashCode = function () {
  6672. var hash = this.normal.getHashCode();
  6673. hash = (hash * 397) ^ (this.d || 0);
  6674. return hash;
  6675. };
  6676. /**
  6677. * Normalize the current Plane in place.
  6678. * Returns the updated Plane.
  6679. */
  6680. Plane.prototype.normalize = function () {
  6681. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6682. var magnitude = 0.0;
  6683. if (norm !== 0) {
  6684. magnitude = 1.0 / norm;
  6685. }
  6686. this.normal.x *= magnitude;
  6687. this.normal.y *= magnitude;
  6688. this.normal.z *= magnitude;
  6689. this.d *= magnitude;
  6690. return this;
  6691. };
  6692. /**
  6693. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6694. */
  6695. Plane.prototype.transform = function (transformation) {
  6696. var transposedMatrix = Matrix.Transpose(transformation);
  6697. var x = this.normal.x;
  6698. var y = this.normal.y;
  6699. var z = this.normal.z;
  6700. var d = this.d;
  6701. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6702. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6703. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6704. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6705. return new Plane(normalX, normalY, normalZ, finalD);
  6706. };
  6707. /**
  6708. * Returns the dot product (float) of the point coordinates and the plane normal.
  6709. */
  6710. Plane.prototype.dotCoordinate = function (point) {
  6711. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6712. };
  6713. /**
  6714. * Updates the current Plane from the plane defined by the three given points.
  6715. * Returns the updated Plane.
  6716. */
  6717. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6718. var x1 = point2.x - point1.x;
  6719. var y1 = point2.y - point1.y;
  6720. var z1 = point2.z - point1.z;
  6721. var x2 = point3.x - point1.x;
  6722. var y2 = point3.y - point1.y;
  6723. var z2 = point3.z - point1.z;
  6724. var yz = (y1 * z2) - (z1 * y2);
  6725. var xz = (z1 * x2) - (x1 * z2);
  6726. var xy = (x1 * y2) - (y1 * x2);
  6727. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6728. var invPyth;
  6729. if (pyth !== 0) {
  6730. invPyth = 1.0 / pyth;
  6731. }
  6732. else {
  6733. invPyth = 0.0;
  6734. }
  6735. this.normal.x = yz * invPyth;
  6736. this.normal.y = xz * invPyth;
  6737. this.normal.z = xy * invPyth;
  6738. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6739. return this;
  6740. };
  6741. /**
  6742. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6743. */
  6744. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6745. var dot = Vector3.Dot(this.normal, direction);
  6746. return (dot <= epsilon);
  6747. };
  6748. /**
  6749. * Returns the signed distance (float) from the given point to the Plane.
  6750. */
  6751. Plane.prototype.signedDistanceTo = function (point) {
  6752. return Vector3.Dot(point, this.normal) + this.d;
  6753. };
  6754. // Statics
  6755. /**
  6756. * Returns a new Plane from the given array.
  6757. */
  6758. Plane.FromArray = function (array) {
  6759. return new Plane(array[0], array[1], array[2], array[3]);
  6760. };
  6761. /**
  6762. * Returns a new Plane defined by the three given points.
  6763. */
  6764. Plane.FromPoints = function (point1, point2, point3) {
  6765. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6766. result.copyFromPoints(point1, point2, point3);
  6767. return result;
  6768. };
  6769. /**
  6770. * Returns a new Plane the normal vector to this plane at the given origin point.
  6771. * Note : the vector "normal" is updated because normalized.
  6772. */
  6773. Plane.FromPositionAndNormal = function (origin, normal) {
  6774. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6775. normal.normalize();
  6776. result.normal = normal;
  6777. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6778. return result;
  6779. };
  6780. /**
  6781. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6782. */
  6783. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6784. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6785. return Vector3.Dot(point, normal) + d;
  6786. };
  6787. return Plane;
  6788. }());
  6789. BABYLON.Plane = Plane;
  6790. var Viewport = /** @class */ (function () {
  6791. /**
  6792. * Creates a Viewport object located at (x, y) and sized (width, height).
  6793. */
  6794. function Viewport(x, y, width, height) {
  6795. this.x = x;
  6796. this.y = y;
  6797. this.width = width;
  6798. this.height = height;
  6799. }
  6800. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6801. if (renderWidthOrEngine.getRenderWidth) {
  6802. var engine = renderWidthOrEngine;
  6803. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6804. }
  6805. var renderWidth = renderWidthOrEngine;
  6806. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6807. };
  6808. /**
  6809. * Returns a new Viewport copied from the current one.
  6810. */
  6811. Viewport.prototype.clone = function () {
  6812. return new Viewport(this.x, this.y, this.width, this.height);
  6813. };
  6814. return Viewport;
  6815. }());
  6816. BABYLON.Viewport = Viewport;
  6817. var Frustum = /** @class */ (function () {
  6818. function Frustum() {
  6819. }
  6820. /**
  6821. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6822. */
  6823. Frustum.GetPlanes = function (transform) {
  6824. var frustumPlanes = [];
  6825. for (var index = 0; index < 6; index++) {
  6826. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6827. }
  6828. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6829. return frustumPlanes;
  6830. };
  6831. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6832. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6833. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6834. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6835. frustumPlane.d = transform.m[15] + transform.m[14];
  6836. frustumPlane.normalize();
  6837. };
  6838. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6840. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6841. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6842. frustumPlane.d = transform.m[15] - transform.m[14];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6847. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6848. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6849. frustumPlane.d = transform.m[15] + transform.m[12];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6854. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6855. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6856. frustumPlane.d = transform.m[15] - transform.m[12];
  6857. frustumPlane.normalize();
  6858. };
  6859. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6860. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6861. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6862. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6863. frustumPlane.d = transform.m[15] - transform.m[13];
  6864. frustumPlane.normalize();
  6865. };
  6866. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6867. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6868. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6869. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6870. frustumPlane.d = transform.m[15] + transform.m[13];
  6871. frustumPlane.normalize();
  6872. };
  6873. /**
  6874. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6875. */
  6876. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6877. // Near
  6878. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6879. // Far
  6880. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6881. // Left
  6882. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6883. // Right
  6884. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6885. // Top
  6886. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6887. // Bottom
  6888. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6889. };
  6890. return Frustum;
  6891. }());
  6892. BABYLON.Frustum = Frustum;
  6893. /** Defines supported spaces */
  6894. var Space;
  6895. (function (Space) {
  6896. /** Local (object) space */
  6897. Space[Space["LOCAL"] = 0] = "LOCAL";
  6898. /** World space */
  6899. Space[Space["WORLD"] = 1] = "WORLD";
  6900. /** Bone space */
  6901. Space[Space["BONE"] = 2] = "BONE";
  6902. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6903. /** Defines the 3 main axes */
  6904. var Axis = /** @class */ (function () {
  6905. function Axis() {
  6906. }
  6907. /** X axis */
  6908. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6909. /** Y axis */
  6910. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6911. /** Z axis */
  6912. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6913. return Axis;
  6914. }());
  6915. BABYLON.Axis = Axis;
  6916. ;
  6917. var BezierCurve = /** @class */ (function () {
  6918. function BezierCurve() {
  6919. }
  6920. /**
  6921. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6922. */
  6923. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6924. // Extract X (which is equal to time here)
  6925. var f0 = 1 - 3 * x2 + 3 * x1;
  6926. var f1 = 3 * x2 - 6 * x1;
  6927. var f2 = 3 * x1;
  6928. var refinedT = t;
  6929. for (var i = 0; i < 5; i++) {
  6930. var refinedT2 = refinedT * refinedT;
  6931. var refinedT3 = refinedT2 * refinedT;
  6932. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6933. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6934. refinedT -= (x - t) * slope;
  6935. refinedT = Math.min(1, Math.max(0, refinedT));
  6936. }
  6937. // Resolve cubic bezier for the given x
  6938. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6939. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6940. Math.pow(refinedT, 3);
  6941. };
  6942. return BezierCurve;
  6943. }());
  6944. BABYLON.BezierCurve = BezierCurve;
  6945. /**
  6946. * Defines potential orientation for back face culling
  6947. */
  6948. var Orientation;
  6949. (function (Orientation) {
  6950. /**
  6951. * Clockwise
  6952. */
  6953. Orientation[Orientation["CW"] = 0] = "CW";
  6954. /** Counter clockwise */
  6955. Orientation[Orientation["CCW"] = 1] = "CCW";
  6956. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6957. /**
  6958. * Defines angle representation
  6959. */
  6960. var Angle = /** @class */ (function () {
  6961. /**
  6962. * Creates an Angle object of "radians" radians (float).
  6963. */
  6964. function Angle(radians) {
  6965. this._radians = radians;
  6966. if (this._radians < 0.0)
  6967. this._radians += (2.0 * Math.PI);
  6968. }
  6969. /**
  6970. * Get value in degrees
  6971. * @returns the Angle value in degrees (float)
  6972. */
  6973. Angle.prototype.degrees = function () {
  6974. return this._radians * 180.0 / Math.PI;
  6975. };
  6976. /**
  6977. * Get value in radians
  6978. * @returns the Angle value in radians (float)
  6979. */
  6980. Angle.prototype.radians = function () {
  6981. return this._radians;
  6982. };
  6983. /**
  6984. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6985. * @param a defines first vector
  6986. * @param b defines second vector
  6987. * @returns a new Angle
  6988. */
  6989. Angle.BetweenTwoPoints = function (a, b) {
  6990. var delta = b.subtract(a);
  6991. var theta = Math.atan2(delta.y, delta.x);
  6992. return new Angle(theta);
  6993. };
  6994. /**
  6995. * Gets a new Angle object from the given float in radians
  6996. * @param radians defines the angle value in radians
  6997. * @returns a new Angle
  6998. */
  6999. Angle.FromRadians = function (radians) {
  7000. return new Angle(radians);
  7001. };
  7002. /**
  7003. * Gets a new Angle object from the given float in degrees
  7004. * @param degrees defines the angle value in degrees
  7005. * @returns a new Angle
  7006. */
  7007. Angle.FromDegrees = function (degrees) {
  7008. return new Angle(degrees * Math.PI / 180.0);
  7009. };
  7010. return Angle;
  7011. }());
  7012. BABYLON.Angle = Angle;
  7013. var Arc2 = /** @class */ (function () {
  7014. /**
  7015. * Creates an Arc object from the three given points : start, middle and end.
  7016. */
  7017. function Arc2(startPoint, midPoint, endPoint) {
  7018. this.startPoint = startPoint;
  7019. this.midPoint = midPoint;
  7020. this.endPoint = endPoint;
  7021. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7022. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7023. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7024. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7025. 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);
  7026. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7027. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7028. var a1 = this.startAngle.degrees();
  7029. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7030. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7031. // angles correction
  7032. if (a2 - a1 > +180.0)
  7033. a2 -= 360.0;
  7034. if (a2 - a1 < -180.0)
  7035. a2 += 360.0;
  7036. if (a3 - a2 > +180.0)
  7037. a3 -= 360.0;
  7038. if (a3 - a2 < -180.0)
  7039. a3 += 360.0;
  7040. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7041. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7042. }
  7043. return Arc2;
  7044. }());
  7045. BABYLON.Arc2 = Arc2;
  7046. var Path2 = /** @class */ (function () {
  7047. /**
  7048. * Creates a Path2 object from the starting 2D coordinates x and y.
  7049. */
  7050. function Path2(x, y) {
  7051. this._points = new Array();
  7052. this._length = 0.0;
  7053. this.closed = false;
  7054. this._points.push(new Vector2(x, y));
  7055. }
  7056. /**
  7057. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7058. * Returns the updated Path2.
  7059. */
  7060. Path2.prototype.addLineTo = function (x, y) {
  7061. if (this.closed) {
  7062. return this;
  7063. }
  7064. var newPoint = new Vector2(x, y);
  7065. var previousPoint = this._points[this._points.length - 1];
  7066. this._points.push(newPoint);
  7067. this._length += newPoint.subtract(previousPoint).length();
  7068. return this;
  7069. };
  7070. /**
  7071. * 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.
  7072. * Returns the updated Path2.
  7073. */
  7074. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7075. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7076. if (this.closed) {
  7077. return this;
  7078. }
  7079. var startPoint = this._points[this._points.length - 1];
  7080. var midPoint = new Vector2(midX, midY);
  7081. var endPoint = new Vector2(endX, endY);
  7082. var arc = new Arc2(startPoint, midPoint, endPoint);
  7083. var increment = arc.angle.radians() / numberOfSegments;
  7084. if (arc.orientation === Orientation.CW)
  7085. increment *= -1;
  7086. var currentAngle = arc.startAngle.radians() + increment;
  7087. for (var i = 0; i < numberOfSegments; i++) {
  7088. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7089. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7090. this.addLineTo(x, y);
  7091. currentAngle += increment;
  7092. }
  7093. return this;
  7094. };
  7095. /**
  7096. * Closes the Path2.
  7097. * Returns the Path2.
  7098. */
  7099. Path2.prototype.close = function () {
  7100. this.closed = true;
  7101. return this;
  7102. };
  7103. /**
  7104. * Returns the Path2 total length (float).
  7105. */
  7106. Path2.prototype.length = function () {
  7107. var result = this._length;
  7108. if (!this.closed) {
  7109. var lastPoint = this._points[this._points.length - 1];
  7110. var firstPoint = this._points[0];
  7111. result += (firstPoint.subtract(lastPoint).length());
  7112. }
  7113. return result;
  7114. };
  7115. /**
  7116. * Returns the Path2 internal array of points.
  7117. */
  7118. Path2.prototype.getPoints = function () {
  7119. return this._points;
  7120. };
  7121. /**
  7122. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7123. */
  7124. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7125. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7126. return Vector2.Zero();
  7127. }
  7128. var lengthPosition = normalizedLengthPosition * this.length();
  7129. var previousOffset = 0;
  7130. for (var i = 0; i < this._points.length; i++) {
  7131. var j = (i + 1) % this._points.length;
  7132. var a = this._points[i];
  7133. var b = this._points[j];
  7134. var bToA = b.subtract(a);
  7135. var nextOffset = (bToA.length() + previousOffset);
  7136. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7137. var dir = bToA.normalize();
  7138. var localOffset = lengthPosition - previousOffset;
  7139. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7140. }
  7141. previousOffset = nextOffset;
  7142. }
  7143. return Vector2.Zero();
  7144. };
  7145. /**
  7146. * Returns a new Path2 starting at the coordinates (x, y).
  7147. */
  7148. Path2.StartingAt = function (x, y) {
  7149. return new Path2(x, y);
  7150. };
  7151. return Path2;
  7152. }());
  7153. BABYLON.Path2 = Path2;
  7154. var Path3D = /** @class */ (function () {
  7155. /**
  7156. * new Path3D(path, normal, raw)
  7157. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7158. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7159. * path : an array of Vector3, the curve axis of the Path3D
  7160. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7161. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7162. */
  7163. function Path3D(path, firstNormal, raw) {
  7164. if (firstNormal === void 0) { firstNormal = null; }
  7165. this.path = path;
  7166. this._curve = new Array();
  7167. this._distances = new Array();
  7168. this._tangents = new Array();
  7169. this._normals = new Array();
  7170. this._binormals = new Array();
  7171. for (var p = 0; p < path.length; p++) {
  7172. this._curve[p] = path[p].clone(); // hard copy
  7173. }
  7174. this._raw = raw || false;
  7175. this._compute(firstNormal);
  7176. }
  7177. /**
  7178. * Returns the Path3D array of successive Vector3 designing its curve.
  7179. */
  7180. Path3D.prototype.getCurve = function () {
  7181. return this._curve;
  7182. };
  7183. /**
  7184. * Returns an array populated with tangent vectors on each Path3D curve point.
  7185. */
  7186. Path3D.prototype.getTangents = function () {
  7187. return this._tangents;
  7188. };
  7189. /**
  7190. * Returns an array populated with normal vectors on each Path3D curve point.
  7191. */
  7192. Path3D.prototype.getNormals = function () {
  7193. return this._normals;
  7194. };
  7195. /**
  7196. * Returns an array populated with binormal vectors on each Path3D curve point.
  7197. */
  7198. Path3D.prototype.getBinormals = function () {
  7199. return this._binormals;
  7200. };
  7201. /**
  7202. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7203. */
  7204. Path3D.prototype.getDistances = function () {
  7205. return this._distances;
  7206. };
  7207. /**
  7208. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7209. * Returns the same object updated.
  7210. */
  7211. Path3D.prototype.update = function (path, firstNormal) {
  7212. if (firstNormal === void 0) { firstNormal = null; }
  7213. for (var p = 0; p < path.length; p++) {
  7214. this._curve[p].x = path[p].x;
  7215. this._curve[p].y = path[p].y;
  7216. this._curve[p].z = path[p].z;
  7217. }
  7218. this._compute(firstNormal);
  7219. return this;
  7220. };
  7221. // private function compute() : computes tangents, normals and binormals
  7222. Path3D.prototype._compute = function (firstNormal) {
  7223. var l = this._curve.length;
  7224. // first and last tangents
  7225. this._tangents[0] = this._getFirstNonNullVector(0);
  7226. if (!this._raw) {
  7227. this._tangents[0].normalize();
  7228. }
  7229. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7230. if (!this._raw) {
  7231. this._tangents[l - 1].normalize();
  7232. }
  7233. // normals and binormals at first point : arbitrary vector with _normalVector()
  7234. var tg0 = this._tangents[0];
  7235. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7236. this._normals[0] = pp0;
  7237. if (!this._raw) {
  7238. this._normals[0].normalize();
  7239. }
  7240. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7241. if (!this._raw) {
  7242. this._binormals[0].normalize();
  7243. }
  7244. this._distances[0] = 0.0;
  7245. // normals and binormals : next points
  7246. var prev; // previous vector (segment)
  7247. var cur; // current vector (segment)
  7248. var curTang; // current tangent
  7249. // previous normal
  7250. var prevBinor; // previous binormal
  7251. for (var i = 1; i < l; i++) {
  7252. // tangents
  7253. prev = this._getLastNonNullVector(i);
  7254. if (i < l - 1) {
  7255. cur = this._getFirstNonNullVector(i);
  7256. this._tangents[i] = prev.add(cur);
  7257. this._tangents[i].normalize();
  7258. }
  7259. this._distances[i] = this._distances[i - 1] + prev.length();
  7260. // normals and binormals
  7261. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7262. curTang = this._tangents[i];
  7263. prevBinor = this._binormals[i - 1];
  7264. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7265. if (!this._raw) {
  7266. this._normals[i].normalize();
  7267. }
  7268. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7269. if (!this._raw) {
  7270. this._binormals[i].normalize();
  7271. }
  7272. }
  7273. };
  7274. // private function getFirstNonNullVector(index)
  7275. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7276. Path3D.prototype._getFirstNonNullVector = function (index) {
  7277. var i = 1;
  7278. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7279. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7280. i++;
  7281. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7282. }
  7283. return nNVector;
  7284. };
  7285. // private function getLastNonNullVector(index)
  7286. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7287. Path3D.prototype._getLastNonNullVector = function (index) {
  7288. var i = 1;
  7289. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7290. while (nLVector.length() === 0 && index > i + 1) {
  7291. i++;
  7292. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7293. }
  7294. return nLVector;
  7295. };
  7296. // private function normalVector(v0, vt, va) :
  7297. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7298. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7299. Path3D.prototype._normalVector = function (v0, vt, va) {
  7300. var normal0;
  7301. var tgl = vt.length();
  7302. if (tgl === 0.0) {
  7303. tgl = 1.0;
  7304. }
  7305. if (va === undefined || va === null) {
  7306. var point;
  7307. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7308. point = new Vector3(0.0, -1.0, 0.0);
  7309. }
  7310. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7311. point = new Vector3(1.0, 0.0, 0.0);
  7312. }
  7313. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7314. point = new Vector3(0.0, 0.0, 1.0);
  7315. }
  7316. else {
  7317. point = Vector3.Zero();
  7318. }
  7319. normal0 = Vector3.Cross(vt, point);
  7320. }
  7321. else {
  7322. normal0 = Vector3.Cross(vt, va);
  7323. Vector3.CrossToRef(normal0, vt, normal0);
  7324. }
  7325. normal0.normalize();
  7326. return normal0;
  7327. };
  7328. return Path3D;
  7329. }());
  7330. BABYLON.Path3D = Path3D;
  7331. var Curve3 = /** @class */ (function () {
  7332. /**
  7333. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7334. * A Curve3 is designed from a series of successive Vector3.
  7335. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7336. */
  7337. function Curve3(points) {
  7338. this._length = 0.0;
  7339. this._points = points;
  7340. this._length = this._computeLength(points);
  7341. }
  7342. /**
  7343. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7344. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7345. * @param v1 (Vector3) the control point
  7346. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7347. * @param nbPoints (integer) the wanted number of points in the curve
  7348. */
  7349. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7350. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7351. var bez = new Array();
  7352. var equation = function (t, val0, val1, val2) {
  7353. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7354. return res;
  7355. };
  7356. for (var i = 0; i <= nbPoints; i++) {
  7357. 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)));
  7358. }
  7359. return new Curve3(bez);
  7360. };
  7361. /**
  7362. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7363. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7364. * @param v1 (Vector3) the first control point
  7365. * @param v2 (Vector3) the second control point
  7366. * @param v3 (Vector3) the end point of the Cubic Bezier
  7367. * @param nbPoints (integer) the wanted number of points in the curve
  7368. */
  7369. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7370. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7371. var bez = new Array();
  7372. var equation = function (t, val0, val1, val2, val3) {
  7373. 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;
  7374. return res;
  7375. };
  7376. for (var i = 0; i <= nbPoints; i++) {
  7377. 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)));
  7378. }
  7379. return new Curve3(bez);
  7380. };
  7381. /**
  7382. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7383. * @param p1 (Vector3) the origin point of the Hermite Spline
  7384. * @param t1 (Vector3) the tangent vector at the origin point
  7385. * @param p2 (Vector3) the end point of the Hermite Spline
  7386. * @param t2 (Vector3) the tangent vector at the end point
  7387. * @param nbPoints (integer) the wanted number of points in the curve
  7388. */
  7389. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7390. var hermite = new Array();
  7391. var step = 1.0 / nbPoints;
  7392. for (var i = 0; i <= nbPoints; i++) {
  7393. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7394. }
  7395. return new Curve3(hermite);
  7396. };
  7397. /**
  7398. * Returns a Curve3 object along a CatmullRom Spline curve :
  7399. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7400. * @param nbPoints (integer) the wanted number of points between each curve control points
  7401. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7402. */
  7403. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7404. var catmullRom = new Array();
  7405. var step = 1.0 / nbPoints;
  7406. var amount = 0.0;
  7407. if (closed) {
  7408. var pointsCount = points.length;
  7409. for (var i = 0; i < pointsCount; i++) {
  7410. amount = 0;
  7411. for (var c = 0; c < nbPoints; c++) {
  7412. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7413. amount += step;
  7414. }
  7415. }
  7416. catmullRom.push(catmullRom[0]);
  7417. }
  7418. else {
  7419. var totalPoints = new Array();
  7420. totalPoints.push(points[0].clone());
  7421. Array.prototype.push.apply(totalPoints, points);
  7422. totalPoints.push(points[points.length - 1].clone());
  7423. for (var i = 0; i < totalPoints.length - 3; i++) {
  7424. amount = 0;
  7425. for (var c = 0; c < nbPoints; c++) {
  7426. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7427. amount += step;
  7428. }
  7429. }
  7430. i--;
  7431. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7432. }
  7433. return new Curve3(catmullRom);
  7434. };
  7435. /**
  7436. * Returns the Curve3 stored array of successive Vector3
  7437. */
  7438. Curve3.prototype.getPoints = function () {
  7439. return this._points;
  7440. };
  7441. /**
  7442. * Returns the computed length (float) of the curve.
  7443. */
  7444. Curve3.prototype.length = function () {
  7445. return this._length;
  7446. };
  7447. /**
  7448. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7449. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7450. * curveA and curveB keep unchanged.
  7451. */
  7452. Curve3.prototype.continue = function (curve) {
  7453. var lastPoint = this._points[this._points.length - 1];
  7454. var continuedPoints = this._points.slice();
  7455. var curvePoints = curve.getPoints();
  7456. for (var i = 1; i < curvePoints.length; i++) {
  7457. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7458. }
  7459. var continuedCurve = new Curve3(continuedPoints);
  7460. return continuedCurve;
  7461. };
  7462. Curve3.prototype._computeLength = function (path) {
  7463. var l = 0;
  7464. for (var i = 1; i < path.length; i++) {
  7465. l += (path[i].subtract(path[i - 1])).length();
  7466. }
  7467. return l;
  7468. };
  7469. return Curve3;
  7470. }());
  7471. BABYLON.Curve3 = Curve3;
  7472. // Vertex formats
  7473. var PositionNormalVertex = /** @class */ (function () {
  7474. function PositionNormalVertex(position, normal) {
  7475. if (position === void 0) { position = Vector3.Zero(); }
  7476. if (normal === void 0) { normal = Vector3.Up(); }
  7477. this.position = position;
  7478. this.normal = normal;
  7479. }
  7480. PositionNormalVertex.prototype.clone = function () {
  7481. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7482. };
  7483. return PositionNormalVertex;
  7484. }());
  7485. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7486. var PositionNormalTextureVertex = /** @class */ (function () {
  7487. function PositionNormalTextureVertex(position, normal, uv) {
  7488. if (position === void 0) { position = Vector3.Zero(); }
  7489. if (normal === void 0) { normal = Vector3.Up(); }
  7490. if (uv === void 0) { uv = Vector2.Zero(); }
  7491. this.position = position;
  7492. this.normal = normal;
  7493. this.uv = uv;
  7494. }
  7495. PositionNormalTextureVertex.prototype.clone = function () {
  7496. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7497. };
  7498. return PositionNormalTextureVertex;
  7499. }());
  7500. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7501. // Temporary pre-allocated objects for engine internal use
  7502. // usage in any internal function :
  7503. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7504. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7505. var Tmp = /** @class */ (function () {
  7506. function Tmp() {
  7507. }
  7508. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7509. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7510. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7511. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7512. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7513. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7514. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7515. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7516. Matrix.Zero(), Matrix.Zero(),
  7517. Matrix.Zero(), Matrix.Zero(),
  7518. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7519. return Tmp;
  7520. }());
  7521. BABYLON.Tmp = Tmp;
  7522. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7523. var MathTmp = /** @class */ (function () {
  7524. function MathTmp() {
  7525. }
  7526. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7527. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7528. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7529. return MathTmp;
  7530. }());
  7531. })(BABYLON || (BABYLON = {}));
  7532. //# sourceMappingURL=babylon.math.js.map
  7533. var BABYLON;
  7534. (function (BABYLON) {
  7535. var Scalar = /** @class */ (function () {
  7536. function Scalar() {
  7537. }
  7538. /**
  7539. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7540. */
  7541. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7542. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7543. var num = a - b;
  7544. return -epsilon <= num && num <= epsilon;
  7545. };
  7546. /**
  7547. * Returns a string : the upper case translation of the number i to hexadecimal.
  7548. */
  7549. Scalar.ToHex = function (i) {
  7550. var str = i.toString(16);
  7551. if (i <= 15) {
  7552. return ("0" + str).toUpperCase();
  7553. }
  7554. return str.toUpperCase();
  7555. };
  7556. /**
  7557. * Returns -1 if value is negative and +1 is value is positive.
  7558. * Returns the value itself if it's equal to zero.
  7559. */
  7560. Scalar.Sign = function (value) {
  7561. value = +value; // convert to a number
  7562. if (value === 0 || isNaN(value))
  7563. return value;
  7564. return value > 0 ? 1 : -1;
  7565. };
  7566. /**
  7567. * Returns the value itself if it's between min and max.
  7568. * Returns min if the value is lower than min.
  7569. * Returns max if the value is greater than max.
  7570. */
  7571. Scalar.Clamp = function (value, min, max) {
  7572. if (min === void 0) { min = 0; }
  7573. if (max === void 0) { max = 1; }
  7574. return Math.min(max, Math.max(min, value));
  7575. };
  7576. /**
  7577. * Returns the log2 of value.
  7578. */
  7579. Scalar.Log2 = function (value) {
  7580. return Math.log(value) * Math.LOG2E;
  7581. };
  7582. /**
  7583. * Loops the value, so that it is never larger than length and never smaller than 0.
  7584. *
  7585. * This is similar to the modulo operator but it works with floating point numbers.
  7586. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7587. * With t = 5 and length = 2.5, the result would be 0.0.
  7588. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7589. */
  7590. Scalar.Repeat = function (value, length) {
  7591. return value - Math.floor(value / length) * length;
  7592. };
  7593. /**
  7594. * Normalize the value between 0.0 and 1.0 using min and max values
  7595. */
  7596. Scalar.Normalize = function (value, min, max) {
  7597. return (value - min) / (max - min);
  7598. };
  7599. /**
  7600. * Denormalize the value from 0.0 and 1.0 using min and max values
  7601. */
  7602. Scalar.Denormalize = function (normalized, min, max) {
  7603. return (normalized * (max - min) + min);
  7604. };
  7605. /**
  7606. * Calculates the shortest difference between two given angles given in degrees.
  7607. */
  7608. Scalar.DeltaAngle = function (current, target) {
  7609. var num = Scalar.Repeat(target - current, 360.0);
  7610. if (num > 180.0) {
  7611. num -= 360.0;
  7612. }
  7613. return num;
  7614. };
  7615. /**
  7616. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7617. *
  7618. * The returned value will move back and forth between 0 and length
  7619. */
  7620. Scalar.PingPong = function (tx, length) {
  7621. var t = Scalar.Repeat(tx, length * 2.0);
  7622. return length - Math.abs(t - length);
  7623. };
  7624. /**
  7625. * Interpolates between min and max with smoothing at the limits.
  7626. *
  7627. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7628. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7629. */
  7630. Scalar.SmoothStep = function (from, to, tx) {
  7631. var t = Scalar.Clamp(tx);
  7632. t = -2.0 * t * t * t + 3.0 * t * t;
  7633. return to * t + from * (1.0 - t);
  7634. };
  7635. /**
  7636. * Moves a value current towards target.
  7637. *
  7638. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7639. * Negative values of maxDelta pushes the value away from target.
  7640. */
  7641. Scalar.MoveTowards = function (current, target, maxDelta) {
  7642. var result = 0;
  7643. if (Math.abs(target - current) <= maxDelta) {
  7644. result = target;
  7645. }
  7646. else {
  7647. result = current + Scalar.Sign(target - current) * maxDelta;
  7648. }
  7649. return result;
  7650. };
  7651. /**
  7652. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7653. *
  7654. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7655. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7656. */
  7657. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7658. var num = Scalar.DeltaAngle(current, target);
  7659. var result = 0;
  7660. if (-maxDelta < num && num < maxDelta) {
  7661. result = target;
  7662. }
  7663. else {
  7664. target = current + num;
  7665. result = Scalar.MoveTowards(current, target, maxDelta);
  7666. }
  7667. return result;
  7668. };
  7669. /**
  7670. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7671. */
  7672. Scalar.Lerp = function (start, end, amount) {
  7673. return start + ((end - start) * amount);
  7674. };
  7675. /**
  7676. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7677. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7678. */
  7679. Scalar.LerpAngle = function (start, end, amount) {
  7680. var num = Scalar.Repeat(end - start, 360.0);
  7681. if (num > 180.0) {
  7682. num -= 360.0;
  7683. }
  7684. return start + num * Scalar.Clamp(amount);
  7685. };
  7686. /**
  7687. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7688. */
  7689. Scalar.InverseLerp = function (a, b, value) {
  7690. var result = 0;
  7691. if (a != b) {
  7692. result = Scalar.Clamp((value - a) / (b - a));
  7693. }
  7694. else {
  7695. result = 0.0;
  7696. }
  7697. return result;
  7698. };
  7699. /**
  7700. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7701. */
  7702. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7703. var squared = amount * amount;
  7704. var cubed = amount * squared;
  7705. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7706. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7707. var part3 = (cubed - (2.0 * squared)) + amount;
  7708. var part4 = cubed - squared;
  7709. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7710. };
  7711. /**
  7712. * Returns a random float number between and min and max values
  7713. */
  7714. Scalar.RandomRange = function (min, max) {
  7715. if (min === max)
  7716. return min;
  7717. return ((Math.random() * (max - min)) + min);
  7718. };
  7719. /**
  7720. * This function returns percentage of a number in a given range.
  7721. *
  7722. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7723. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7724. */
  7725. Scalar.RangeToPercent = function (number, min, max) {
  7726. return ((number - min) / (max - min));
  7727. };
  7728. /**
  7729. * This function returns number that corresponds to the percentage in a given range.
  7730. *
  7731. * PercentToRange(0.34,0,100) will return 34.
  7732. */
  7733. Scalar.PercentToRange = function (percent, min, max) {
  7734. return ((max - min) * percent + min);
  7735. };
  7736. /**
  7737. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7738. * @param angle The angle to normalize in radian.
  7739. * @return The converted angle.
  7740. */
  7741. Scalar.NormalizeRadians = function (angle) {
  7742. // More precise but slower version kept for reference.
  7743. // angle = angle % Tools.TwoPi;
  7744. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7745. //if (angle > Math.PI) {
  7746. // angle -= Tools.TwoPi;
  7747. //}
  7748. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7749. return angle;
  7750. };
  7751. /**
  7752. * Two pi constants convenient for computation.
  7753. */
  7754. Scalar.TwoPi = Math.PI * 2;
  7755. return Scalar;
  7756. }());
  7757. BABYLON.Scalar = Scalar;
  7758. })(BABYLON || (BABYLON = {}));
  7759. //# sourceMappingURL=babylon.math.scalar.js.map
  7760. //# sourceMappingURL=babylon.mixins.js.map
  7761. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7762. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7763. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7764. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7765. //# sourceMappingURL=babylon.webgl2.js.map
  7766. var BABYLON;
  7767. (function (BABYLON) {
  7768. var __decoratorInitialStore = {};
  7769. var __mergedStore = {};
  7770. var _copySource = function (creationFunction, source, instanciate) {
  7771. var destination = creationFunction();
  7772. // Tags
  7773. if (BABYLON.Tags) {
  7774. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7775. }
  7776. var classStore = getMergedStore(destination);
  7777. // Properties
  7778. for (var property in classStore) {
  7779. var propertyDescriptor = classStore[property];
  7780. var sourceProperty = source[property];
  7781. var propertyType = propertyDescriptor.type;
  7782. if (sourceProperty !== undefined && sourceProperty !== null) {
  7783. switch (propertyType) {
  7784. case 0: // Value
  7785. case 6: // Mesh reference
  7786. case 11: // Camera reference
  7787. destination[property] = sourceProperty;
  7788. break;
  7789. case 1: // Texture
  7790. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7791. break;
  7792. case 2: // Color3
  7793. case 3: // FresnelParameters
  7794. case 4: // Vector2
  7795. case 5: // Vector3
  7796. case 7: // Color Curves
  7797. case 10: // Quaternion
  7798. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7799. break;
  7800. }
  7801. }
  7802. }
  7803. return destination;
  7804. };
  7805. function getDirectStore(target) {
  7806. var classKey = target.getClassName();
  7807. if (!__decoratorInitialStore[classKey]) {
  7808. __decoratorInitialStore[classKey] = {};
  7809. }
  7810. return __decoratorInitialStore[classKey];
  7811. }
  7812. /**
  7813. * Return the list of properties flagged as serializable
  7814. * @param target: host object
  7815. */
  7816. function getMergedStore(target) {
  7817. var classKey = target.getClassName();
  7818. if (__mergedStore[classKey]) {
  7819. return __mergedStore[classKey];
  7820. }
  7821. __mergedStore[classKey] = {};
  7822. var store = __mergedStore[classKey];
  7823. var currentTarget = target;
  7824. var currentKey = classKey;
  7825. while (currentKey) {
  7826. var initialStore = __decoratorInitialStore[currentKey];
  7827. for (var property in initialStore) {
  7828. store[property] = initialStore[property];
  7829. }
  7830. var parent_1 = void 0;
  7831. var done = false;
  7832. do {
  7833. parent_1 = Object.getPrototypeOf(currentTarget);
  7834. if (!parent_1.getClassName) {
  7835. done = true;
  7836. break;
  7837. }
  7838. if (parent_1.getClassName() !== currentKey) {
  7839. break;
  7840. }
  7841. currentTarget = parent_1;
  7842. } while (parent_1);
  7843. if (done) {
  7844. break;
  7845. }
  7846. currentKey = parent_1.getClassName();
  7847. currentTarget = parent_1;
  7848. }
  7849. return store;
  7850. }
  7851. function generateSerializableMember(type, sourceName) {
  7852. return function (target, propertyKey) {
  7853. var classStore = getDirectStore(target);
  7854. if (!classStore[propertyKey]) {
  7855. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7856. }
  7857. };
  7858. }
  7859. function generateExpandMember(setCallback, targetKey) {
  7860. if (targetKey === void 0) { targetKey = null; }
  7861. return function (target, propertyKey) {
  7862. var key = targetKey || ("_" + propertyKey);
  7863. Object.defineProperty(target, propertyKey, {
  7864. get: function () {
  7865. return this[key];
  7866. },
  7867. set: function (value) {
  7868. if (this[key] === value) {
  7869. return;
  7870. }
  7871. this[key] = value;
  7872. target[setCallback].apply(this);
  7873. },
  7874. enumerable: true,
  7875. configurable: true
  7876. });
  7877. };
  7878. }
  7879. function expandToProperty(callback, targetKey) {
  7880. if (targetKey === void 0) { targetKey = null; }
  7881. return generateExpandMember(callback, targetKey);
  7882. }
  7883. BABYLON.expandToProperty = expandToProperty;
  7884. function serialize(sourceName) {
  7885. return generateSerializableMember(0, sourceName); // value member
  7886. }
  7887. BABYLON.serialize = serialize;
  7888. function serializeAsTexture(sourceName) {
  7889. return generateSerializableMember(1, sourceName); // texture member
  7890. }
  7891. BABYLON.serializeAsTexture = serializeAsTexture;
  7892. function serializeAsColor3(sourceName) {
  7893. return generateSerializableMember(2, sourceName); // color3 member
  7894. }
  7895. BABYLON.serializeAsColor3 = serializeAsColor3;
  7896. function serializeAsFresnelParameters(sourceName) {
  7897. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7898. }
  7899. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7900. function serializeAsVector2(sourceName) {
  7901. return generateSerializableMember(4, sourceName); // vector2 member
  7902. }
  7903. BABYLON.serializeAsVector2 = serializeAsVector2;
  7904. function serializeAsVector3(sourceName) {
  7905. return generateSerializableMember(5, sourceName); // vector3 member
  7906. }
  7907. BABYLON.serializeAsVector3 = serializeAsVector3;
  7908. function serializeAsMeshReference(sourceName) {
  7909. return generateSerializableMember(6, sourceName); // mesh reference member
  7910. }
  7911. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7912. function serializeAsColorCurves(sourceName) {
  7913. return generateSerializableMember(7, sourceName); // color curves
  7914. }
  7915. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7916. function serializeAsColor4(sourceName) {
  7917. return generateSerializableMember(8, sourceName); // color 4
  7918. }
  7919. BABYLON.serializeAsColor4 = serializeAsColor4;
  7920. function serializeAsImageProcessingConfiguration(sourceName) {
  7921. return generateSerializableMember(9, sourceName); // image processing
  7922. }
  7923. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7924. function serializeAsQuaternion(sourceName) {
  7925. return generateSerializableMember(10, sourceName); // quaternion member
  7926. }
  7927. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7928. /**
  7929. * Decorator used to define property that can be serialized as reference to a camera
  7930. * @param sourceName defines the name of the property to decorate
  7931. */
  7932. function serializeAsCameraReference(sourceName) {
  7933. return generateSerializableMember(11, sourceName); // camera reference member
  7934. }
  7935. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7936. var SerializationHelper = /** @class */ (function () {
  7937. function SerializationHelper() {
  7938. }
  7939. SerializationHelper.Serialize = function (entity, serializationObject) {
  7940. if (!serializationObject) {
  7941. serializationObject = {};
  7942. }
  7943. // Tags
  7944. if (BABYLON.Tags) {
  7945. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7946. }
  7947. var serializedProperties = getMergedStore(entity);
  7948. // Properties
  7949. for (var property in serializedProperties) {
  7950. var propertyDescriptor = serializedProperties[property];
  7951. var targetPropertyName = propertyDescriptor.sourceName || property;
  7952. var propertyType = propertyDescriptor.type;
  7953. var sourceProperty = entity[property];
  7954. if (sourceProperty !== undefined && sourceProperty !== null) {
  7955. switch (propertyType) {
  7956. case 0: // Value
  7957. serializationObject[targetPropertyName] = sourceProperty;
  7958. break;
  7959. case 1: // Texture
  7960. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7961. break;
  7962. case 2: // Color3
  7963. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7964. break;
  7965. case 3: // FresnelParameters
  7966. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7967. break;
  7968. case 4: // Vector2
  7969. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7970. break;
  7971. case 5: // Vector3
  7972. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7973. break;
  7974. case 6: // Mesh reference
  7975. serializationObject[targetPropertyName] = sourceProperty.id;
  7976. break;
  7977. case 7: // Color Curves
  7978. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7979. break;
  7980. case 8: // Color 4
  7981. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7982. break;
  7983. case 9: // Image Processing
  7984. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7985. break;
  7986. case 10: // Quaternion
  7987. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7988. break;
  7989. case 11: // Camera reference
  7990. serializationObject[targetPropertyName] = sourceProperty.id;
  7991. break;
  7992. }
  7993. }
  7994. }
  7995. return serializationObject;
  7996. };
  7997. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7998. if (rootUrl === void 0) { rootUrl = null; }
  7999. var destination = creationFunction();
  8000. if (!rootUrl) {
  8001. rootUrl = "";
  8002. }
  8003. // Tags
  8004. if (BABYLON.Tags) {
  8005. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8006. }
  8007. var classStore = getMergedStore(destination);
  8008. // Properties
  8009. for (var property in classStore) {
  8010. var propertyDescriptor = classStore[property];
  8011. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8012. var propertyType = propertyDescriptor.type;
  8013. if (sourceProperty !== undefined && sourceProperty !== null) {
  8014. var dest = destination;
  8015. switch (propertyType) {
  8016. case 0: // Value
  8017. dest[property] = sourceProperty;
  8018. break;
  8019. case 1: // Texture
  8020. if (scene) {
  8021. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8022. }
  8023. break;
  8024. case 2: // Color3
  8025. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8026. break;
  8027. case 3: // FresnelParameters
  8028. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8029. break;
  8030. case 4: // Vector2
  8031. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8032. break;
  8033. case 5: // Vector3
  8034. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8035. break;
  8036. case 6: // Mesh reference
  8037. if (scene) {
  8038. dest[property] = scene.getLastMeshByID(sourceProperty);
  8039. }
  8040. break;
  8041. case 7: // Color Curves
  8042. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8043. break;
  8044. case 8: // Color 4
  8045. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8046. break;
  8047. case 9: // Image Processing
  8048. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8049. break;
  8050. case 10: // Quaternion
  8051. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8052. break;
  8053. case 11: // Camera reference
  8054. if (scene) {
  8055. dest[property] = scene.getCameraByID(sourceProperty);
  8056. }
  8057. break;
  8058. }
  8059. }
  8060. }
  8061. return destination;
  8062. };
  8063. SerializationHelper.Clone = function (creationFunction, source) {
  8064. return _copySource(creationFunction, source, false);
  8065. };
  8066. SerializationHelper.Instanciate = function (creationFunction, source) {
  8067. return _copySource(creationFunction, source, true);
  8068. };
  8069. return SerializationHelper;
  8070. }());
  8071. BABYLON.SerializationHelper = SerializationHelper;
  8072. })(BABYLON || (BABYLON = {}));
  8073. //# sourceMappingURL=babylon.decorators.js.map
  8074. var BABYLON;
  8075. (function (BABYLON) {
  8076. /**
  8077. * Wrapper class for promise with external resolve and reject.
  8078. */
  8079. var Deferred = /** @class */ (function () {
  8080. /**
  8081. * Constructor for this deferred object.
  8082. */
  8083. function Deferred() {
  8084. var _this = this;
  8085. this.promise = new Promise(function (resolve, reject) {
  8086. _this._resolve = resolve;
  8087. _this._reject = reject;
  8088. });
  8089. }
  8090. Object.defineProperty(Deferred.prototype, "resolve", {
  8091. /**
  8092. * The resolve method of the promise associated with this deferred object.
  8093. */
  8094. get: function () {
  8095. return this._resolve;
  8096. },
  8097. enumerable: true,
  8098. configurable: true
  8099. });
  8100. Object.defineProperty(Deferred.prototype, "reject", {
  8101. /**
  8102. * The reject method of the promise associated with this deferred object.
  8103. */
  8104. get: function () {
  8105. return this._reject;
  8106. },
  8107. enumerable: true,
  8108. configurable: true
  8109. });
  8110. return Deferred;
  8111. }());
  8112. BABYLON.Deferred = Deferred;
  8113. })(BABYLON || (BABYLON = {}));
  8114. //# sourceMappingURL=babylon.deferred.js.map
  8115. var BABYLON;
  8116. (function (BABYLON) {
  8117. /**
  8118. * A class serves as a medium between the observable and its observers
  8119. */
  8120. var EventState = /** @class */ (function () {
  8121. /**
  8122. * Create a new EventState
  8123. * @param mask defines the mask associated with this state
  8124. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8125. * @param target defines the original target of the state
  8126. * @param currentTarget defines the current target of the state
  8127. */
  8128. function EventState(mask, skipNextObservers, target, currentTarget) {
  8129. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8130. this.initalize(mask, skipNextObservers, target, currentTarget);
  8131. }
  8132. /**
  8133. * Initialize the current event state
  8134. * @param mask defines the mask associated with this state
  8135. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8136. * @param target defines the original target of the state
  8137. * @param currentTarget defines the current target of the state
  8138. * @returns the current event state
  8139. */
  8140. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8141. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8142. this.mask = mask;
  8143. this.skipNextObservers = skipNextObservers;
  8144. this.target = target;
  8145. this.currentTarget = currentTarget;
  8146. return this;
  8147. };
  8148. return EventState;
  8149. }());
  8150. BABYLON.EventState = EventState;
  8151. /**
  8152. * Represent an Observer registered to a given Observable object.
  8153. */
  8154. var Observer = /** @class */ (function () {
  8155. /**
  8156. * Creates a new observer
  8157. * @param callback defines the callback to call when the observer is notified
  8158. * @param mask defines the mask of the observer (used to filter notifications)
  8159. * @param scope defines the current scope used to restore the JS context
  8160. */
  8161. function Observer(
  8162. /**
  8163. * Defines the callback to call when the observer is notified
  8164. */
  8165. callback,
  8166. /**
  8167. * Defines the mask of the observer (used to filter notifications)
  8168. */
  8169. mask,
  8170. /**
  8171. * Defines the current scope used to restore the JS context
  8172. */
  8173. scope) {
  8174. if (scope === void 0) { scope = null; }
  8175. this.callback = callback;
  8176. this.mask = mask;
  8177. this.scope = scope;
  8178. /** @hidden */
  8179. this._willBeUnregistered = false;
  8180. /**
  8181. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8182. */
  8183. this.unregisterOnNextCall = false;
  8184. }
  8185. return Observer;
  8186. }());
  8187. BABYLON.Observer = Observer;
  8188. /**
  8189. * Represent a list of observers registered to multiple Observables object.
  8190. */
  8191. var MultiObserver = /** @class */ (function () {
  8192. function MultiObserver() {
  8193. }
  8194. /**
  8195. * Release associated resources
  8196. */
  8197. MultiObserver.prototype.dispose = function () {
  8198. if (this._observers && this._observables) {
  8199. for (var index = 0; index < this._observers.length; index++) {
  8200. this._observables[index].remove(this._observers[index]);
  8201. }
  8202. }
  8203. this._observers = null;
  8204. this._observables = null;
  8205. };
  8206. /**
  8207. * Raise a callback when one of the observable will notify
  8208. * @param observables defines a list of observables to watch
  8209. * @param callback defines the callback to call on notification
  8210. * @param mask defines the mask used to filter notifications
  8211. * @param scope defines the current scope used to restore the JS context
  8212. * @returns the new MultiObserver
  8213. */
  8214. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8215. if (mask === void 0) { mask = -1; }
  8216. if (scope === void 0) { scope = null; }
  8217. var result = new MultiObserver();
  8218. result._observers = new Array();
  8219. result._observables = observables;
  8220. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8221. var observable = observables_1[_i];
  8222. var observer = observable.add(callback, mask, false, scope);
  8223. if (observer) {
  8224. result._observers.push(observer);
  8225. }
  8226. }
  8227. return result;
  8228. };
  8229. return MultiObserver;
  8230. }());
  8231. BABYLON.MultiObserver = MultiObserver;
  8232. /**
  8233. * The Observable class is a simple implementation of the Observable pattern.
  8234. *
  8235. * 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.
  8236. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8237. * 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).
  8238. * 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.
  8239. */
  8240. var Observable = /** @class */ (function () {
  8241. /**
  8242. * Creates a new observable
  8243. * @param onObserverAdded defines a callback to call when a new observer is added
  8244. */
  8245. function Observable(onObserverAdded) {
  8246. this._observers = new Array();
  8247. this._eventState = new EventState(0);
  8248. if (onObserverAdded) {
  8249. this._onObserverAdded = onObserverAdded;
  8250. }
  8251. }
  8252. /**
  8253. * Create a new Observer with the specified callback
  8254. * @param callback the callback that will be executed for that Observer
  8255. * @param mask the mask used to filter observers
  8256. * @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.
  8257. * @param scope optional scope for the callback to be called from
  8258. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8259. * @returns the new observer created for the callback
  8260. */
  8261. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8262. if (mask === void 0) { mask = -1; }
  8263. if (insertFirst === void 0) { insertFirst = false; }
  8264. if (scope === void 0) { scope = null; }
  8265. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8266. if (!callback) {
  8267. return null;
  8268. }
  8269. var observer = new Observer(callback, mask, scope);
  8270. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8271. if (insertFirst) {
  8272. this._observers.unshift(observer);
  8273. }
  8274. else {
  8275. this._observers.push(observer);
  8276. }
  8277. if (this._onObserverAdded) {
  8278. this._onObserverAdded(observer);
  8279. }
  8280. return observer;
  8281. };
  8282. /**
  8283. * Create a new Observer with the specified callback and unregisters after the next notification
  8284. * @param callback the callback that will be executed for that Observer
  8285. * @returns the new observer created for the callback
  8286. */
  8287. Observable.prototype.addOnce = function (callback) {
  8288. return this.add(callback, undefined, undefined, undefined, true);
  8289. };
  8290. /**
  8291. * Remove an Observer from the Observable object
  8292. * @param observer the instance of the Observer to remove
  8293. * @returns false if it doesn't belong to this Observable
  8294. */
  8295. Observable.prototype.remove = function (observer) {
  8296. if (!observer) {
  8297. return false;
  8298. }
  8299. var index = this._observers.indexOf(observer);
  8300. if (index !== -1) {
  8301. this._deferUnregister(observer);
  8302. return true;
  8303. }
  8304. return false;
  8305. };
  8306. /**
  8307. * Remove a callback from the Observable object
  8308. * @param callback the callback to remove
  8309. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8310. * @returns false if it doesn't belong to this Observable
  8311. */
  8312. Observable.prototype.removeCallback = function (callback, scope) {
  8313. for (var index = 0; index < this._observers.length; index++) {
  8314. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8315. this._deferUnregister(this._observers[index]);
  8316. return true;
  8317. }
  8318. }
  8319. return false;
  8320. };
  8321. Observable.prototype._deferUnregister = function (observer) {
  8322. var _this = this;
  8323. observer.unregisterOnNextCall = false;
  8324. observer._willBeUnregistered = true;
  8325. BABYLON.Tools.SetImmediate(function () {
  8326. _this._remove(observer);
  8327. });
  8328. };
  8329. // This should only be called when not iterating over _observers to avoid callback skipping.
  8330. // Removes an observer from the _observer Array.
  8331. Observable.prototype._remove = function (observer) {
  8332. if (!observer) {
  8333. return false;
  8334. }
  8335. var index = this._observers.indexOf(observer);
  8336. if (index !== -1) {
  8337. this._observers.splice(index, 1);
  8338. return true;
  8339. }
  8340. return false;
  8341. };
  8342. /**
  8343. * Notify all Observers by calling their respective callback with the given data
  8344. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8345. * @param eventData defines the data to send to all observers
  8346. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8347. * @param target defines the original target of the state
  8348. * @param currentTarget defines the current target of the state
  8349. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8350. */
  8351. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8352. if (mask === void 0) { mask = -1; }
  8353. if (!this._observers.length) {
  8354. return true;
  8355. }
  8356. var state = this._eventState;
  8357. state.mask = mask;
  8358. state.target = target;
  8359. state.currentTarget = currentTarget;
  8360. state.skipNextObservers = false;
  8361. state.lastReturnValue = eventData;
  8362. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8363. var obs = _a[_i];
  8364. if (obs._willBeUnregistered) {
  8365. continue;
  8366. }
  8367. if (obs.mask & mask) {
  8368. if (obs.scope) {
  8369. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8370. }
  8371. else {
  8372. state.lastReturnValue = obs.callback(eventData, state);
  8373. }
  8374. if (obs.unregisterOnNextCall) {
  8375. this._deferUnregister(obs);
  8376. }
  8377. }
  8378. if (state.skipNextObservers) {
  8379. return false;
  8380. }
  8381. }
  8382. return true;
  8383. };
  8384. /**
  8385. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8386. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8387. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8388. * and it is crucial that all callbacks will be executed.
  8389. * The order of the callbacks is kept, callbacks are not executed parallel.
  8390. *
  8391. * @param eventData The data to be sent to each callback
  8392. * @param mask is used to filter observers defaults to -1
  8393. * @param target defines the callback target (see EventState)
  8394. * @param currentTarget defines he current object in the bubbling phase
  8395. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8396. */
  8397. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8398. var _this = this;
  8399. if (mask === void 0) { mask = -1; }
  8400. // create an empty promise
  8401. var p = Promise.resolve(eventData);
  8402. // no observers? return this promise.
  8403. if (!this._observers.length) {
  8404. return p;
  8405. }
  8406. var state = this._eventState;
  8407. state.mask = mask;
  8408. state.target = target;
  8409. state.currentTarget = currentTarget;
  8410. state.skipNextObservers = false;
  8411. // execute one callback after another (not using Promise.all, the order is important)
  8412. this._observers.forEach(function (obs) {
  8413. if (state.skipNextObservers) {
  8414. return;
  8415. }
  8416. if (obs._willBeUnregistered) {
  8417. return;
  8418. }
  8419. if (obs.mask & mask) {
  8420. if (obs.scope) {
  8421. p = p.then(function (lastReturnedValue) {
  8422. state.lastReturnValue = lastReturnedValue;
  8423. return obs.callback.apply(obs.scope, [eventData, state]);
  8424. });
  8425. }
  8426. else {
  8427. p = p.then(function (lastReturnedValue) {
  8428. state.lastReturnValue = lastReturnedValue;
  8429. return obs.callback(eventData, state);
  8430. });
  8431. }
  8432. if (obs.unregisterOnNextCall) {
  8433. _this._deferUnregister(obs);
  8434. }
  8435. }
  8436. });
  8437. // return the eventData
  8438. return p.then(function () { return eventData; });
  8439. };
  8440. /**
  8441. * Notify a specific observer
  8442. * @param observer defines the observer to notify
  8443. * @param eventData defines the data to be sent to each callback
  8444. * @param mask is used to filter observers defaults to -1
  8445. */
  8446. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8447. if (mask === void 0) { mask = -1; }
  8448. var state = this._eventState;
  8449. state.mask = mask;
  8450. state.skipNextObservers = false;
  8451. observer.callback(eventData, state);
  8452. };
  8453. /**
  8454. * Gets a boolean indicating if the observable has at least one observer
  8455. * @returns true is the Observable has at least one Observer registered
  8456. */
  8457. Observable.prototype.hasObservers = function () {
  8458. return this._observers.length > 0;
  8459. };
  8460. /**
  8461. * Clear the list of observers
  8462. */
  8463. Observable.prototype.clear = function () {
  8464. this._observers = new Array();
  8465. this._onObserverAdded = null;
  8466. };
  8467. /**
  8468. * Clone the current observable
  8469. * @returns a new observable
  8470. */
  8471. Observable.prototype.clone = function () {
  8472. var result = new Observable();
  8473. result._observers = this._observers.slice(0);
  8474. return result;
  8475. };
  8476. /**
  8477. * Does this observable handles observer registered with a given mask
  8478. * @param mask defines the mask to be tested
  8479. * @return whether or not one observer registered with the given mask is handeled
  8480. **/
  8481. Observable.prototype.hasSpecificMask = function (mask) {
  8482. if (mask === void 0) { mask = -1; }
  8483. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8484. var obs = _a[_i];
  8485. if (obs.mask & mask || obs.mask === mask) {
  8486. return true;
  8487. }
  8488. }
  8489. return false;
  8490. };
  8491. return Observable;
  8492. }());
  8493. BABYLON.Observable = Observable;
  8494. })(BABYLON || (BABYLON = {}));
  8495. //# sourceMappingURL=babylon.observable.js.map
  8496. var BABYLON;
  8497. (function (BABYLON) {
  8498. var SmartArray = /** @class */ (function () {
  8499. function SmartArray(capacity) {
  8500. this.length = 0;
  8501. this.data = new Array(capacity);
  8502. this._id = SmartArray._GlobalId++;
  8503. }
  8504. SmartArray.prototype.push = function (value) {
  8505. this.data[this.length++] = value;
  8506. if (this.length > this.data.length) {
  8507. this.data.length *= 2;
  8508. }
  8509. };
  8510. SmartArray.prototype.forEach = function (func) {
  8511. for (var index = 0; index < this.length; index++) {
  8512. func(this.data[index]);
  8513. }
  8514. };
  8515. SmartArray.prototype.sort = function (compareFn) {
  8516. this.data.sort(compareFn);
  8517. };
  8518. SmartArray.prototype.reset = function () {
  8519. this.length = 0;
  8520. };
  8521. SmartArray.prototype.dispose = function () {
  8522. this.reset();
  8523. if (this.data) {
  8524. this.data.length = 0;
  8525. this.data = [];
  8526. }
  8527. };
  8528. SmartArray.prototype.concat = function (array) {
  8529. if (array.length === 0) {
  8530. return;
  8531. }
  8532. if (this.length + array.length > this.data.length) {
  8533. this.data.length = (this.length + array.length) * 2;
  8534. }
  8535. for (var index = 0; index < array.length; index++) {
  8536. this.data[this.length++] = (array.data || array)[index];
  8537. }
  8538. };
  8539. SmartArray.prototype.indexOf = function (value) {
  8540. var position = this.data.indexOf(value);
  8541. if (position >= this.length) {
  8542. return -1;
  8543. }
  8544. return position;
  8545. };
  8546. SmartArray.prototype.contains = function (value) {
  8547. return this.data.indexOf(value) !== -1;
  8548. };
  8549. // Statics
  8550. SmartArray._GlobalId = 0;
  8551. return SmartArray;
  8552. }());
  8553. BABYLON.SmartArray = SmartArray;
  8554. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8555. __extends(SmartArrayNoDuplicate, _super);
  8556. function SmartArrayNoDuplicate() {
  8557. var _this = _super !== null && _super.apply(this, arguments) || this;
  8558. _this._duplicateId = 0;
  8559. return _this;
  8560. }
  8561. SmartArrayNoDuplicate.prototype.push = function (value) {
  8562. _super.prototype.push.call(this, value);
  8563. if (!value.__smartArrayFlags) {
  8564. value.__smartArrayFlags = {};
  8565. }
  8566. value.__smartArrayFlags[this._id] = this._duplicateId;
  8567. };
  8568. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8569. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8570. return false;
  8571. }
  8572. this.push(value);
  8573. return true;
  8574. };
  8575. SmartArrayNoDuplicate.prototype.reset = function () {
  8576. _super.prototype.reset.call(this);
  8577. this._duplicateId++;
  8578. };
  8579. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8580. if (array.length === 0) {
  8581. return;
  8582. }
  8583. if (this.length + array.length > this.data.length) {
  8584. this.data.length = (this.length + array.length) * 2;
  8585. }
  8586. for (var index = 0; index < array.length; index++) {
  8587. var item = (array.data || array)[index];
  8588. this.pushNoDuplicate(item);
  8589. }
  8590. };
  8591. return SmartArrayNoDuplicate;
  8592. }(SmartArray));
  8593. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8594. })(BABYLON || (BABYLON = {}));
  8595. //# sourceMappingURL=babylon.smartArray.js.map
  8596. var BABYLON;
  8597. (function (BABYLON) {
  8598. /** Class used to store color gradient */
  8599. var ColorGradient = /** @class */ (function () {
  8600. function ColorGradient() {
  8601. }
  8602. /**
  8603. * Will get a color picked randomly between color1 and color2.
  8604. * If color2 is undefined then color1 will be used
  8605. * @param result defines the target Color4 to store the result in
  8606. */
  8607. ColorGradient.prototype.getColorToRef = function (result) {
  8608. if (!this.color2) {
  8609. result.copyFrom(this.color1);
  8610. return;
  8611. }
  8612. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8613. };
  8614. return ColorGradient;
  8615. }());
  8616. BABYLON.ColorGradient = ColorGradient;
  8617. /** Class used to store factor gradient */
  8618. var FactorGradient = /** @class */ (function () {
  8619. function FactorGradient() {
  8620. }
  8621. /**
  8622. * Will get a number picked randomly between factor1 and factor2.
  8623. * If factor2 is undefined then factor1 will be used
  8624. * @returns the picked number
  8625. */
  8626. FactorGradient.prototype.getFactor = function () {
  8627. if (this.factor2 === undefined) {
  8628. return this.factor1;
  8629. }
  8630. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8631. };
  8632. return FactorGradient;
  8633. }());
  8634. BABYLON.FactorGradient = FactorGradient;
  8635. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8636. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8637. var LoadFileError = /** @class */ (function (_super) {
  8638. __extends(LoadFileError, _super);
  8639. function LoadFileError(message, request) {
  8640. var _this = _super.call(this, message) || this;
  8641. _this.request = request;
  8642. _this.name = "LoadFileError";
  8643. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8644. return _this;
  8645. }
  8646. // Polyfill for Object.setPrototypeOf if necessary.
  8647. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8648. return LoadFileError;
  8649. }(Error));
  8650. BABYLON.LoadFileError = LoadFileError;
  8651. var RetryStrategy = /** @class */ (function () {
  8652. function RetryStrategy() {
  8653. }
  8654. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8655. if (maxRetries === void 0) { maxRetries = 3; }
  8656. if (baseInterval === void 0) { baseInterval = 500; }
  8657. return function (url, request, retryIndex) {
  8658. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8659. return -1;
  8660. }
  8661. return Math.pow(2, retryIndex) * baseInterval;
  8662. };
  8663. };
  8664. return RetryStrategy;
  8665. }());
  8666. BABYLON.RetryStrategy = RetryStrategy;
  8667. // Screenshots
  8668. var screenshotCanvas;
  8669. var cloneValue = function (source, destinationObject) {
  8670. if (!source)
  8671. return null;
  8672. if (source instanceof BABYLON.Mesh) {
  8673. return null;
  8674. }
  8675. if (source instanceof BABYLON.SubMesh) {
  8676. return source.clone(destinationObject);
  8677. }
  8678. else if (source.clone) {
  8679. return source.clone();
  8680. }
  8681. return null;
  8682. };
  8683. var Tools = /** @class */ (function () {
  8684. function Tools() {
  8685. }
  8686. /**
  8687. * Interpolates between a and b via alpha
  8688. * @param a The lower value (returned when alpha = 0)
  8689. * @param b The upper value (returned when alpha = 1)
  8690. * @param alpha The interpolation-factor
  8691. * @return The mixed value
  8692. */
  8693. Tools.Mix = function (a, b, alpha) {
  8694. return a * (1 - alpha) + b * alpha;
  8695. };
  8696. Tools.Instantiate = function (className) {
  8697. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8698. return Tools.RegisteredExternalClasses[className];
  8699. }
  8700. var arr = className.split(".");
  8701. var fn = (window || this);
  8702. for (var i = 0, len = arr.length; i < len; i++) {
  8703. fn = fn[arr[i]];
  8704. }
  8705. if (typeof fn !== "function") {
  8706. return null;
  8707. }
  8708. return fn;
  8709. };
  8710. /**
  8711. * Provides a slice function that will work even on IE
  8712. * @param data defines the array to slice
  8713. * @param start defines the start of the data (optional)
  8714. * @param end defines the end of the data (optional)
  8715. * @returns the new sliced array
  8716. */
  8717. Tools.Slice = function (data, start, end) {
  8718. if (data.slice) {
  8719. return data.slice(start, end);
  8720. }
  8721. return Array.prototype.slice.call(data, start, end);
  8722. };
  8723. Tools.SetImmediate = function (action) {
  8724. if (window.setImmediate) {
  8725. window.setImmediate(action);
  8726. }
  8727. else {
  8728. setTimeout(action, 1);
  8729. }
  8730. };
  8731. Tools.IsExponentOfTwo = function (value) {
  8732. var count = 1;
  8733. do {
  8734. count *= 2;
  8735. } while (count < value);
  8736. return count === value;
  8737. };
  8738. /**
  8739. * Returns the nearest 32-bit single precision float representation of a Number
  8740. * @param value A Number. If the parameter is of a different type, it will get converted
  8741. * to a number or to NaN if it cannot be converted
  8742. * @returns number
  8743. */
  8744. Tools.FloatRound = function (value) {
  8745. if (Math.fround) {
  8746. return Math.fround(value);
  8747. }
  8748. return (Tools._tmpFloatArray[0] = value);
  8749. };
  8750. /**
  8751. * Find the next highest power of two.
  8752. * @param x Number to start search from.
  8753. * @return Next highest power of two.
  8754. */
  8755. Tools.CeilingPOT = function (x) {
  8756. x--;
  8757. x |= x >> 1;
  8758. x |= x >> 2;
  8759. x |= x >> 4;
  8760. x |= x >> 8;
  8761. x |= x >> 16;
  8762. x++;
  8763. return x;
  8764. };
  8765. /**
  8766. * Find the next lowest power of two.
  8767. * @param x Number to start search from.
  8768. * @return Next lowest power of two.
  8769. */
  8770. Tools.FloorPOT = function (x) {
  8771. x = x | (x >> 1);
  8772. x = x | (x >> 2);
  8773. x = x | (x >> 4);
  8774. x = x | (x >> 8);
  8775. x = x | (x >> 16);
  8776. return x - (x >> 1);
  8777. };
  8778. /**
  8779. * Find the nearest power of two.
  8780. * @param x Number to start search from.
  8781. * @return Next nearest power of two.
  8782. */
  8783. Tools.NearestPOT = function (x) {
  8784. var c = Tools.CeilingPOT(x);
  8785. var f = Tools.FloorPOT(x);
  8786. return (c - x) > (x - f) ? f : c;
  8787. };
  8788. Tools.GetExponentOfTwo = function (value, max, mode) {
  8789. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8790. var pot;
  8791. switch (mode) {
  8792. case BABYLON.Engine.SCALEMODE_FLOOR:
  8793. pot = Tools.FloorPOT(value);
  8794. break;
  8795. case BABYLON.Engine.SCALEMODE_NEAREST:
  8796. pot = Tools.NearestPOT(value);
  8797. break;
  8798. case BABYLON.Engine.SCALEMODE_CEILING:
  8799. default:
  8800. pot = Tools.CeilingPOT(value);
  8801. break;
  8802. }
  8803. return Math.min(pot, max);
  8804. };
  8805. Tools.GetFilename = function (path) {
  8806. var index = path.lastIndexOf("/");
  8807. if (index < 0)
  8808. return path;
  8809. return path.substring(index + 1);
  8810. };
  8811. /**
  8812. * Extracts the "folder" part of a path (everything before the filename).
  8813. * @param uri The URI to extract the info from
  8814. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8815. * @returns The "folder" part of the path
  8816. */
  8817. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8818. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8819. var index = uri.lastIndexOf("/");
  8820. if (index < 0) {
  8821. if (returnUnchangedIfNoSlash) {
  8822. return uri;
  8823. }
  8824. return "";
  8825. }
  8826. return uri.substring(0, index + 1);
  8827. };
  8828. Tools.GetDOMTextContent = function (element) {
  8829. var result = "";
  8830. var child = element.firstChild;
  8831. while (child) {
  8832. if (child.nodeType === 3) {
  8833. result += child.textContent;
  8834. }
  8835. child = child.nextSibling;
  8836. }
  8837. return result;
  8838. };
  8839. Tools.ToDegrees = function (angle) {
  8840. return angle * 180 / Math.PI;
  8841. };
  8842. Tools.ToRadians = function (angle) {
  8843. return angle * Math.PI / 180;
  8844. };
  8845. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8846. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8847. var output = "";
  8848. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8849. var i = 0;
  8850. var bytes = new Uint8Array(buffer);
  8851. while (i < bytes.length) {
  8852. chr1 = bytes[i++];
  8853. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8854. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8855. enc1 = chr1 >> 2;
  8856. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8857. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8858. enc4 = chr3 & 63;
  8859. if (isNaN(chr2)) {
  8860. enc3 = enc4 = 64;
  8861. }
  8862. else if (isNaN(chr3)) {
  8863. enc4 = 64;
  8864. }
  8865. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8866. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8867. }
  8868. return "data:image/png;base64," + output;
  8869. };
  8870. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8871. if (bias === void 0) { bias = null; }
  8872. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8873. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8874. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8875. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8876. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8877. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8878. }
  8879. if (bias) {
  8880. minimum.x -= minimum.x * bias.x + bias.y;
  8881. minimum.y -= minimum.y * bias.x + bias.y;
  8882. minimum.z -= minimum.z * bias.x + bias.y;
  8883. maximum.x += maximum.x * bias.x + bias.y;
  8884. maximum.y += maximum.y * bias.x + bias.y;
  8885. maximum.z += maximum.z * bias.x + bias.y;
  8886. }
  8887. return {
  8888. minimum: minimum,
  8889. maximum: maximum
  8890. };
  8891. };
  8892. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8893. if (bias === void 0) { bias = null; }
  8894. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8895. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8896. if (!stride) {
  8897. stride = 3;
  8898. }
  8899. for (var index = start; index < start + count; index++) {
  8900. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8901. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8902. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8903. }
  8904. if (bias) {
  8905. minimum.x -= minimum.x * bias.x + bias.y;
  8906. minimum.y -= minimum.y * bias.x + bias.y;
  8907. minimum.z -= minimum.z * bias.x + bias.y;
  8908. maximum.x += maximum.x * bias.x + bias.y;
  8909. maximum.y += maximum.y * bias.x + bias.y;
  8910. maximum.z += maximum.z * bias.x + bias.y;
  8911. }
  8912. return {
  8913. minimum: minimum,
  8914. maximum: maximum
  8915. };
  8916. };
  8917. Tools.Vector2ArrayFeeder = function (array) {
  8918. return function (index) {
  8919. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8920. var length = isFloatArray ? array.length / 2 : array.length;
  8921. if (index >= length) {
  8922. return null;
  8923. }
  8924. if (isFloatArray) {
  8925. var fa = array;
  8926. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8927. }
  8928. var a = array;
  8929. return a[index];
  8930. };
  8931. };
  8932. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8933. if (bias === void 0) { bias = null; }
  8934. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8935. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8936. var i = 0;
  8937. var cur = feeder(i++);
  8938. while (cur) {
  8939. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8940. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8941. cur = feeder(i++);
  8942. }
  8943. if (bias) {
  8944. minimum.x -= minimum.x * bias.x + bias.y;
  8945. minimum.y -= minimum.y * bias.x + bias.y;
  8946. maximum.x += maximum.x * bias.x + bias.y;
  8947. maximum.y += maximum.y * bias.x + bias.y;
  8948. }
  8949. return {
  8950. minimum: minimum,
  8951. maximum: maximum
  8952. };
  8953. };
  8954. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8955. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8956. return null;
  8957. return Array.isArray(obj) ? obj : [obj];
  8958. };
  8959. // Misc.
  8960. Tools.GetPointerPrefix = function () {
  8961. var eventPrefix = "pointer";
  8962. // Check if pointer events are supported
  8963. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8964. eventPrefix = "mouse";
  8965. }
  8966. return eventPrefix;
  8967. };
  8968. /**
  8969. * @param func - the function to be called
  8970. * @param requester - the object that will request the next frame. Falls back to window.
  8971. */
  8972. Tools.QueueNewFrame = function (func, requester) {
  8973. if (!Tools.IsWindowObjectExist()) {
  8974. return setTimeout(func, 16);
  8975. }
  8976. if (!requester) {
  8977. requester = window;
  8978. }
  8979. if (requester.requestAnimationFrame) {
  8980. return requester.requestAnimationFrame(func);
  8981. }
  8982. else if (requester.msRequestAnimationFrame) {
  8983. return requester.msRequestAnimationFrame(func);
  8984. }
  8985. else if (requester.webkitRequestAnimationFrame) {
  8986. return requester.webkitRequestAnimationFrame(func);
  8987. }
  8988. else if (requester.mozRequestAnimationFrame) {
  8989. return requester.mozRequestAnimationFrame(func);
  8990. }
  8991. else if (requester.oRequestAnimationFrame) {
  8992. return requester.oRequestAnimationFrame(func);
  8993. }
  8994. else {
  8995. return window.setTimeout(func, 16);
  8996. }
  8997. };
  8998. Tools.RequestFullscreen = function (element) {
  8999. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9000. if (!requestFunction)
  9001. return;
  9002. requestFunction.call(element);
  9003. };
  9004. Tools.ExitFullscreen = function () {
  9005. if (document.exitFullscreen) {
  9006. document.exitFullscreen();
  9007. }
  9008. else if (document.mozCancelFullScreen) {
  9009. document.mozCancelFullScreen();
  9010. }
  9011. else if (document.webkitCancelFullScreen) {
  9012. document.webkitCancelFullScreen();
  9013. }
  9014. else if (document.msCancelFullScreen) {
  9015. document.msCancelFullScreen();
  9016. }
  9017. };
  9018. Tools.SetCorsBehavior = function (url, element) {
  9019. if (url && url.indexOf("data:") === 0) {
  9020. return;
  9021. }
  9022. if (Tools.CorsBehavior) {
  9023. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9024. element.crossOrigin = Tools.CorsBehavior;
  9025. }
  9026. else {
  9027. var result = Tools.CorsBehavior(url);
  9028. if (result) {
  9029. element.crossOrigin = result;
  9030. }
  9031. }
  9032. }
  9033. };
  9034. // External files
  9035. Tools.CleanUrl = function (url) {
  9036. url = url.replace(/#/mg, "%23");
  9037. return url;
  9038. };
  9039. /**
  9040. * Loads an image as an HTMLImageElement.
  9041. * @param input url string, ArrayBuffer, or Blob to load
  9042. * @param onLoad callback called when the image successfully loads
  9043. * @param onError callback called when the image fails to load
  9044. * @param database database for caching
  9045. * @returns the HTMLImageElement of the loaded image
  9046. */
  9047. Tools.LoadImage = function (input, onLoad, onError, database) {
  9048. var url;
  9049. var usingObjectURL = false;
  9050. if (input instanceof ArrayBuffer) {
  9051. url = URL.createObjectURL(new Blob([input]));
  9052. usingObjectURL = true;
  9053. }
  9054. else if (input instanceof Blob) {
  9055. url = URL.createObjectURL(input);
  9056. usingObjectURL = true;
  9057. }
  9058. else {
  9059. url = Tools.CleanUrl(input);
  9060. url = Tools.PreprocessUrl(input);
  9061. }
  9062. var img = new Image();
  9063. Tools.SetCorsBehavior(url, img);
  9064. var loadHandler = function () {
  9065. if (usingObjectURL && img.src) {
  9066. URL.revokeObjectURL(img.src);
  9067. }
  9068. img.removeEventListener("load", loadHandler);
  9069. img.removeEventListener("error", errorHandler);
  9070. onLoad(img);
  9071. };
  9072. var errorHandler = function (err) {
  9073. if (usingObjectURL && img.src) {
  9074. URL.revokeObjectURL(img.src);
  9075. }
  9076. img.removeEventListener("load", loadHandler);
  9077. img.removeEventListener("error", errorHandler);
  9078. Tools.Error("Error while trying to load image: " + input);
  9079. if (onError) {
  9080. onError("Error while trying to load image: " + input, err);
  9081. }
  9082. };
  9083. img.addEventListener("load", loadHandler);
  9084. img.addEventListener("error", errorHandler);
  9085. var noIndexedDB = function () {
  9086. img.src = url;
  9087. };
  9088. var loadFromIndexedDB = function () {
  9089. if (database) {
  9090. database.loadImageFromDB(url, img);
  9091. }
  9092. };
  9093. //ANY database to do!
  9094. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9095. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9096. }
  9097. else {
  9098. if (url.indexOf("file:") !== -1) {
  9099. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9100. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9101. try {
  9102. var blobURL;
  9103. try {
  9104. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9105. }
  9106. catch (ex) {
  9107. // Chrome doesn't support oneTimeOnly parameter
  9108. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9109. }
  9110. img.src = blobURL;
  9111. usingObjectURL = true;
  9112. }
  9113. catch (e) {
  9114. img.src = "";
  9115. }
  9116. return img;
  9117. }
  9118. }
  9119. noIndexedDB();
  9120. }
  9121. return img;
  9122. };
  9123. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9124. url = Tools.CleanUrl(url);
  9125. url = Tools.PreprocessUrl(url);
  9126. // If file and file input are set
  9127. if (url.indexOf("file:") !== -1) {
  9128. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9129. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9130. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9131. }
  9132. }
  9133. var loadUrl = Tools.BaseUrl + url;
  9134. var aborted = false;
  9135. var fileRequest = {
  9136. onCompleteObservable: new BABYLON.Observable(),
  9137. abort: function () { return aborted = true; },
  9138. };
  9139. var requestFile = function () {
  9140. var request = new XMLHttpRequest();
  9141. var retryHandle = null;
  9142. fileRequest.abort = function () {
  9143. aborted = true;
  9144. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9145. request.abort();
  9146. }
  9147. if (retryHandle !== null) {
  9148. clearTimeout(retryHandle);
  9149. retryHandle = null;
  9150. }
  9151. };
  9152. var retryLoop = function (retryIndex) {
  9153. request.open('GET', loadUrl, true);
  9154. if (useArrayBuffer) {
  9155. request.responseType = "arraybuffer";
  9156. }
  9157. if (onProgress) {
  9158. request.addEventListener("progress", onProgress);
  9159. }
  9160. var onLoadEnd = function () {
  9161. request.removeEventListener("loadend", onLoadEnd);
  9162. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9163. fileRequest.onCompleteObservable.clear();
  9164. };
  9165. request.addEventListener("loadend", onLoadEnd);
  9166. var onReadyStateChange = function () {
  9167. if (aborted) {
  9168. return;
  9169. }
  9170. // In case of undefined state in some browsers.
  9171. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9172. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9173. request.removeEventListener("readystatechange", onReadyStateChange);
  9174. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9175. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9176. return;
  9177. }
  9178. var retryStrategy = Tools.DefaultRetryStrategy;
  9179. if (retryStrategy) {
  9180. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9181. if (waitTime !== -1) {
  9182. // Prevent the request from completing for retry.
  9183. request.removeEventListener("loadend", onLoadEnd);
  9184. request = new XMLHttpRequest();
  9185. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9186. return;
  9187. }
  9188. }
  9189. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9190. if (onError) {
  9191. onError(request, e);
  9192. }
  9193. else {
  9194. throw e;
  9195. }
  9196. }
  9197. };
  9198. request.addEventListener("readystatechange", onReadyStateChange);
  9199. request.send();
  9200. };
  9201. retryLoop(0);
  9202. };
  9203. // Caching all files
  9204. if (database && database.enableSceneOffline) {
  9205. var noIndexedDB_1 = function (request) {
  9206. if (request && request.status > 400) {
  9207. if (onError) {
  9208. onError(request);
  9209. }
  9210. }
  9211. else {
  9212. if (!aborted) {
  9213. requestFile();
  9214. }
  9215. }
  9216. };
  9217. var loadFromIndexedDB = function () {
  9218. // TODO: database needs to support aborting and should return a IFileRequest
  9219. if (aborted) {
  9220. return;
  9221. }
  9222. if (database) {
  9223. database.loadFileFromDB(url, function (data) {
  9224. if (!aborted) {
  9225. onSuccess(data);
  9226. }
  9227. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9228. }, onProgress ? function (event) {
  9229. if (!aborted) {
  9230. onProgress(event);
  9231. }
  9232. } : undefined, noIndexedDB_1, useArrayBuffer);
  9233. }
  9234. };
  9235. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9236. }
  9237. else {
  9238. requestFile();
  9239. }
  9240. return fileRequest;
  9241. };
  9242. /**
  9243. * Load a script (identified by an url). When the url returns, the
  9244. * content of this file is added into a new script element, attached to the DOM (body element)
  9245. */
  9246. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9247. var head = document.getElementsByTagName('head')[0];
  9248. var script = document.createElement('script');
  9249. script.type = 'text/javascript';
  9250. script.src = scriptUrl;
  9251. script.onload = function () {
  9252. if (onSuccess) {
  9253. onSuccess();
  9254. }
  9255. };
  9256. script.onerror = function (e) {
  9257. if (onError) {
  9258. onError("Unable to load script '" + scriptUrl + "'", e);
  9259. }
  9260. };
  9261. head.appendChild(script);
  9262. };
  9263. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9264. var reader = new FileReader();
  9265. var request = {
  9266. onCompleteObservable: new BABYLON.Observable(),
  9267. abort: function () { return reader.abort(); },
  9268. };
  9269. reader.onloadend = function (e) {
  9270. request.onCompleteObservable.notifyObservers(request);
  9271. };
  9272. reader.onload = function (e) {
  9273. //target doesn't have result from ts 1.3
  9274. callback(e.target['result']);
  9275. };
  9276. reader.onprogress = progressCallback;
  9277. reader.readAsDataURL(fileToLoad);
  9278. return request;
  9279. };
  9280. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9281. var reader = new FileReader();
  9282. var request = {
  9283. onCompleteObservable: new BABYLON.Observable(),
  9284. abort: function () { return reader.abort(); },
  9285. };
  9286. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9287. reader.onerror = function (e) {
  9288. Tools.Log("Error while reading file: " + fileToLoad.name);
  9289. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9290. };
  9291. reader.onload = function (e) {
  9292. //target doesn't have result from ts 1.3
  9293. callback(e.target['result']);
  9294. };
  9295. if (progressCallBack) {
  9296. reader.onprogress = progressCallBack;
  9297. }
  9298. if (!useArrayBuffer) {
  9299. // Asynchronous read
  9300. reader.readAsText(fileToLoad);
  9301. }
  9302. else {
  9303. reader.readAsArrayBuffer(fileToLoad);
  9304. }
  9305. return request;
  9306. };
  9307. //returns a downloadable url to a file content.
  9308. Tools.FileAsURL = function (content) {
  9309. var fileBlob = new Blob([content]);
  9310. var url = window.URL || window.webkitURL;
  9311. var link = url.createObjectURL(fileBlob);
  9312. return link;
  9313. };
  9314. // Misc.
  9315. Tools.Format = function (value, decimals) {
  9316. if (decimals === void 0) { decimals = 2; }
  9317. return value.toFixed(decimals);
  9318. };
  9319. Tools.CheckExtends = function (v, min, max) {
  9320. if (v.x < min.x)
  9321. min.x = v.x;
  9322. if (v.y < min.y)
  9323. min.y = v.y;
  9324. if (v.z < min.z)
  9325. min.z = v.z;
  9326. if (v.x > max.x)
  9327. max.x = v.x;
  9328. if (v.y > max.y)
  9329. max.y = v.y;
  9330. if (v.z > max.z)
  9331. max.z = v.z;
  9332. };
  9333. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9334. for (var prop in source) {
  9335. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9336. continue;
  9337. }
  9338. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9339. continue;
  9340. }
  9341. var sourceValue = source[prop];
  9342. var typeOfSourceValue = typeof sourceValue;
  9343. if (typeOfSourceValue === "function") {
  9344. continue;
  9345. }
  9346. try {
  9347. if (typeOfSourceValue === "object") {
  9348. if (sourceValue instanceof Array) {
  9349. destination[prop] = [];
  9350. if (sourceValue.length > 0) {
  9351. if (typeof sourceValue[0] == "object") {
  9352. for (var index = 0; index < sourceValue.length; index++) {
  9353. var clonedValue = cloneValue(sourceValue[index], destination);
  9354. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9355. destination[prop].push(clonedValue);
  9356. }
  9357. }
  9358. }
  9359. else {
  9360. destination[prop] = sourceValue.slice(0);
  9361. }
  9362. }
  9363. }
  9364. else {
  9365. destination[prop] = cloneValue(sourceValue, destination);
  9366. }
  9367. }
  9368. else {
  9369. destination[prop] = sourceValue;
  9370. }
  9371. }
  9372. catch (e) {
  9373. // Just ignore error (it could be because of a read-only property)
  9374. }
  9375. }
  9376. };
  9377. Tools.IsEmpty = function (obj) {
  9378. for (var i in obj) {
  9379. if (obj.hasOwnProperty(i)) {
  9380. return false;
  9381. }
  9382. }
  9383. return true;
  9384. };
  9385. Tools.RegisterTopRootEvents = function (events) {
  9386. for (var index = 0; index < events.length; index++) {
  9387. var event = events[index];
  9388. window.addEventListener(event.name, event.handler, false);
  9389. try {
  9390. if (window.parent) {
  9391. window.parent.addEventListener(event.name, event.handler, false);
  9392. }
  9393. }
  9394. catch (e) {
  9395. // Silently fails...
  9396. }
  9397. }
  9398. };
  9399. Tools.UnregisterTopRootEvents = function (events) {
  9400. for (var index = 0; index < events.length; index++) {
  9401. var event = events[index];
  9402. window.removeEventListener(event.name, event.handler);
  9403. try {
  9404. if (window.parent) {
  9405. window.parent.removeEventListener(event.name, event.handler);
  9406. }
  9407. }
  9408. catch (e) {
  9409. // Silently fails...
  9410. }
  9411. }
  9412. };
  9413. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9414. if (mimeType === void 0) { mimeType = "image/png"; }
  9415. // Read the contents of the framebuffer
  9416. var numberOfChannelsByLine = width * 4;
  9417. var halfHeight = height / 2;
  9418. //Reading datas from WebGL
  9419. var data = engine.readPixels(0, 0, width, height);
  9420. //To flip image on Y axis.
  9421. for (var i = 0; i < halfHeight; i++) {
  9422. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9423. var currentCell = j + i * numberOfChannelsByLine;
  9424. var targetLine = height - i - 1;
  9425. var targetCell = j + targetLine * numberOfChannelsByLine;
  9426. var temp = data[currentCell];
  9427. data[currentCell] = data[targetCell];
  9428. data[targetCell] = temp;
  9429. }
  9430. }
  9431. // Create a 2D canvas to store the result
  9432. if (!screenshotCanvas) {
  9433. screenshotCanvas = document.createElement('canvas');
  9434. }
  9435. screenshotCanvas.width = width;
  9436. screenshotCanvas.height = height;
  9437. var context = screenshotCanvas.getContext('2d');
  9438. if (context) {
  9439. // Copy the pixels to a 2D canvas
  9440. var imageData = context.createImageData(width, height);
  9441. var castData = (imageData.data);
  9442. castData.set(data);
  9443. context.putImageData(imageData, 0, 0);
  9444. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9445. }
  9446. };
  9447. /**
  9448. * Converts the canvas data to blob.
  9449. * This acts as a polyfill for browsers not supporting the to blob function.
  9450. * @param canvas Defines the canvas to extract the data from
  9451. * @param successCallback Defines the callback triggered once the data are available
  9452. * @param mimeType Defines the mime type of the result
  9453. */
  9454. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9455. if (mimeType === void 0) { mimeType = "image/png"; }
  9456. // We need HTMLCanvasElement.toBlob for HD screenshots
  9457. if (!canvas.toBlob) {
  9458. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9459. canvas.toBlob = function (callback, type, quality) {
  9460. var _this = this;
  9461. setTimeout(function () {
  9462. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9463. for (var i = 0; i < len; i++) {
  9464. arr[i] = binStr.charCodeAt(i);
  9465. }
  9466. callback(new Blob([arr]));
  9467. });
  9468. };
  9469. }
  9470. canvas.toBlob(function (blob) {
  9471. successCallback(blob);
  9472. }, mimeType);
  9473. };
  9474. /**
  9475. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9476. * @param successCallback Defines the callback triggered once the data are available
  9477. * @param mimeType Defines the mime type of the result
  9478. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9479. */
  9480. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9481. if (mimeType === void 0) { mimeType = "image/png"; }
  9482. if (successCallback) {
  9483. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9484. successCallback(base64Image);
  9485. }
  9486. else {
  9487. this.ToBlob(screenshotCanvas, function (blob) {
  9488. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9489. if (("download" in document.createElement("a"))) {
  9490. if (!fileName) {
  9491. var date = new Date();
  9492. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9493. fileName = "screenshot_" + stringDate + ".png";
  9494. }
  9495. Tools.Download(blob, fileName);
  9496. }
  9497. else {
  9498. var url = URL.createObjectURL(blob);
  9499. var newWindow = window.open("");
  9500. if (!newWindow)
  9501. return;
  9502. var img = newWindow.document.createElement("img");
  9503. img.onload = function () {
  9504. // no longer need to read the blob so it's revoked
  9505. URL.revokeObjectURL(url);
  9506. };
  9507. img.src = url;
  9508. newWindow.document.body.appendChild(img);
  9509. }
  9510. }, mimeType);
  9511. }
  9512. };
  9513. /**
  9514. * Downloads a blob in the browser
  9515. * @param blob defines the blob to download
  9516. * @param fileName defines the name of the downloaded file
  9517. */
  9518. Tools.Download = function (blob, fileName) {
  9519. var url = window.URL.createObjectURL(blob);
  9520. var a = document.createElement("a");
  9521. document.body.appendChild(a);
  9522. a.style.display = "none";
  9523. a.href = url;
  9524. a.download = fileName;
  9525. a.addEventListener("click", function () {
  9526. if (a.parentElement) {
  9527. a.parentElement.removeChild(a);
  9528. }
  9529. });
  9530. a.click();
  9531. window.URL.revokeObjectURL(url);
  9532. };
  9533. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9534. if (mimeType === void 0) { mimeType = "image/png"; }
  9535. var width;
  9536. var height;
  9537. // If a precision value is specified
  9538. if (size.precision) {
  9539. width = Math.round(engine.getRenderWidth() * size.precision);
  9540. height = Math.round(width / engine.getAspectRatio(camera));
  9541. }
  9542. else if (size.width && size.height) {
  9543. width = size.width;
  9544. height = size.height;
  9545. }
  9546. //If passing only width, computing height to keep display canvas ratio.
  9547. else if (size.width && !size.height) {
  9548. width = size.width;
  9549. height = Math.round(width / engine.getAspectRatio(camera));
  9550. }
  9551. //If passing only height, computing width to keep display canvas ratio.
  9552. else if (size.height && !size.width) {
  9553. height = size.height;
  9554. width = Math.round(height * engine.getAspectRatio(camera));
  9555. }
  9556. //Assuming here that "size" parameter is a number
  9557. else if (!isNaN(size)) {
  9558. height = size;
  9559. width = size;
  9560. }
  9561. else {
  9562. Tools.Error("Invalid 'size' parameter !");
  9563. return;
  9564. }
  9565. if (!screenshotCanvas) {
  9566. screenshotCanvas = document.createElement('canvas');
  9567. }
  9568. screenshotCanvas.width = width;
  9569. screenshotCanvas.height = height;
  9570. var renderContext = screenshotCanvas.getContext("2d");
  9571. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9572. var newWidth = width;
  9573. var newHeight = newWidth / ratio;
  9574. if (newHeight > height) {
  9575. newHeight = height;
  9576. newWidth = newHeight * ratio;
  9577. }
  9578. var offsetX = Math.max(0, width - newWidth) / 2;
  9579. var offsetY = Math.max(0, height - newHeight) / 2;
  9580. var renderingCanvas = engine.getRenderingCanvas();
  9581. if (renderContext && renderingCanvas) {
  9582. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9583. }
  9584. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9585. };
  9586. /**
  9587. * Generates an image screenshot from the specified camera.
  9588. *
  9589. * @param engine The engine to use for rendering
  9590. * @param camera The camera to use for rendering
  9591. * @param size This parameter can be set to a single number or to an object with the
  9592. * following (optional) properties: precision, width, height. If a single number is passed,
  9593. * it will be used for both width and height. If an object is passed, the screenshot size
  9594. * will be derived from the parameters. The precision property is a multiplier allowing
  9595. * rendering at a higher or lower resolution.
  9596. * @param successCallback The callback receives a single parameter which contains the
  9597. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9598. * src parameter of an <img> to display it.
  9599. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9600. * Check your browser for supported MIME types.
  9601. * @param samples Texture samples (default: 1)
  9602. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9603. * @param fileName A name for for the downloaded file.
  9604. * @constructor
  9605. */
  9606. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9607. if (mimeType === void 0) { mimeType = "image/png"; }
  9608. if (samples === void 0) { samples = 1; }
  9609. if (antialiasing === void 0) { antialiasing = false; }
  9610. var width;
  9611. var height;
  9612. //If a precision value is specified
  9613. if (size.precision) {
  9614. width = Math.round(engine.getRenderWidth() * size.precision);
  9615. height = Math.round(width / engine.getAspectRatio(camera));
  9616. size = { width: width, height: height };
  9617. }
  9618. else if (size.width && size.height) {
  9619. width = size.width;
  9620. height = size.height;
  9621. }
  9622. //If passing only width, computing height to keep display canvas ratio.
  9623. else if (size.width && !size.height) {
  9624. width = size.width;
  9625. height = Math.round(width / engine.getAspectRatio(camera));
  9626. size = { width: width, height: height };
  9627. }
  9628. //If passing only height, computing width to keep display canvas ratio.
  9629. else if (size.height && !size.width) {
  9630. height = size.height;
  9631. width = Math.round(height * engine.getAspectRatio(camera));
  9632. size = { width: width, height: height };
  9633. }
  9634. //Assuming here that "size" parameter is a number
  9635. else if (!isNaN(size)) {
  9636. height = size;
  9637. width = size;
  9638. }
  9639. else {
  9640. Tools.Error("Invalid 'size' parameter !");
  9641. return;
  9642. }
  9643. var scene = camera.getScene();
  9644. var previousCamera = null;
  9645. if (scene.activeCamera !== camera) {
  9646. previousCamera = scene.activeCamera;
  9647. scene.activeCamera = camera;
  9648. }
  9649. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9650. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9651. texture.renderList = null;
  9652. texture.samples = samples;
  9653. if (antialiasing) {
  9654. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9655. }
  9656. texture.onAfterRenderObservable.add(function () {
  9657. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9658. });
  9659. scene.incrementRenderId();
  9660. scene.resetCachedMaterial();
  9661. texture.render(true);
  9662. texture.dispose();
  9663. if (previousCamera) {
  9664. scene.activeCamera = previousCamera;
  9665. }
  9666. camera.getProjectionMatrix(true); // Force cache refresh;
  9667. };
  9668. // XHR response validator for local file scenario
  9669. Tools.ValidateXHRData = function (xhr, dataType) {
  9670. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9671. if (dataType === void 0) { dataType = 7; }
  9672. try {
  9673. if (dataType & 1) {
  9674. if (xhr.responseText && xhr.responseText.length > 0) {
  9675. return true;
  9676. }
  9677. else if (dataType === 1) {
  9678. return false;
  9679. }
  9680. }
  9681. if (dataType & 2) {
  9682. // Check header width and height since there is no "TGA" magic number
  9683. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9684. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9685. return true;
  9686. }
  9687. else if (dataType === 2) {
  9688. return false;
  9689. }
  9690. }
  9691. if (dataType & 4) {
  9692. // Check for the "DDS" magic number
  9693. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9694. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9695. return true;
  9696. }
  9697. else {
  9698. return false;
  9699. }
  9700. }
  9701. }
  9702. catch (e) {
  9703. // Global protection
  9704. }
  9705. return false;
  9706. };
  9707. /**
  9708. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9709. * Be aware Math.random() could cause collisions, but:
  9710. * "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"
  9711. */
  9712. Tools.RandomId = function () {
  9713. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9714. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9715. return v.toString(16);
  9716. });
  9717. };
  9718. /**
  9719. * Test if the given uri is a base64 string.
  9720. * @param uri The uri to test
  9721. * @return True if the uri is a base64 string or false otherwise.
  9722. */
  9723. Tools.IsBase64 = function (uri) {
  9724. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9725. };
  9726. /**
  9727. * Decode the given base64 uri.
  9728. * @param uri The uri to decode
  9729. * @return The decoded base64 data.
  9730. */
  9731. Tools.DecodeBase64 = function (uri) {
  9732. var decodedString = atob(uri.split(",")[1]);
  9733. var bufferLength = decodedString.length;
  9734. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9735. for (var i = 0; i < bufferLength; i++) {
  9736. bufferView[i] = decodedString.charCodeAt(i);
  9737. }
  9738. return bufferView.buffer;
  9739. };
  9740. Object.defineProperty(Tools, "NoneLogLevel", {
  9741. get: function () {
  9742. return Tools._NoneLogLevel;
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. Object.defineProperty(Tools, "MessageLogLevel", {
  9748. get: function () {
  9749. return Tools._MessageLogLevel;
  9750. },
  9751. enumerable: true,
  9752. configurable: true
  9753. });
  9754. Object.defineProperty(Tools, "WarningLogLevel", {
  9755. get: function () {
  9756. return Tools._WarningLogLevel;
  9757. },
  9758. enumerable: true,
  9759. configurable: true
  9760. });
  9761. Object.defineProperty(Tools, "ErrorLogLevel", {
  9762. get: function () {
  9763. return Tools._ErrorLogLevel;
  9764. },
  9765. enumerable: true,
  9766. configurable: true
  9767. });
  9768. Object.defineProperty(Tools, "AllLogLevel", {
  9769. get: function () {
  9770. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. Tools._AddLogEntry = function (entry) {
  9776. Tools._LogCache = entry + Tools._LogCache;
  9777. if (Tools.OnNewCacheEntry) {
  9778. Tools.OnNewCacheEntry(entry);
  9779. }
  9780. };
  9781. Tools._FormatMessage = function (message) {
  9782. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9783. var date = new Date();
  9784. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9785. };
  9786. Tools._LogDisabled = function (message) {
  9787. // nothing to do
  9788. };
  9789. Tools._LogEnabled = function (message) {
  9790. var formattedMessage = Tools._FormatMessage(message);
  9791. console.log("BJS - " + formattedMessage);
  9792. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9793. Tools._AddLogEntry(entry);
  9794. };
  9795. Tools._WarnDisabled = function (message) {
  9796. // nothing to do
  9797. };
  9798. Tools._WarnEnabled = function (message) {
  9799. var formattedMessage = Tools._FormatMessage(message);
  9800. console.warn("BJS - " + formattedMessage);
  9801. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9802. Tools._AddLogEntry(entry);
  9803. };
  9804. Tools._ErrorDisabled = function (message) {
  9805. // nothing to do
  9806. };
  9807. Tools._ErrorEnabled = function (message) {
  9808. Tools.errorsCount++;
  9809. var formattedMessage = Tools._FormatMessage(message);
  9810. console.error("BJS - " + formattedMessage);
  9811. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9812. Tools._AddLogEntry(entry);
  9813. };
  9814. Object.defineProperty(Tools, "LogCache", {
  9815. get: function () {
  9816. return Tools._LogCache;
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Tools.ClearLogCache = function () {
  9822. Tools._LogCache = "";
  9823. Tools.errorsCount = 0;
  9824. };
  9825. Object.defineProperty(Tools, "LogLevels", {
  9826. set: function (level) {
  9827. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9828. Tools.Log = Tools._LogEnabled;
  9829. }
  9830. else {
  9831. Tools.Log = Tools._LogDisabled;
  9832. }
  9833. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9834. Tools.Warn = Tools._WarnEnabled;
  9835. }
  9836. else {
  9837. Tools.Warn = Tools._WarnDisabled;
  9838. }
  9839. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9840. Tools.Error = Tools._ErrorEnabled;
  9841. }
  9842. else {
  9843. Tools.Error = Tools._ErrorDisabled;
  9844. }
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Tools.IsWindowObjectExist = function () {
  9850. return (typeof window) !== "undefined";
  9851. };
  9852. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9853. get: function () {
  9854. return Tools._PerformanceNoneLogLevel;
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9860. get: function () {
  9861. return Tools._PerformanceUserMarkLogLevel;
  9862. },
  9863. enumerable: true,
  9864. configurable: true
  9865. });
  9866. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9867. get: function () {
  9868. return Tools._PerformanceConsoleLogLevel;
  9869. },
  9870. enumerable: true,
  9871. configurable: true
  9872. });
  9873. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9874. set: function (level) {
  9875. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9876. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9877. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9878. return;
  9879. }
  9880. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9881. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9882. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9883. return;
  9884. }
  9885. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9886. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9892. };
  9893. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9894. };
  9895. Tools._StartUserMark = function (counterName, condition) {
  9896. if (condition === void 0) { condition = true; }
  9897. if (!Tools._performance) {
  9898. if (!Tools.IsWindowObjectExist()) {
  9899. return;
  9900. }
  9901. Tools._performance = window.performance;
  9902. }
  9903. if (!condition || !Tools._performance.mark) {
  9904. return;
  9905. }
  9906. Tools._performance.mark(counterName + "-Begin");
  9907. };
  9908. Tools._EndUserMark = function (counterName, condition) {
  9909. if (condition === void 0) { condition = true; }
  9910. if (!condition || !Tools._performance.mark) {
  9911. return;
  9912. }
  9913. Tools._performance.mark(counterName + "-End");
  9914. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9915. };
  9916. Tools._StartPerformanceConsole = function (counterName, condition) {
  9917. if (condition === void 0) { condition = true; }
  9918. if (!condition) {
  9919. return;
  9920. }
  9921. Tools._StartUserMark(counterName, condition);
  9922. if (console.time) {
  9923. console.time(counterName);
  9924. }
  9925. };
  9926. Tools._EndPerformanceConsole = function (counterName, condition) {
  9927. if (condition === void 0) { condition = true; }
  9928. if (!condition) {
  9929. return;
  9930. }
  9931. Tools._EndUserMark(counterName, condition);
  9932. if (console.time) {
  9933. console.timeEnd(counterName);
  9934. }
  9935. };
  9936. Object.defineProperty(Tools, "Now", {
  9937. get: function () {
  9938. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9939. return window.performance.now();
  9940. }
  9941. return Date.now();
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. /**
  9947. * This method will return the name of the class used to create the instance of the given object.
  9948. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9949. * @param object the object to get the class name from
  9950. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9951. */
  9952. Tools.GetClassName = function (object, isType) {
  9953. if (isType === void 0) { isType = false; }
  9954. var name = null;
  9955. if (!isType && object.getClassName) {
  9956. name = object.getClassName();
  9957. }
  9958. else {
  9959. if (object instanceof Object) {
  9960. var classObj = isType ? object : Object.getPrototypeOf(object);
  9961. name = classObj.constructor["__bjsclassName__"];
  9962. }
  9963. if (!name) {
  9964. name = typeof object;
  9965. }
  9966. }
  9967. return name;
  9968. };
  9969. Tools.First = function (array, predicate) {
  9970. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9971. var el = array_1[_i];
  9972. if (predicate(el)) {
  9973. return el;
  9974. }
  9975. }
  9976. return null;
  9977. };
  9978. /**
  9979. * This method will return the name of the full name of the class, including its owning module (if any).
  9980. * 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).
  9981. * @param object the object to get the class name from
  9982. * @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.
  9983. */
  9984. Tools.getFullClassName = function (object, isType) {
  9985. if (isType === void 0) { isType = false; }
  9986. var className = null;
  9987. var moduleName = null;
  9988. if (!isType && object.getClassName) {
  9989. className = object.getClassName();
  9990. }
  9991. else {
  9992. if (object instanceof Object) {
  9993. var classObj = isType ? object : Object.getPrototypeOf(object);
  9994. className = classObj.constructor["__bjsclassName__"];
  9995. moduleName = classObj.constructor["__bjsmoduleName__"];
  9996. }
  9997. if (!className) {
  9998. className = typeof object;
  9999. }
  10000. }
  10001. if (!className) {
  10002. return null;
  10003. }
  10004. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10005. };
  10006. /**
  10007. * 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.
  10008. * @param array
  10009. */
  10010. Tools.arrayOrStringFeeder = function (array) {
  10011. return function (index) {
  10012. if (index >= array.length) {
  10013. return null;
  10014. }
  10015. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10016. if (val && val.getHashCode) {
  10017. val = val.getHashCode();
  10018. }
  10019. if (typeof val === "string") {
  10020. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10021. }
  10022. return val;
  10023. };
  10024. };
  10025. /**
  10026. * Compute the hashCode of a stream of number
  10027. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10028. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10029. * @return the hash code computed
  10030. */
  10031. Tools.hashCodeFromStream = function (feeder) {
  10032. // Based from here: http://stackoverflow.com/a/7616484/802124
  10033. var hash = 0;
  10034. var index = 0;
  10035. var chr = feeder(index++);
  10036. while (chr != null) {
  10037. hash = ((hash << 5) - hash) + chr;
  10038. hash |= 0; // Convert to 32bit integer
  10039. chr = feeder(index++);
  10040. }
  10041. return hash;
  10042. };
  10043. /**
  10044. * Returns a promise that resolves after the given amount of time.
  10045. * @param delay Number of milliseconds to delay
  10046. * @returns Promise that resolves after the given amount of time
  10047. */
  10048. Tools.DelayAsync = function (delay) {
  10049. return new Promise(function (resolve) {
  10050. setTimeout(function () {
  10051. resolve();
  10052. }, delay);
  10053. });
  10054. };
  10055. /**
  10056. * Gets the current gradient from an array of IValueGradient
  10057. * @param ratio defines the current ratio to get
  10058. * @param gradients defines the array of IValueGradient
  10059. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10060. */
  10061. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10062. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10063. var currentGradient = gradients[gradientIndex];
  10064. var nextGradient = gradients[gradientIndex + 1];
  10065. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10066. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10067. updateFunc(currentGradient, nextGradient, scale);
  10068. }
  10069. }
  10070. };
  10071. Tools.BaseUrl = "";
  10072. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10073. /**
  10074. * Default behaviour for cors in the application.
  10075. * It can be a string if the expected behavior is identical in the entire app.
  10076. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10077. */
  10078. Tools.CorsBehavior = "anonymous";
  10079. Tools.UseFallbackTexture = true;
  10080. /**
  10081. * Use this object to register external classes like custom textures or material
  10082. * to allow the laoders to instantiate them
  10083. */
  10084. Tools.RegisteredExternalClasses = {};
  10085. // Used in case of a texture loading problem
  10086. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQ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4FPqCiiivhT++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";
  10087. Tools._tmpFloatArray = new Float32Array(1);
  10088. Tools.PreprocessUrl = function (url) {
  10089. return url;
  10090. };
  10091. // Logs
  10092. Tools._NoneLogLevel = 0;
  10093. Tools._MessageLogLevel = 1;
  10094. Tools._WarningLogLevel = 2;
  10095. Tools._ErrorLogLevel = 4;
  10096. Tools._LogCache = "";
  10097. Tools.errorsCount = 0;
  10098. Tools.Log = Tools._LogEnabled;
  10099. Tools.Warn = Tools._WarnEnabled;
  10100. Tools.Error = Tools._ErrorEnabled;
  10101. // Performances
  10102. Tools._PerformanceNoneLogLevel = 0;
  10103. Tools._PerformanceUserMarkLogLevel = 1;
  10104. Tools._PerformanceConsoleLogLevel = 2;
  10105. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10106. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10107. return Tools;
  10108. }());
  10109. BABYLON.Tools = Tools;
  10110. /**
  10111. * This class is used to track a performance counter which is number based.
  10112. * The user has access to many properties which give statistics of different nature
  10113. *
  10114. * The implementer can track two kinds of Performance Counter: time and count
  10115. * 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.
  10116. * 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.
  10117. */
  10118. var PerfCounter = /** @class */ (function () {
  10119. function PerfCounter() {
  10120. this._startMonitoringTime = 0;
  10121. this._min = 0;
  10122. this._max = 0;
  10123. this._average = 0;
  10124. this._lastSecAverage = 0;
  10125. this._current = 0;
  10126. this._totalValueCount = 0;
  10127. this._totalAccumulated = 0;
  10128. this._lastSecAccumulated = 0;
  10129. this._lastSecTime = 0;
  10130. this._lastSecValueCount = 0;
  10131. }
  10132. Object.defineProperty(PerfCounter.prototype, "min", {
  10133. /**
  10134. * Returns the smallest value ever
  10135. */
  10136. get: function () {
  10137. return this._min;
  10138. },
  10139. enumerable: true,
  10140. configurable: true
  10141. });
  10142. Object.defineProperty(PerfCounter.prototype, "max", {
  10143. /**
  10144. * Returns the biggest value ever
  10145. */
  10146. get: function () {
  10147. return this._max;
  10148. },
  10149. enumerable: true,
  10150. configurable: true
  10151. });
  10152. Object.defineProperty(PerfCounter.prototype, "average", {
  10153. /**
  10154. * Returns the average value since the performance counter is running
  10155. */
  10156. get: function () {
  10157. return this._average;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10163. /**
  10164. * Returns the average value of the last second the counter was monitored
  10165. */
  10166. get: function () {
  10167. return this._lastSecAverage;
  10168. },
  10169. enumerable: true,
  10170. configurable: true
  10171. });
  10172. Object.defineProperty(PerfCounter.prototype, "current", {
  10173. /**
  10174. * Returns the current value
  10175. */
  10176. get: function () {
  10177. return this._current;
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Object.defineProperty(PerfCounter.prototype, "total", {
  10183. get: function () {
  10184. return this._totalAccumulated;
  10185. },
  10186. enumerable: true,
  10187. configurable: true
  10188. });
  10189. Object.defineProperty(PerfCounter.prototype, "count", {
  10190. get: function () {
  10191. return this._totalValueCount;
  10192. },
  10193. enumerable: true,
  10194. configurable: true
  10195. });
  10196. /**
  10197. * Call this method to start monitoring a new frame.
  10198. * 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.
  10199. */
  10200. PerfCounter.prototype.fetchNewFrame = function () {
  10201. this._totalValueCount++;
  10202. this._current = 0;
  10203. this._lastSecValueCount++;
  10204. };
  10205. /**
  10206. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10207. * @param newCount the count value to add to the monitored count
  10208. * @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.
  10209. */
  10210. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10211. if (!PerfCounter.Enabled) {
  10212. return;
  10213. }
  10214. this._current += newCount;
  10215. if (fetchResult) {
  10216. this._fetchResult();
  10217. }
  10218. };
  10219. /**
  10220. * Start monitoring this performance counter
  10221. */
  10222. PerfCounter.prototype.beginMonitoring = function () {
  10223. if (!PerfCounter.Enabled) {
  10224. return;
  10225. }
  10226. this._startMonitoringTime = Tools.Now;
  10227. };
  10228. /**
  10229. * Compute the time lapsed since the previous beginMonitoring() call.
  10230. * @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
  10231. */
  10232. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10233. if (newFrame === void 0) { newFrame = true; }
  10234. if (!PerfCounter.Enabled) {
  10235. return;
  10236. }
  10237. if (newFrame) {
  10238. this.fetchNewFrame();
  10239. }
  10240. var currentTime = Tools.Now;
  10241. this._current = currentTime - this._startMonitoringTime;
  10242. if (newFrame) {
  10243. this._fetchResult();
  10244. }
  10245. };
  10246. PerfCounter.prototype._fetchResult = function () {
  10247. this._totalAccumulated += this._current;
  10248. this._lastSecAccumulated += this._current;
  10249. // Min/Max update
  10250. this._min = Math.min(this._min, this._current);
  10251. this._max = Math.max(this._max, this._current);
  10252. this._average = this._totalAccumulated / this._totalValueCount;
  10253. // Reset last sec?
  10254. var now = Tools.Now;
  10255. if ((now - this._lastSecTime) > 1000) {
  10256. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10257. this._lastSecTime = now;
  10258. this._lastSecAccumulated = 0;
  10259. this._lastSecValueCount = 0;
  10260. }
  10261. };
  10262. PerfCounter.Enabled = true;
  10263. return PerfCounter;
  10264. }());
  10265. BABYLON.PerfCounter = PerfCounter;
  10266. /**
  10267. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10268. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10269. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10270. * @param name The name of the class, case should be preserved
  10271. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10272. */
  10273. function className(name, module) {
  10274. return function (target) {
  10275. target["__bjsclassName__"] = name;
  10276. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10277. };
  10278. }
  10279. BABYLON.className = className;
  10280. /**
  10281. * An implementation of a loop for asynchronous functions.
  10282. */
  10283. var AsyncLoop = /** @class */ (function () {
  10284. /**
  10285. * Constroctor.
  10286. * @param iterations the number of iterations.
  10287. * @param _fn the function to run each iteration
  10288. * @param _successCallback the callback that will be called upon succesful execution
  10289. * @param offset starting offset.
  10290. */
  10291. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10292. if (offset === void 0) { offset = 0; }
  10293. this.iterations = iterations;
  10294. this._fn = _fn;
  10295. this._successCallback = _successCallback;
  10296. this.index = offset - 1;
  10297. this._done = false;
  10298. }
  10299. /**
  10300. * Execute the next iteration. Must be called after the last iteration was finished.
  10301. */
  10302. AsyncLoop.prototype.executeNext = function () {
  10303. if (!this._done) {
  10304. if (this.index + 1 < this.iterations) {
  10305. ++this.index;
  10306. this._fn(this);
  10307. }
  10308. else {
  10309. this.breakLoop();
  10310. }
  10311. }
  10312. };
  10313. /**
  10314. * Break the loop and run the success callback.
  10315. */
  10316. AsyncLoop.prototype.breakLoop = function () {
  10317. this._done = true;
  10318. this._successCallback();
  10319. };
  10320. /**
  10321. * Helper function
  10322. */
  10323. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10324. if (offset === void 0) { offset = 0; }
  10325. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10326. loop.executeNext();
  10327. return loop;
  10328. };
  10329. /**
  10330. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10331. * @param iterations total number of iterations
  10332. * @param syncedIterations number of synchronous iterations in each async iteration.
  10333. * @param fn the function to call each iteration.
  10334. * @param callback a success call back that will be called when iterating stops.
  10335. * @param breakFunction a break condition (optional)
  10336. * @param timeout timeout settings for the setTimeout function. default - 0.
  10337. * @constructor
  10338. */
  10339. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10340. if (timeout === void 0) { timeout = 0; }
  10341. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10342. if (breakFunction && breakFunction())
  10343. loop.breakLoop();
  10344. else {
  10345. setTimeout(function () {
  10346. for (var i = 0; i < syncedIterations; ++i) {
  10347. var iteration = (loop.index * syncedIterations) + i;
  10348. if (iteration >= iterations)
  10349. break;
  10350. fn(iteration);
  10351. if (breakFunction && breakFunction()) {
  10352. loop.breakLoop();
  10353. break;
  10354. }
  10355. }
  10356. loop.executeNext();
  10357. }, timeout);
  10358. }
  10359. }, callback);
  10360. };
  10361. return AsyncLoop;
  10362. }());
  10363. BABYLON.AsyncLoop = AsyncLoop;
  10364. })(BABYLON || (BABYLON = {}));
  10365. //# sourceMappingURL=babylon.tools.js.map
  10366. var BABYLON;
  10367. (function (BABYLON) {
  10368. var PromiseStates;
  10369. (function (PromiseStates) {
  10370. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10371. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10372. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10373. })(PromiseStates || (PromiseStates = {}));
  10374. var FulFillmentAgregator = /** @class */ (function () {
  10375. function FulFillmentAgregator() {
  10376. this.count = 0;
  10377. this.target = 0;
  10378. this.results = [];
  10379. }
  10380. return FulFillmentAgregator;
  10381. }());
  10382. var InternalPromise = /** @class */ (function () {
  10383. function InternalPromise(resolver) {
  10384. var _this = this;
  10385. this._state = PromiseStates.Pending;
  10386. this._children = new Array();
  10387. this._rejectWasConsumed = false;
  10388. if (!resolver) {
  10389. return;
  10390. }
  10391. try {
  10392. resolver(function (value) {
  10393. _this._resolve(value);
  10394. }, function (reason) {
  10395. _this._reject(reason);
  10396. });
  10397. }
  10398. catch (e) {
  10399. this._reject(e);
  10400. }
  10401. }
  10402. Object.defineProperty(InternalPromise.prototype, "_result", {
  10403. get: function () {
  10404. return this._resultValue;
  10405. },
  10406. set: function (value) {
  10407. this._resultValue = value;
  10408. if (this._parent && this._parent._result === undefined) {
  10409. this._parent._result = value;
  10410. }
  10411. },
  10412. enumerable: true,
  10413. configurable: true
  10414. });
  10415. InternalPromise.prototype.catch = function (onRejected) {
  10416. return this.then(undefined, onRejected);
  10417. };
  10418. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10419. var _this = this;
  10420. var newPromise = new InternalPromise();
  10421. newPromise._onFulfilled = onFulfilled;
  10422. newPromise._onRejected = onRejected;
  10423. // Composition
  10424. this._children.push(newPromise);
  10425. newPromise._parent = this;
  10426. if (this._state !== PromiseStates.Pending) {
  10427. BABYLON.Tools.SetImmediate(function () {
  10428. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10429. var returnedValue = newPromise._resolve(_this._result);
  10430. if (returnedValue !== undefined && returnedValue !== null) {
  10431. if (returnedValue._state !== undefined) {
  10432. var returnedPromise = returnedValue;
  10433. newPromise._children.push(returnedPromise);
  10434. returnedPromise._parent = newPromise;
  10435. newPromise = returnedPromise;
  10436. }
  10437. else {
  10438. newPromise._result = returnedValue;
  10439. }
  10440. }
  10441. }
  10442. else {
  10443. newPromise._reject(_this._reason);
  10444. }
  10445. });
  10446. }
  10447. return newPromise;
  10448. };
  10449. InternalPromise.prototype._moveChildren = function (children) {
  10450. var _this = this;
  10451. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10452. this._children.forEach(function (child) {
  10453. child._parent = _this;
  10454. });
  10455. if (this._state === PromiseStates.Fulfilled) {
  10456. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10457. var child = _b[_i];
  10458. child._resolve(this._result);
  10459. }
  10460. }
  10461. else if (this._state === PromiseStates.Rejected) {
  10462. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10463. var child = _d[_c];
  10464. child._reject(this._reason);
  10465. }
  10466. }
  10467. var _a;
  10468. };
  10469. InternalPromise.prototype._resolve = function (value) {
  10470. try {
  10471. this._state = PromiseStates.Fulfilled;
  10472. var returnedValue = null;
  10473. if (this._onFulfilled) {
  10474. returnedValue = this._onFulfilled(value);
  10475. }
  10476. if (returnedValue !== undefined && returnedValue !== null) {
  10477. if (returnedValue._state !== undefined) {
  10478. // Transmit children
  10479. var returnedPromise = returnedValue;
  10480. returnedPromise._parent = this;
  10481. returnedPromise._moveChildren(this._children);
  10482. value = returnedPromise._result;
  10483. }
  10484. else {
  10485. value = returnedValue;
  10486. }
  10487. }
  10488. this._result = value;
  10489. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10490. var child = _a[_i];
  10491. child._resolve(value);
  10492. }
  10493. this._children.length = 0;
  10494. delete this._onFulfilled;
  10495. delete this._onRejected;
  10496. }
  10497. catch (e) {
  10498. this._reject(e, true);
  10499. }
  10500. };
  10501. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10502. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10503. this._state = PromiseStates.Rejected;
  10504. this._reason = reason;
  10505. if (this._onRejected && !onLocalThrow) {
  10506. try {
  10507. this._onRejected(reason);
  10508. this._rejectWasConsumed = true;
  10509. }
  10510. catch (e) {
  10511. reason = e;
  10512. }
  10513. }
  10514. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10515. var child = _a[_i];
  10516. if (this._rejectWasConsumed) {
  10517. child._resolve(null);
  10518. }
  10519. else {
  10520. child._reject(reason);
  10521. }
  10522. }
  10523. this._children.length = 0;
  10524. delete this._onFulfilled;
  10525. delete this._onRejected;
  10526. };
  10527. InternalPromise.resolve = function (value) {
  10528. var newPromise = new InternalPromise();
  10529. newPromise._resolve(value);
  10530. return newPromise;
  10531. };
  10532. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10533. promise.then(function (value) {
  10534. agregator.results[index] = value;
  10535. agregator.count++;
  10536. if (agregator.count === agregator.target) {
  10537. agregator.rootPromise._resolve(agregator.results);
  10538. }
  10539. return null;
  10540. }, function (reason) {
  10541. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10542. agregator.rootPromise._reject(reason);
  10543. }
  10544. });
  10545. };
  10546. InternalPromise.all = function (promises) {
  10547. var newPromise = new InternalPromise();
  10548. var agregator = new FulFillmentAgregator();
  10549. agregator.target = promises.length;
  10550. agregator.rootPromise = newPromise;
  10551. if (promises.length) {
  10552. for (var index = 0; index < promises.length; index++) {
  10553. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10554. }
  10555. }
  10556. else {
  10557. newPromise._resolve([]);
  10558. }
  10559. return newPromise;
  10560. };
  10561. InternalPromise.race = function (promises) {
  10562. var newPromise = new InternalPromise();
  10563. if (promises.length) {
  10564. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10565. var promise = promises_1[_i];
  10566. promise.then(function (value) {
  10567. if (newPromise) {
  10568. newPromise._resolve(value);
  10569. newPromise = null;
  10570. }
  10571. return null;
  10572. }, function (reason) {
  10573. if (newPromise) {
  10574. newPromise._reject(reason);
  10575. newPromise = null;
  10576. }
  10577. });
  10578. }
  10579. }
  10580. return newPromise;
  10581. };
  10582. return InternalPromise;
  10583. }());
  10584. /**
  10585. * Helper class that provides a small promise polyfill
  10586. */
  10587. var PromisePolyfill = /** @class */ (function () {
  10588. function PromisePolyfill() {
  10589. }
  10590. /**
  10591. * Static function used to check if the polyfill is required
  10592. * If this is the case then the function will inject the polyfill to window.Promise
  10593. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10594. */
  10595. PromisePolyfill.Apply = function (force) {
  10596. if (force === void 0) { force = false; }
  10597. if (force || typeof Promise === 'undefined') {
  10598. var root = window;
  10599. root.Promise = InternalPromise;
  10600. }
  10601. };
  10602. return PromisePolyfill;
  10603. }());
  10604. BABYLON.PromisePolyfill = PromisePolyfill;
  10605. })(BABYLON || (BABYLON = {}));
  10606. //# sourceMappingURL=babylon.promise.js.map
  10607. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10608. var BABYLON;
  10609. (function (BABYLON) {
  10610. /**
  10611. * Helper class to push actions to a pool of workers.
  10612. */
  10613. var WorkerPool = /** @class */ (function () {
  10614. /**
  10615. * Constructor
  10616. * @param workers Array of workers to use for actions
  10617. */
  10618. function WorkerPool(workers) {
  10619. this._pendingActions = new Array();
  10620. this._workerInfos = workers.map(function (worker) { return ({
  10621. worker: worker,
  10622. active: false
  10623. }); });
  10624. }
  10625. /**
  10626. * Terminates all workers and clears any pending actions.
  10627. */
  10628. WorkerPool.prototype.dispose = function () {
  10629. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10630. var workerInfo = _a[_i];
  10631. workerInfo.worker.terminate();
  10632. }
  10633. delete this._workerInfos;
  10634. delete this._pendingActions;
  10635. };
  10636. /**
  10637. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10638. * pended until a worker has completed its action.
  10639. * @param action The action to perform. Call onComplete when the action is complete.
  10640. */
  10641. WorkerPool.prototype.push = function (action) {
  10642. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10643. var workerInfo = _a[_i];
  10644. if (!workerInfo.active) {
  10645. this._execute(workerInfo, action);
  10646. return;
  10647. }
  10648. }
  10649. this._pendingActions.push(action);
  10650. };
  10651. WorkerPool.prototype._execute = function (workerInfo, action) {
  10652. var _this = this;
  10653. workerInfo.active = true;
  10654. action(workerInfo.worker, function () {
  10655. workerInfo.active = false;
  10656. var nextAction = _this._pendingActions.shift();
  10657. if (nextAction) {
  10658. _this._execute(workerInfo, nextAction);
  10659. }
  10660. });
  10661. };
  10662. return WorkerPool;
  10663. }());
  10664. BABYLON.WorkerPool = WorkerPool;
  10665. })(BABYLON || (BABYLON = {}));
  10666. //# sourceMappingURL=babylon.workerPool.js.map
  10667. var BABYLON;
  10668. (function (BABYLON) {
  10669. /**
  10670. * @hidden
  10671. **/
  10672. var _AlphaState = /** @class */ (function () {
  10673. /**
  10674. * Initializes the state.
  10675. */
  10676. function _AlphaState() {
  10677. this._isAlphaBlendDirty = false;
  10678. this._isBlendFunctionParametersDirty = false;
  10679. this._isBlendEquationParametersDirty = false;
  10680. this._isBlendConstantsDirty = false;
  10681. this._alphaBlend = false;
  10682. this._blendFunctionParameters = new Array(4);
  10683. this._blendEquationParameters = new Array(2);
  10684. this._blendConstants = new Array(4);
  10685. this.reset();
  10686. }
  10687. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10688. get: function () {
  10689. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10690. },
  10691. enumerable: true,
  10692. configurable: true
  10693. });
  10694. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10695. get: function () {
  10696. return this._alphaBlend;
  10697. },
  10698. set: function (value) {
  10699. if (this._alphaBlend === value) {
  10700. return;
  10701. }
  10702. this._alphaBlend = value;
  10703. this._isAlphaBlendDirty = true;
  10704. },
  10705. enumerable: true,
  10706. configurable: true
  10707. });
  10708. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10709. if (this._blendConstants[0] === r &&
  10710. this._blendConstants[1] === g &&
  10711. this._blendConstants[2] === b &&
  10712. this._blendConstants[3] === a) {
  10713. return;
  10714. }
  10715. this._blendConstants[0] = r;
  10716. this._blendConstants[1] = g;
  10717. this._blendConstants[2] = b;
  10718. this._blendConstants[3] = a;
  10719. this._isBlendConstantsDirty = true;
  10720. };
  10721. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10722. if (this._blendFunctionParameters[0] === value0 &&
  10723. this._blendFunctionParameters[1] === value1 &&
  10724. this._blendFunctionParameters[2] === value2 &&
  10725. this._blendFunctionParameters[3] === value3) {
  10726. return;
  10727. }
  10728. this._blendFunctionParameters[0] = value0;
  10729. this._blendFunctionParameters[1] = value1;
  10730. this._blendFunctionParameters[2] = value2;
  10731. this._blendFunctionParameters[3] = value3;
  10732. this._isBlendFunctionParametersDirty = true;
  10733. };
  10734. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10735. if (this._blendEquationParameters[0] === rgb &&
  10736. this._blendEquationParameters[1] === alpha) {
  10737. return;
  10738. }
  10739. this._blendEquationParameters[0] = rgb;
  10740. this._blendEquationParameters[1] = alpha;
  10741. this._isBlendEquationParametersDirty = true;
  10742. };
  10743. _AlphaState.prototype.reset = function () {
  10744. this._alphaBlend = false;
  10745. this._blendFunctionParameters[0] = null;
  10746. this._blendFunctionParameters[1] = null;
  10747. this._blendFunctionParameters[2] = null;
  10748. this._blendFunctionParameters[3] = null;
  10749. this._blendEquationParameters[0] = null;
  10750. this._blendEquationParameters[1] = null;
  10751. this._blendConstants[0] = null;
  10752. this._blendConstants[1] = null;
  10753. this._blendConstants[2] = null;
  10754. this._blendConstants[3] = null;
  10755. this._isAlphaBlendDirty = true;
  10756. this._isBlendFunctionParametersDirty = false;
  10757. this._isBlendEquationParametersDirty = false;
  10758. this._isBlendConstantsDirty = false;
  10759. };
  10760. _AlphaState.prototype.apply = function (gl) {
  10761. if (!this.isDirty) {
  10762. return;
  10763. }
  10764. // Alpha blend
  10765. if (this._isAlphaBlendDirty) {
  10766. if (this._alphaBlend) {
  10767. gl.enable(gl.BLEND);
  10768. }
  10769. else {
  10770. gl.disable(gl.BLEND);
  10771. }
  10772. this._isAlphaBlendDirty = false;
  10773. }
  10774. // Alpha function
  10775. if (this._isBlendFunctionParametersDirty) {
  10776. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10777. this._isBlendFunctionParametersDirty = false;
  10778. }
  10779. // Alpha equation
  10780. if (this._isBlendEquationParametersDirty) {
  10781. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10782. this._isBlendEquationParametersDirty = false;
  10783. }
  10784. // Constants
  10785. if (this._isBlendConstantsDirty) {
  10786. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10787. this._isBlendConstantsDirty = false;
  10788. }
  10789. };
  10790. return _AlphaState;
  10791. }());
  10792. BABYLON._AlphaState = _AlphaState;
  10793. })(BABYLON || (BABYLON = {}));
  10794. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10795. var BABYLON;
  10796. (function (BABYLON) {
  10797. /**
  10798. * @hidden
  10799. **/
  10800. var _DepthCullingState = /** @class */ (function () {
  10801. /**
  10802. * Initializes the state.
  10803. */
  10804. function _DepthCullingState() {
  10805. this._isDepthTestDirty = false;
  10806. this._isDepthMaskDirty = false;
  10807. this._isDepthFuncDirty = false;
  10808. this._isCullFaceDirty = false;
  10809. this._isCullDirty = false;
  10810. this._isZOffsetDirty = false;
  10811. this._isFrontFaceDirty = false;
  10812. this.reset();
  10813. }
  10814. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10815. get: function () {
  10816. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10822. get: function () {
  10823. return this._zOffset;
  10824. },
  10825. set: function (value) {
  10826. if (this._zOffset === value) {
  10827. return;
  10828. }
  10829. this._zOffset = value;
  10830. this._isZOffsetDirty = true;
  10831. },
  10832. enumerable: true,
  10833. configurable: true
  10834. });
  10835. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10836. get: function () {
  10837. return this._cullFace;
  10838. },
  10839. set: function (value) {
  10840. if (this._cullFace === value) {
  10841. return;
  10842. }
  10843. this._cullFace = value;
  10844. this._isCullFaceDirty = true;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10850. get: function () {
  10851. return this._cull;
  10852. },
  10853. set: function (value) {
  10854. if (this._cull === value) {
  10855. return;
  10856. }
  10857. this._cull = value;
  10858. this._isCullDirty = true;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10864. get: function () {
  10865. return this._depthFunc;
  10866. },
  10867. set: function (value) {
  10868. if (this._depthFunc === value) {
  10869. return;
  10870. }
  10871. this._depthFunc = value;
  10872. this._isDepthFuncDirty = true;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10878. get: function () {
  10879. return this._depthMask;
  10880. },
  10881. set: function (value) {
  10882. if (this._depthMask === value) {
  10883. return;
  10884. }
  10885. this._depthMask = value;
  10886. this._isDepthMaskDirty = true;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10892. get: function () {
  10893. return this._depthTest;
  10894. },
  10895. set: function (value) {
  10896. if (this._depthTest === value) {
  10897. return;
  10898. }
  10899. this._depthTest = value;
  10900. this._isDepthTestDirty = true;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10906. get: function () {
  10907. return this._frontFace;
  10908. },
  10909. set: function (value) {
  10910. if (this._frontFace === value) {
  10911. return;
  10912. }
  10913. this._frontFace = value;
  10914. this._isFrontFaceDirty = true;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. _DepthCullingState.prototype.reset = function () {
  10920. this._depthMask = true;
  10921. this._depthTest = true;
  10922. this._depthFunc = null;
  10923. this._cullFace = null;
  10924. this._cull = null;
  10925. this._zOffset = 0;
  10926. this._frontFace = null;
  10927. this._isDepthTestDirty = true;
  10928. this._isDepthMaskDirty = true;
  10929. this._isDepthFuncDirty = false;
  10930. this._isCullFaceDirty = false;
  10931. this._isCullDirty = false;
  10932. this._isZOffsetDirty = false;
  10933. this._isFrontFaceDirty = false;
  10934. };
  10935. _DepthCullingState.prototype.apply = function (gl) {
  10936. if (!this.isDirty) {
  10937. return;
  10938. }
  10939. // Cull
  10940. if (this._isCullDirty) {
  10941. if (this.cull) {
  10942. gl.enable(gl.CULL_FACE);
  10943. }
  10944. else {
  10945. gl.disable(gl.CULL_FACE);
  10946. }
  10947. this._isCullDirty = false;
  10948. }
  10949. // Cull face
  10950. if (this._isCullFaceDirty) {
  10951. gl.cullFace(this.cullFace);
  10952. this._isCullFaceDirty = false;
  10953. }
  10954. // Depth mask
  10955. if (this._isDepthMaskDirty) {
  10956. gl.depthMask(this.depthMask);
  10957. this._isDepthMaskDirty = false;
  10958. }
  10959. // Depth test
  10960. if (this._isDepthTestDirty) {
  10961. if (this.depthTest) {
  10962. gl.enable(gl.DEPTH_TEST);
  10963. }
  10964. else {
  10965. gl.disable(gl.DEPTH_TEST);
  10966. }
  10967. this._isDepthTestDirty = false;
  10968. }
  10969. // Depth func
  10970. if (this._isDepthFuncDirty) {
  10971. gl.depthFunc(this.depthFunc);
  10972. this._isDepthFuncDirty = false;
  10973. }
  10974. // zOffset
  10975. if (this._isZOffsetDirty) {
  10976. if (this.zOffset) {
  10977. gl.enable(gl.POLYGON_OFFSET_FILL);
  10978. gl.polygonOffset(this.zOffset, 0);
  10979. }
  10980. else {
  10981. gl.disable(gl.POLYGON_OFFSET_FILL);
  10982. }
  10983. this._isZOffsetDirty = false;
  10984. }
  10985. // Front face
  10986. if (this._isFrontFaceDirty) {
  10987. gl.frontFace(this.frontFace);
  10988. this._isFrontFaceDirty = false;
  10989. }
  10990. };
  10991. return _DepthCullingState;
  10992. }());
  10993. BABYLON._DepthCullingState = _DepthCullingState;
  10994. })(BABYLON || (BABYLON = {}));
  10995. //# sourceMappingURL=babylon.depthCullingState.js.map
  10996. var BABYLON;
  10997. (function (BABYLON) {
  10998. /**
  10999. * @hidden
  11000. **/
  11001. var _StencilState = /** @class */ (function () {
  11002. function _StencilState() {
  11003. this._isStencilTestDirty = false;
  11004. this._isStencilMaskDirty = false;
  11005. this._isStencilFuncDirty = false;
  11006. this._isStencilOpDirty = false;
  11007. this.reset();
  11008. }
  11009. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11010. get: function () {
  11011. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11017. get: function () {
  11018. return this._stencilFunc;
  11019. },
  11020. set: function (value) {
  11021. if (this._stencilFunc === value) {
  11022. return;
  11023. }
  11024. this._stencilFunc = value;
  11025. this._isStencilFuncDirty = true;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11031. get: function () {
  11032. return this._stencilFuncRef;
  11033. },
  11034. set: function (value) {
  11035. if (this._stencilFuncRef === value) {
  11036. return;
  11037. }
  11038. this._stencilFuncRef = value;
  11039. this._isStencilFuncDirty = true;
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11045. get: function () {
  11046. return this._stencilFuncMask;
  11047. },
  11048. set: function (value) {
  11049. if (this._stencilFuncMask === value) {
  11050. return;
  11051. }
  11052. this._stencilFuncMask = value;
  11053. this._isStencilFuncDirty = true;
  11054. },
  11055. enumerable: true,
  11056. configurable: true
  11057. });
  11058. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11059. get: function () {
  11060. return this._stencilOpStencilFail;
  11061. },
  11062. set: function (value) {
  11063. if (this._stencilOpStencilFail === value) {
  11064. return;
  11065. }
  11066. this._stencilOpStencilFail = value;
  11067. this._isStencilOpDirty = true;
  11068. },
  11069. enumerable: true,
  11070. configurable: true
  11071. });
  11072. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11073. get: function () {
  11074. return this._stencilOpDepthFail;
  11075. },
  11076. set: function (value) {
  11077. if (this._stencilOpDepthFail === value) {
  11078. return;
  11079. }
  11080. this._stencilOpDepthFail = value;
  11081. this._isStencilOpDirty = true;
  11082. },
  11083. enumerable: true,
  11084. configurable: true
  11085. });
  11086. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11087. get: function () {
  11088. return this._stencilOpStencilDepthPass;
  11089. },
  11090. set: function (value) {
  11091. if (this._stencilOpStencilDepthPass === value) {
  11092. return;
  11093. }
  11094. this._stencilOpStencilDepthPass = value;
  11095. this._isStencilOpDirty = true;
  11096. },
  11097. enumerable: true,
  11098. configurable: true
  11099. });
  11100. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11101. get: function () {
  11102. return this._stencilMask;
  11103. },
  11104. set: function (value) {
  11105. if (this._stencilMask === value) {
  11106. return;
  11107. }
  11108. this._stencilMask = value;
  11109. this._isStencilMaskDirty = true;
  11110. },
  11111. enumerable: true,
  11112. configurable: true
  11113. });
  11114. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11115. get: function () {
  11116. return this._stencilTest;
  11117. },
  11118. set: function (value) {
  11119. if (this._stencilTest === value) {
  11120. return;
  11121. }
  11122. this._stencilTest = value;
  11123. this._isStencilTestDirty = true;
  11124. },
  11125. enumerable: true,
  11126. configurable: true
  11127. });
  11128. _StencilState.prototype.reset = function () {
  11129. this._stencilTest = false;
  11130. this._stencilMask = 0xFF;
  11131. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11132. this._stencilFuncRef = 1;
  11133. this._stencilFuncMask = 0xFF;
  11134. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11135. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11136. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11137. this._isStencilTestDirty = true;
  11138. this._isStencilMaskDirty = true;
  11139. this._isStencilFuncDirty = true;
  11140. this._isStencilOpDirty = true;
  11141. };
  11142. _StencilState.prototype.apply = function (gl) {
  11143. if (!this.isDirty) {
  11144. return;
  11145. }
  11146. // Stencil test
  11147. if (this._isStencilTestDirty) {
  11148. if (this.stencilTest) {
  11149. gl.enable(gl.STENCIL_TEST);
  11150. }
  11151. else {
  11152. gl.disable(gl.STENCIL_TEST);
  11153. }
  11154. this._isStencilTestDirty = false;
  11155. }
  11156. // Stencil mask
  11157. if (this._isStencilMaskDirty) {
  11158. gl.stencilMask(this.stencilMask);
  11159. this._isStencilMaskDirty = false;
  11160. }
  11161. // Stencil func
  11162. if (this._isStencilFuncDirty) {
  11163. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11164. this._isStencilFuncDirty = false;
  11165. }
  11166. // Stencil op
  11167. if (this._isStencilOpDirty) {
  11168. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11169. this._isStencilOpDirty = false;
  11170. }
  11171. };
  11172. return _StencilState;
  11173. }());
  11174. BABYLON._StencilState = _StencilState;
  11175. })(BABYLON || (BABYLON = {}));
  11176. //# sourceMappingURL=babylon.stencilState.js.map
  11177. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11178. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11179. s = arguments[i];
  11180. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11181. t[p] = s[p];
  11182. }
  11183. return t;
  11184. };
  11185. var BABYLON;
  11186. (function (BABYLON) {
  11187. /**
  11188. * Keeps track of all the buffer info used in engine.
  11189. */
  11190. var BufferPointer = /** @class */ (function () {
  11191. function BufferPointer() {
  11192. }
  11193. return BufferPointer;
  11194. }());
  11195. /**
  11196. * Interface for attribute information associated with buffer instanciation
  11197. */
  11198. var InstancingAttributeInfo = /** @class */ (function () {
  11199. function InstancingAttributeInfo() {
  11200. }
  11201. return InstancingAttributeInfo;
  11202. }());
  11203. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11204. /**
  11205. * Define options used to create a render target texture
  11206. */
  11207. var RenderTargetCreationOptions = /** @class */ (function () {
  11208. function RenderTargetCreationOptions() {
  11209. }
  11210. return RenderTargetCreationOptions;
  11211. }());
  11212. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11213. /**
  11214. * Define options used to create a depth texture
  11215. */
  11216. var DepthTextureCreationOptions = /** @class */ (function () {
  11217. function DepthTextureCreationOptions() {
  11218. }
  11219. return DepthTextureCreationOptions;
  11220. }());
  11221. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11222. /**
  11223. * Class used to describe the capabilities of the engine relatively to the current browser
  11224. */
  11225. var EngineCapabilities = /** @class */ (function () {
  11226. function EngineCapabilities() {
  11227. }
  11228. return EngineCapabilities;
  11229. }());
  11230. BABYLON.EngineCapabilities = EngineCapabilities;
  11231. /**
  11232. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11233. */
  11234. var Engine = /** @class */ (function () {
  11235. /**
  11236. * Creates a new engine
  11237. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11238. * @param antialias defines enable antialiasing (default: false)
  11239. * @param options defines further options to be sent to the getContext() function
  11240. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11241. */
  11242. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11243. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11244. var _this = this;
  11245. // Public members
  11246. /**
  11247. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11248. */
  11249. this.forcePOTTextures = false;
  11250. /**
  11251. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11252. */
  11253. this.isFullscreen = false;
  11254. /**
  11255. * Gets a boolean indicating if the pointer is currently locked
  11256. */
  11257. this.isPointerLock = false;
  11258. /**
  11259. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11260. */
  11261. this.cullBackFaces = true;
  11262. /**
  11263. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11264. */
  11265. this.renderEvenInBackground = true;
  11266. /**
  11267. * Gets or sets a boolean indicating that cache can be kept between frames
  11268. */
  11269. this.preventCacheWipeBetweenFrames = false;
  11270. /**
  11271. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11272. **/
  11273. this.enableOfflineSupport = false;
  11274. /**
  11275. * 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)
  11276. **/
  11277. this.disableManifestCheck = false;
  11278. /**
  11279. * Gets the list of created scenes
  11280. */
  11281. this.scenes = new Array();
  11282. /**
  11283. * Gets the list of created postprocesses
  11284. */
  11285. this.postProcesses = new Array();
  11286. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11287. this.validateShaderPrograms = false;
  11288. // Observables
  11289. /**
  11290. * Observable event triggered each time the rendering canvas is resized
  11291. */
  11292. this.onResizeObservable = new BABYLON.Observable();
  11293. /**
  11294. * Observable event triggered each time the canvas loses focus
  11295. */
  11296. this.onCanvasBlurObservable = new BABYLON.Observable();
  11297. /**
  11298. * Observable event triggered each time the canvas gains focus
  11299. */
  11300. this.onCanvasFocusObservable = new BABYLON.Observable();
  11301. /**
  11302. * Observable event triggered each time the canvas receives pointerout event
  11303. */
  11304. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11305. /**
  11306. * Observable event triggered before each texture is initialized
  11307. */
  11308. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11309. //WebVR
  11310. this._vrDisplay = undefined;
  11311. this._vrSupported = false;
  11312. this._vrExclusivePointerMode = false;
  11313. // Uniform buffers list
  11314. /**
  11315. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11316. */
  11317. this.disableUniformBuffers = false;
  11318. /** @hidden */
  11319. this._uniformBuffers = new Array();
  11320. // Observables
  11321. /**
  11322. * Observable raised when the engine begins a new frame
  11323. */
  11324. this.onBeginFrameObservable = new BABYLON.Observable();
  11325. /**
  11326. * Observable raised when the engine ends the current frame
  11327. */
  11328. this.onEndFrameObservable = new BABYLON.Observable();
  11329. /**
  11330. * Observable raised when the engine is about to compile a shader
  11331. */
  11332. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11333. /**
  11334. * Observable raised when the engine has jsut compiled a shader
  11335. */
  11336. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11337. this._windowIsBackground = false;
  11338. this._webGLVersion = 1.0;
  11339. /** @hidden */
  11340. this._badOS = false;
  11341. /** @hidden */
  11342. this._badDesktopOS = false;
  11343. /**
  11344. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11345. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11346. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11347. */
  11348. this.disableTextureBindingOptimization = false;
  11349. /**
  11350. * Observable signaled when VR display mode changes
  11351. */
  11352. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11353. /**
  11354. * Observable signaled when VR request present is complete
  11355. */
  11356. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11357. /**
  11358. * Observable signaled when VR request present starts
  11359. */
  11360. this.onVRRequestPresentStart = new BABYLON.Observable();
  11361. this._colorWrite = true;
  11362. /** @hidden */
  11363. this._drawCalls = new BABYLON.PerfCounter();
  11364. /** @hidden */
  11365. this._textureCollisions = new BABYLON.PerfCounter();
  11366. this._renderingQueueLaunched = false;
  11367. this._activeRenderLoops = new Array();
  11368. // Deterministic lockstepMaxSteps
  11369. this._deterministicLockstep = false;
  11370. this._lockstepMaxSteps = 4;
  11371. // Lost context
  11372. /**
  11373. * Observable signaled when a context lost event is raised
  11374. */
  11375. this.onContextLostObservable = new BABYLON.Observable();
  11376. /**
  11377. * Observable signaled when a context restored event is raised
  11378. */
  11379. this.onContextRestoredObservable = new BABYLON.Observable();
  11380. this._contextWasLost = false;
  11381. this._doNotHandleContextLost = false;
  11382. // FPS
  11383. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11384. this._fps = 60;
  11385. this._deltaTime = 0;
  11386. /**
  11387. * Turn this value on if you want to pause FPS computation when in background
  11388. */
  11389. this.disablePerformanceMonitorInBackground = false;
  11390. // States
  11391. /** @hidden */
  11392. this._depthCullingState = new BABYLON._DepthCullingState();
  11393. /** @hidden */
  11394. this._stencilState = new BABYLON._StencilState();
  11395. /** @hidden */
  11396. this._alphaState = new BABYLON._AlphaState();
  11397. /** @hidden */
  11398. this._alphaMode = Engine.ALPHA_DISABLE;
  11399. // Cache
  11400. this._internalTexturesCache = new Array();
  11401. /** @hidden */
  11402. this._activeChannel = 0;
  11403. this._currentTextureChannel = -1;
  11404. /** @hidden */
  11405. this._boundTexturesCache = {};
  11406. this._compiledEffects = {};
  11407. this._vertexAttribArraysEnabled = [];
  11408. this._uintIndicesCurrentlySet = false;
  11409. this._currentBoundBuffer = new Array();
  11410. /** @hidden */
  11411. this._currentFramebuffer = null;
  11412. this._currentBufferPointers = new Array();
  11413. this._currentInstanceLocations = new Array();
  11414. this._currentInstanceBuffers = new Array();
  11415. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11416. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11417. this._vaoRecordInProgress = false;
  11418. this._mustWipeVertexAttributes = false;
  11419. this._nextFreeTextureSlots = new Array();
  11420. this._maxSimultaneousTextures = 0;
  11421. this._activeRequests = new Array();
  11422. // Hardware supported Compressed Textures
  11423. this._texturesSupported = new Array();
  11424. /**
  11425. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11426. */
  11427. this.premultipliedAlpha = true;
  11428. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11429. this._onVRFullScreenTriggered = function () {
  11430. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11431. //get the old size before we change
  11432. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11433. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11434. //get the width and height, change the render size
  11435. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11436. _this.setHardwareScalingLevel(1);
  11437. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11438. }
  11439. else {
  11440. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11441. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11442. }
  11443. };
  11444. this._unpackFlipYCached = null;
  11445. this._boundUniforms = {};
  11446. // Register promises
  11447. BABYLON.PromisePolyfill.Apply();
  11448. var canvas = null;
  11449. Engine.Instances.push(this);
  11450. if (!canvasOrContext) {
  11451. return;
  11452. }
  11453. options = options || {};
  11454. if (canvasOrContext.getContext) {
  11455. canvas = canvasOrContext;
  11456. this._renderingCanvas = canvas;
  11457. if (antialias != null) {
  11458. options.antialias = antialias;
  11459. }
  11460. if (options.deterministicLockstep === undefined) {
  11461. options.deterministicLockstep = false;
  11462. }
  11463. if (options.lockstepMaxSteps === undefined) {
  11464. options.lockstepMaxSteps = 4;
  11465. }
  11466. if (options.preserveDrawingBuffer === undefined) {
  11467. options.preserveDrawingBuffer = false;
  11468. }
  11469. if (options.audioEngine === undefined) {
  11470. options.audioEngine = true;
  11471. }
  11472. if (options.stencil === undefined) {
  11473. options.stencil = true;
  11474. }
  11475. if (options.premultipliedAlpha === false) {
  11476. this.premultipliedAlpha = false;
  11477. }
  11478. this._deterministicLockstep = options.deterministicLockstep;
  11479. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11480. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11481. // Exceptions
  11482. if (navigator && navigator.userAgent) {
  11483. var ua = navigator.userAgent;
  11484. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11485. var exception = _a[_i];
  11486. var key = exception.key;
  11487. var targets = exception.targets;
  11488. if (ua.indexOf(key) > -1) {
  11489. if (exception.capture && exception.captureConstraint) {
  11490. var capture = exception.capture;
  11491. var constraint = exception.captureConstraint;
  11492. var regex = new RegExp(capture);
  11493. var matches = regex.exec(ua);
  11494. if (matches && matches.length > 0) {
  11495. var capturedValue = parseInt(matches[matches.length - 1]);
  11496. if (capturedValue >= constraint) {
  11497. continue;
  11498. }
  11499. }
  11500. }
  11501. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11502. var target = targets_1[_b];
  11503. switch (target) {
  11504. case "uniformBuffer":
  11505. this.disableUniformBuffers = true;
  11506. break;
  11507. case "textureBindingOptimization":
  11508. this.disableTextureBindingOptimization = true;
  11509. break;
  11510. }
  11511. }
  11512. }
  11513. }
  11514. }
  11515. // GL
  11516. if (!options.disableWebGL2Support) {
  11517. try {
  11518. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11519. if (this._gl) {
  11520. this._webGLVersion = 2.0;
  11521. }
  11522. }
  11523. catch (e) {
  11524. // Do nothing
  11525. }
  11526. }
  11527. if (!this._gl) {
  11528. if (!canvas) {
  11529. throw new Error("The provided canvas is null or undefined.");
  11530. }
  11531. try {
  11532. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11533. }
  11534. catch (e) {
  11535. throw new Error("WebGL not supported");
  11536. }
  11537. }
  11538. if (!this._gl) {
  11539. throw new Error("WebGL not supported");
  11540. }
  11541. this._onCanvasFocus = function () {
  11542. _this.onCanvasFocusObservable.notifyObservers(_this);
  11543. };
  11544. this._onCanvasBlur = function () {
  11545. _this.onCanvasBlurObservable.notifyObservers(_this);
  11546. };
  11547. canvas.addEventListener("focus", this._onCanvasFocus);
  11548. canvas.addEventListener("blur", this._onCanvasBlur);
  11549. this._onBlur = function () {
  11550. if (_this.disablePerformanceMonitorInBackground) {
  11551. _this._performanceMonitor.disable();
  11552. }
  11553. _this._windowIsBackground = true;
  11554. };
  11555. this._onFocus = function () {
  11556. if (_this.disablePerformanceMonitorInBackground) {
  11557. _this._performanceMonitor.enable();
  11558. }
  11559. _this._windowIsBackground = false;
  11560. };
  11561. this._onCanvasPointerOut = function (ev) {
  11562. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11563. };
  11564. window.addEventListener("blur", this._onBlur);
  11565. window.addEventListener("focus", this._onFocus);
  11566. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11567. // Context lost
  11568. if (!this._doNotHandleContextLost) {
  11569. this._onContextLost = function (evt) {
  11570. evt.preventDefault();
  11571. _this._contextWasLost = true;
  11572. BABYLON.Tools.Warn("WebGL context lost.");
  11573. _this.onContextLostObservable.notifyObservers(_this);
  11574. };
  11575. this._onContextRestored = function (evt) {
  11576. // Adding a timeout to avoid race condition at browser level
  11577. setTimeout(function () {
  11578. // Rebuild gl context
  11579. _this._initGLContext();
  11580. // Rebuild effects
  11581. _this._rebuildEffects();
  11582. // Rebuild textures
  11583. _this._rebuildInternalTextures();
  11584. // Rebuild buffers
  11585. _this._rebuildBuffers();
  11586. // Cache
  11587. _this.wipeCaches(true);
  11588. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11589. _this.onContextRestoredObservable.notifyObservers(_this);
  11590. _this._contextWasLost = false;
  11591. }, 0);
  11592. };
  11593. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11594. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11595. }
  11596. }
  11597. else {
  11598. this._gl = canvasOrContext;
  11599. this._renderingCanvas = this._gl.canvas;
  11600. if (this._gl.renderbufferStorageMultisample) {
  11601. this._webGLVersion = 2.0;
  11602. }
  11603. options.stencil = this._gl.getContextAttributes().stencil;
  11604. }
  11605. // Viewport
  11606. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11607. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11608. this.resize();
  11609. this._isStencilEnable = options.stencil ? true : false;
  11610. this._initGLContext();
  11611. if (canvas) {
  11612. // Fullscreen
  11613. this._onFullscreenChange = function () {
  11614. if (document.fullscreen !== undefined) {
  11615. _this.isFullscreen = document.fullscreen;
  11616. }
  11617. else if (document.mozFullScreen !== undefined) {
  11618. _this.isFullscreen = document.mozFullScreen;
  11619. }
  11620. else if (document.webkitIsFullScreen !== undefined) {
  11621. _this.isFullscreen = document.webkitIsFullScreen;
  11622. }
  11623. else if (document.msIsFullScreen !== undefined) {
  11624. _this.isFullscreen = document.msIsFullScreen;
  11625. }
  11626. // Pointer lock
  11627. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11628. canvas.requestPointerLock = canvas.requestPointerLock ||
  11629. canvas.msRequestPointerLock ||
  11630. canvas.mozRequestPointerLock ||
  11631. canvas.webkitRequestPointerLock;
  11632. if (canvas.requestPointerLock) {
  11633. canvas.requestPointerLock();
  11634. }
  11635. }
  11636. };
  11637. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11638. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11639. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11640. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11641. // Pointer lock
  11642. this._onPointerLockChange = function () {
  11643. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11644. document.webkitPointerLockElement === canvas ||
  11645. document.msPointerLockElement === canvas ||
  11646. document.pointerLockElement === canvas);
  11647. };
  11648. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11649. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11650. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11651. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11652. this._onVRDisplayPointerRestricted = function () {
  11653. if (canvas) {
  11654. canvas.requestPointerLock();
  11655. }
  11656. };
  11657. this._onVRDisplayPointerUnrestricted = function () {
  11658. document.exitPointerLock();
  11659. };
  11660. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11661. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11662. }
  11663. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11664. Engine.audioEngine = new BABYLON.AudioEngine();
  11665. }
  11666. // Prepare buffer pointers
  11667. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11668. this._currentBufferPointers[i] = new BufferPointer();
  11669. }
  11670. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11671. // Load WebVR Devices
  11672. if (options.autoEnableWebVR) {
  11673. this.initWebVR();
  11674. }
  11675. // Detect if we are running on a faulty buggy OS.
  11676. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11677. // Detect if we are running on a faulty buggy desktop OS.
  11678. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11679. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11680. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11681. }
  11682. Object.defineProperty(Engine, "LastCreatedEngine", {
  11683. /**
  11684. * Gets the latest created engine
  11685. */
  11686. get: function () {
  11687. if (Engine.Instances.length === 0) {
  11688. return null;
  11689. }
  11690. return Engine.Instances[Engine.Instances.length - 1];
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Engine, "LastCreatedScene", {
  11696. /**
  11697. * Gets the latest created scene
  11698. */
  11699. get: function () {
  11700. var lastCreatedEngine = Engine.LastCreatedEngine;
  11701. if (!lastCreatedEngine) {
  11702. return null;
  11703. }
  11704. if (lastCreatedEngine.scenes.length === 0) {
  11705. return null;
  11706. }
  11707. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. /**
  11713. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11714. * @param flag defines which part of the materials must be marked as dirty
  11715. * @param predicate defines a predicate used to filter which materials should be affected
  11716. */
  11717. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11718. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11719. var engine = Engine.Instances[engineIndex];
  11720. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11721. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11722. }
  11723. }
  11724. };
  11725. Object.defineProperty(Engine, "Version", {
  11726. /**
  11727. * Returns the current version of the framework
  11728. */
  11729. get: function () {
  11730. return "3.3.0-alpha.11";
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11736. /**
  11737. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11738. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11739. */
  11740. get: function () {
  11741. return this._vrExclusivePointerMode;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11747. /**
  11748. * Gets a boolean indicating that the engine supports uniform buffers
  11749. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11750. */
  11751. get: function () {
  11752. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11758. /**
  11759. * Gets a boolean indicating that only power of 2 textures are supported
  11760. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11761. */
  11762. get: function () {
  11763. return this._webGLVersion < 2 || this.forcePOTTextures;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11769. /**
  11770. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11771. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11772. */
  11773. get: function () {
  11774. return this._doNotHandleContextLost;
  11775. },
  11776. set: function (value) {
  11777. this._doNotHandleContextLost = value;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11783. /**
  11784. * Gets the performance monitor attached to this engine
  11785. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11786. */
  11787. get: function () {
  11788. return this._performanceMonitor;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11794. /**
  11795. * Gets the list of texture formats supported
  11796. */
  11797. get: function () {
  11798. return this._texturesSupported;
  11799. },
  11800. enumerable: true,
  11801. configurable: true
  11802. });
  11803. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11804. /**
  11805. * Gets the list of texture formats in use
  11806. */
  11807. get: function () {
  11808. return this._textureFormatInUse;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine.prototype, "currentViewport", {
  11814. /**
  11815. * Gets the current viewport
  11816. */
  11817. get: function () {
  11818. return this._cachedViewport;
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11824. /**
  11825. * Gets the default empty texture
  11826. */
  11827. get: function () {
  11828. if (!this._emptyTexture) {
  11829. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11830. }
  11831. return this._emptyTexture;
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11837. /**
  11838. * Gets the default empty 3D texture
  11839. */
  11840. get: function () {
  11841. if (!this._emptyTexture3D) {
  11842. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11843. }
  11844. return this._emptyTexture3D;
  11845. },
  11846. enumerable: true,
  11847. configurable: true
  11848. });
  11849. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11850. /**
  11851. * Gets the default empty cube texture
  11852. */
  11853. get: function () {
  11854. if (!this._emptyCubeTexture) {
  11855. var faceData = new Uint8Array(4);
  11856. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11857. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11858. }
  11859. return this._emptyCubeTexture;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Engine.prototype._rebuildInternalTextures = function () {
  11865. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11866. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11867. var internalTexture = currentState_1[_i];
  11868. internalTexture._rebuild();
  11869. }
  11870. };
  11871. Engine.prototype._rebuildEffects = function () {
  11872. for (var key in this._compiledEffects) {
  11873. var effect = this._compiledEffects[key];
  11874. effect._prepareEffect();
  11875. }
  11876. BABYLON.Effect.ResetCache();
  11877. };
  11878. Engine.prototype._rebuildBuffers = function () {
  11879. // Index / Vertex
  11880. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11881. var scene = _a[_i];
  11882. scene.resetCachedMaterial();
  11883. scene._rebuildGeometries();
  11884. scene._rebuildTextures();
  11885. }
  11886. // Uniforms
  11887. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11888. var uniformBuffer = _c[_b];
  11889. uniformBuffer._rebuild();
  11890. }
  11891. };
  11892. Engine.prototype._initGLContext = function () {
  11893. // Caps
  11894. this._caps = new EngineCapabilities();
  11895. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11896. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11897. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11898. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11899. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11900. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11901. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11902. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11903. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11904. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11905. // Infos
  11906. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11907. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11908. if (rendererInfo != null) {
  11909. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11910. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11911. }
  11912. if (!this._glVendor) {
  11913. this._glVendor = "Unknown vendor";
  11914. }
  11915. if (!this._glRenderer) {
  11916. this._glRenderer = "Unknown renderer";
  11917. }
  11918. // Constants
  11919. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11920. if (this._gl.RGBA16F !== 0x881A) {
  11921. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11922. }
  11923. if (this._gl.RGBA32F !== 0x8814) {
  11924. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11925. }
  11926. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11927. this._gl.DEPTH24_STENCIL8 = 35056;
  11928. }
  11929. // Extensions
  11930. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11931. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11932. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11933. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11934. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11935. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11936. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11937. 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');
  11938. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11939. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11940. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11941. this._caps.highPrecisionShaderSupported = true;
  11942. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11943. if (this._caps.timerQuery) {
  11944. if (this._webGLVersion === 1) {
  11945. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11946. }
  11947. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11948. }
  11949. // Checks if some of the format renders first to allow the use of webgl inspector.
  11950. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11951. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11952. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11953. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11954. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11955. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11956. if (this._webGLVersion > 1) {
  11957. this._gl.HALF_FLOAT_OES = 0x140B;
  11958. }
  11959. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11960. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11961. // Draw buffers
  11962. if (this._webGLVersion > 1) {
  11963. this._caps.drawBuffersExtension = true;
  11964. }
  11965. else {
  11966. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11967. if (drawBuffersExtension !== null) {
  11968. this._caps.drawBuffersExtension = true;
  11969. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11970. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11971. for (var i = 0; i < 16; i++) {
  11972. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11973. }
  11974. }
  11975. else {
  11976. this._caps.drawBuffersExtension = false;
  11977. }
  11978. }
  11979. // Depth Texture
  11980. if (this._webGLVersion > 1) {
  11981. this._caps.depthTextureExtension = true;
  11982. }
  11983. else {
  11984. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11985. if (depthTextureExtension != null) {
  11986. this._caps.depthTextureExtension = true;
  11987. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11988. }
  11989. }
  11990. // Vertex array object
  11991. if (this._webGLVersion > 1) {
  11992. this._caps.vertexArrayObject = true;
  11993. }
  11994. else {
  11995. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11996. if (vertexArrayObjectExtension != null) {
  11997. this._caps.vertexArrayObject = true;
  11998. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11999. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12000. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12001. }
  12002. else {
  12003. this._caps.vertexArrayObject = false;
  12004. }
  12005. }
  12006. // Instances count
  12007. if (this._webGLVersion > 1) {
  12008. this._caps.instancedArrays = true;
  12009. }
  12010. else {
  12011. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12012. if (instanceExtension != null) {
  12013. this._caps.instancedArrays = true;
  12014. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12015. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12016. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12017. }
  12018. else {
  12019. this._caps.instancedArrays = false;
  12020. }
  12021. }
  12022. // Intelligently add supported compressed formats in order to check for.
  12023. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12024. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12025. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12026. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12027. if (this._caps.astc)
  12028. this.texturesSupported.push('-astc.ktx');
  12029. if (this._caps.s3tc)
  12030. this.texturesSupported.push('-dxt.ktx');
  12031. if (this._caps.pvrtc)
  12032. this.texturesSupported.push('-pvrtc.ktx');
  12033. if (this._caps.etc2)
  12034. this.texturesSupported.push('-etc2.ktx');
  12035. if (this._caps.etc1)
  12036. this.texturesSupported.push('-etc1.ktx');
  12037. if (this._gl.getShaderPrecisionFormat) {
  12038. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12039. if (highp) {
  12040. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12041. }
  12042. }
  12043. // Depth buffer
  12044. this.setDepthBuffer(true);
  12045. this.setDepthFunctionToLessOrEqual();
  12046. this.setDepthWrite(true);
  12047. // Texture maps
  12048. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12049. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12050. this._nextFreeTextureSlots.push(slot);
  12051. }
  12052. };
  12053. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12054. /**
  12055. * Gets version of the current webGL context
  12056. */
  12057. get: function () {
  12058. return this._webGLVersion;
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12064. /**
  12065. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12066. */
  12067. get: function () {
  12068. return this._isStencilEnable;
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Engine.prototype._prepareWorkingCanvas = function () {
  12074. if (this._workingCanvas) {
  12075. return;
  12076. }
  12077. this._workingCanvas = document.createElement("canvas");
  12078. var context = this._workingCanvas.getContext("2d");
  12079. if (context) {
  12080. this._workingContext = context;
  12081. }
  12082. };
  12083. /**
  12084. * Reset the texture cache to empty state
  12085. */
  12086. Engine.prototype.resetTextureCache = function () {
  12087. for (var key in this._boundTexturesCache) {
  12088. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12089. continue;
  12090. }
  12091. var boundTexture = this._boundTexturesCache[key];
  12092. if (boundTexture) {
  12093. this._removeDesignatedSlot(boundTexture);
  12094. }
  12095. this._boundTexturesCache[key] = null;
  12096. }
  12097. if (!this.disableTextureBindingOptimization) {
  12098. this._nextFreeTextureSlots = [];
  12099. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12100. this._nextFreeTextureSlots.push(slot);
  12101. }
  12102. }
  12103. this._currentTextureChannel = -1;
  12104. };
  12105. /**
  12106. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12107. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12108. * @returns true if engine is in deterministic lock step mode
  12109. */
  12110. Engine.prototype.isDeterministicLockStep = function () {
  12111. return this._deterministicLockstep;
  12112. };
  12113. /**
  12114. * Gets the max steps when engine is running in deterministic lock step
  12115. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12116. * @returns the max steps
  12117. */
  12118. Engine.prototype.getLockstepMaxSteps = function () {
  12119. return this._lockstepMaxSteps;
  12120. };
  12121. /**
  12122. * Gets an object containing information about the current webGL context
  12123. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12124. */
  12125. Engine.prototype.getGlInfo = function () {
  12126. return {
  12127. vendor: this._glVendor,
  12128. renderer: this._glRenderer,
  12129. version: this._glVersion
  12130. };
  12131. };
  12132. /**
  12133. * Gets current aspect ratio
  12134. * @param camera defines the camera to use to get the aspect ratio
  12135. * @param useScreen defines if screen size must be used (or the current render target if any)
  12136. * @returns a number defining the aspect ratio
  12137. */
  12138. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12139. if (useScreen === void 0) { useScreen = false; }
  12140. var viewport = camera.viewport;
  12141. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12142. };
  12143. /**
  12144. * Gets current screen aspect ratio
  12145. * @returns a number defining the aspect ratio
  12146. */
  12147. Engine.prototype.getScreenAspectRatio = function () {
  12148. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12149. };
  12150. /**
  12151. * Gets the current render width
  12152. * @param useScreen defines if screen size must be used (or the current render target if any)
  12153. * @returns a number defining the current render width
  12154. */
  12155. Engine.prototype.getRenderWidth = function (useScreen) {
  12156. if (useScreen === void 0) { useScreen = false; }
  12157. if (!useScreen && this._currentRenderTarget) {
  12158. return this._currentRenderTarget.width;
  12159. }
  12160. return this._gl.drawingBufferWidth;
  12161. };
  12162. /**
  12163. * Gets the current render height
  12164. * @param useScreen defines if screen size must be used (or the current render target if any)
  12165. * @returns a number defining the current render height
  12166. */
  12167. Engine.prototype.getRenderHeight = function (useScreen) {
  12168. if (useScreen === void 0) { useScreen = false; }
  12169. if (!useScreen && this._currentRenderTarget) {
  12170. return this._currentRenderTarget.height;
  12171. }
  12172. return this._gl.drawingBufferHeight;
  12173. };
  12174. /**
  12175. * Gets the HTML canvas attached with the current webGL context
  12176. * @returns a HTML canvas
  12177. */
  12178. Engine.prototype.getRenderingCanvas = function () {
  12179. return this._renderingCanvas;
  12180. };
  12181. /**
  12182. * Gets the client rect of the HTML canvas attached with the current webGL context
  12183. * @returns a client rectanglee
  12184. */
  12185. Engine.prototype.getRenderingCanvasClientRect = function () {
  12186. if (!this._renderingCanvas) {
  12187. return null;
  12188. }
  12189. return this._renderingCanvas.getBoundingClientRect();
  12190. };
  12191. /**
  12192. * Defines the hardware scaling level.
  12193. * By default the hardware scaling level is computed from the window device ratio.
  12194. * 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.
  12195. * @param level defines the level to use
  12196. */
  12197. Engine.prototype.setHardwareScalingLevel = function (level) {
  12198. this._hardwareScalingLevel = level;
  12199. this.resize();
  12200. };
  12201. /**
  12202. * Gets the current hardware scaling level.
  12203. * By default the hardware scaling level is computed from the window device ratio.
  12204. * 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.
  12205. * @returns a number indicating the current hardware scaling level
  12206. */
  12207. Engine.prototype.getHardwareScalingLevel = function () {
  12208. return this._hardwareScalingLevel;
  12209. };
  12210. /**
  12211. * Gets the list of loaded textures
  12212. * @returns an array containing all loaded textures
  12213. */
  12214. Engine.prototype.getLoadedTexturesCache = function () {
  12215. return this._internalTexturesCache;
  12216. };
  12217. /**
  12218. * Gets the object containing all engine capabilities
  12219. * @returns the EngineCapabilities object
  12220. */
  12221. Engine.prototype.getCaps = function () {
  12222. return this._caps;
  12223. };
  12224. Object.defineProperty(Engine.prototype, "drawCalls", {
  12225. /** @hidden */
  12226. get: function () {
  12227. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12228. return 0;
  12229. },
  12230. enumerable: true,
  12231. configurable: true
  12232. });
  12233. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12234. /** @hidden */
  12235. get: function () {
  12236. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12237. return null;
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. /**
  12243. * Gets the current depth function
  12244. * @returns a number defining the depth function
  12245. */
  12246. Engine.prototype.getDepthFunction = function () {
  12247. return this._depthCullingState.depthFunc;
  12248. };
  12249. /**
  12250. * Sets the current depth function
  12251. * @param depthFunc defines the function to use
  12252. */
  12253. Engine.prototype.setDepthFunction = function (depthFunc) {
  12254. this._depthCullingState.depthFunc = depthFunc;
  12255. };
  12256. /**
  12257. * Sets the current depth function to GREATER
  12258. */
  12259. Engine.prototype.setDepthFunctionToGreater = function () {
  12260. this._depthCullingState.depthFunc = this._gl.GREATER;
  12261. };
  12262. /**
  12263. * Sets the current depth function to GEQUAL
  12264. */
  12265. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12266. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12267. };
  12268. /**
  12269. * Sets the current depth function to LESS
  12270. */
  12271. Engine.prototype.setDepthFunctionToLess = function () {
  12272. this._depthCullingState.depthFunc = this._gl.LESS;
  12273. };
  12274. /**
  12275. * Sets the current depth function to LEQUAL
  12276. */
  12277. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12278. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12279. };
  12280. /**
  12281. * Gets a boolean indicating if stencil buffer is enabled
  12282. * @returns the current stencil buffer state
  12283. */
  12284. Engine.prototype.getStencilBuffer = function () {
  12285. return this._stencilState.stencilTest;
  12286. };
  12287. /**
  12288. * Enable or disable the stencil buffer
  12289. * @param enable defines if the stencil buffer must be enabled or disabled
  12290. */
  12291. Engine.prototype.setStencilBuffer = function (enable) {
  12292. this._stencilState.stencilTest = enable;
  12293. };
  12294. /**
  12295. * Gets the current stencil mask
  12296. * @returns a number defining the new stencil mask to use
  12297. */
  12298. Engine.prototype.getStencilMask = function () {
  12299. return this._stencilState.stencilMask;
  12300. };
  12301. /**
  12302. * Sets the current stencil mask
  12303. * @param mask defines the new stencil mask to use
  12304. */
  12305. Engine.prototype.setStencilMask = function (mask) {
  12306. this._stencilState.stencilMask = mask;
  12307. };
  12308. /**
  12309. * Gets the current stencil function
  12310. * @returns a number defining the stencil function to use
  12311. */
  12312. Engine.prototype.getStencilFunction = function () {
  12313. return this._stencilState.stencilFunc;
  12314. };
  12315. /**
  12316. * Gets the current stencil reference value
  12317. * @returns a number defining the stencil reference value to use
  12318. */
  12319. Engine.prototype.getStencilFunctionReference = function () {
  12320. return this._stencilState.stencilFuncRef;
  12321. };
  12322. /**
  12323. * Gets the current stencil mask
  12324. * @returns a number defining the stencil mask to use
  12325. */
  12326. Engine.prototype.getStencilFunctionMask = function () {
  12327. return this._stencilState.stencilFuncMask;
  12328. };
  12329. /**
  12330. * Sets the current stencil function
  12331. * @param stencilFunc defines the new stencil function to use
  12332. */
  12333. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12334. this._stencilState.stencilFunc = stencilFunc;
  12335. };
  12336. /**
  12337. * Sets the current stencil reference
  12338. * @param reference defines the new stencil reference to use
  12339. */
  12340. Engine.prototype.setStencilFunctionReference = function (reference) {
  12341. this._stencilState.stencilFuncRef = reference;
  12342. };
  12343. /**
  12344. * Sets the current stencil mask
  12345. * @param mask defines the new stencil mask to use
  12346. */
  12347. Engine.prototype.setStencilFunctionMask = function (mask) {
  12348. this._stencilState.stencilFuncMask = mask;
  12349. };
  12350. /**
  12351. * Gets the current stencil operation when stencil fails
  12352. * @returns a number defining stencil operation to use when stencil fails
  12353. */
  12354. Engine.prototype.getStencilOperationFail = function () {
  12355. return this._stencilState.stencilOpStencilFail;
  12356. };
  12357. /**
  12358. * Gets the current stencil operation when depth fails
  12359. * @returns a number defining stencil operation to use when depth fails
  12360. */
  12361. Engine.prototype.getStencilOperationDepthFail = function () {
  12362. return this._stencilState.stencilOpDepthFail;
  12363. };
  12364. /**
  12365. * Gets the current stencil operation when stencil passes
  12366. * @returns a number defining stencil operation to use when stencil passes
  12367. */
  12368. Engine.prototype.getStencilOperationPass = function () {
  12369. return this._stencilState.stencilOpStencilDepthPass;
  12370. };
  12371. /**
  12372. * Sets the stencil operation to use when stencil fails
  12373. * @param operation defines the stencil operation to use when stencil fails
  12374. */
  12375. Engine.prototype.setStencilOperationFail = function (operation) {
  12376. this._stencilState.stencilOpStencilFail = operation;
  12377. };
  12378. /**
  12379. * Sets the stencil operation to use when depth fails
  12380. * @param operation defines the stencil operation to use when depth fails
  12381. */
  12382. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12383. this._stencilState.stencilOpDepthFail = operation;
  12384. };
  12385. /**
  12386. * Sets the stencil operation to use when stencil passes
  12387. * @param operation defines the stencil operation to use when stencil passes
  12388. */
  12389. Engine.prototype.setStencilOperationPass = function (operation) {
  12390. this._stencilState.stencilOpStencilDepthPass = operation;
  12391. };
  12392. /**
  12393. * Sets a boolean indicating if the dithering state is enabled or disabled
  12394. * @param value defines the dithering state
  12395. */
  12396. Engine.prototype.setDitheringState = function (value) {
  12397. if (value) {
  12398. this._gl.enable(this._gl.DITHER);
  12399. }
  12400. else {
  12401. this._gl.disable(this._gl.DITHER);
  12402. }
  12403. };
  12404. /**
  12405. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12406. * @param value defines the rasterizer state
  12407. */
  12408. Engine.prototype.setRasterizerState = function (value) {
  12409. if (value) {
  12410. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12411. }
  12412. else {
  12413. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12414. }
  12415. };
  12416. /**
  12417. * stop executing a render loop function and remove it from the execution array
  12418. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12419. */
  12420. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12421. if (!renderFunction) {
  12422. this._activeRenderLoops = [];
  12423. return;
  12424. }
  12425. var index = this._activeRenderLoops.indexOf(renderFunction);
  12426. if (index >= 0) {
  12427. this._activeRenderLoops.splice(index, 1);
  12428. }
  12429. };
  12430. /** @hidden */
  12431. Engine.prototype._renderLoop = function () {
  12432. if (!this._contextWasLost) {
  12433. var shouldRender = true;
  12434. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12435. shouldRender = false;
  12436. }
  12437. if (shouldRender) {
  12438. // Start new frame
  12439. this.beginFrame();
  12440. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12441. var renderFunction = this._activeRenderLoops[index];
  12442. renderFunction();
  12443. }
  12444. // Present
  12445. this.endFrame();
  12446. }
  12447. }
  12448. if (this._activeRenderLoops.length > 0) {
  12449. // Register new frame
  12450. var requester = null;
  12451. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12452. requester = this._vrDisplay;
  12453. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12454. }
  12455. else {
  12456. this._renderingQueueLaunched = false;
  12457. }
  12458. };
  12459. /**
  12460. * Register and execute a render loop. The engine can have more than one render function
  12461. * @param renderFunction defines the function to continuously execute
  12462. */
  12463. Engine.prototype.runRenderLoop = function (renderFunction) {
  12464. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12465. return;
  12466. }
  12467. this._activeRenderLoops.push(renderFunction);
  12468. if (!this._renderingQueueLaunched) {
  12469. this._renderingQueueLaunched = true;
  12470. this._bindedRenderFunction = this._renderLoop.bind(this);
  12471. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12472. }
  12473. };
  12474. /**
  12475. * Toggle full screen mode
  12476. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12477. * @param options defines an option object to be sent to the requestFullscreen function
  12478. */
  12479. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12480. if (this.isFullscreen) {
  12481. BABYLON.Tools.ExitFullscreen();
  12482. }
  12483. else {
  12484. this._pointerLockRequested = requestPointerLock;
  12485. if (this._renderingCanvas) {
  12486. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12487. }
  12488. }
  12489. };
  12490. /**
  12491. * Clear the current render buffer or the current render target (if any is set up)
  12492. * @param color defines the color to use
  12493. * @param backBuffer defines if the back buffer must be cleared
  12494. * @param depth defines if the depth buffer must be cleared
  12495. * @param stencil defines if the stencil buffer must be cleared
  12496. */
  12497. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12498. if (stencil === void 0) { stencil = false; }
  12499. this.applyStates();
  12500. var mode = 0;
  12501. if (backBuffer && color) {
  12502. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12503. mode |= this._gl.COLOR_BUFFER_BIT;
  12504. }
  12505. if (depth) {
  12506. this._gl.clearDepth(1.0);
  12507. mode |= this._gl.DEPTH_BUFFER_BIT;
  12508. }
  12509. if (stencil) {
  12510. this._gl.clearStencil(0);
  12511. mode |= this._gl.STENCIL_BUFFER_BIT;
  12512. }
  12513. this._gl.clear(mode);
  12514. };
  12515. /**
  12516. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12517. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12518. * @param y defines the y-coordinate of the corner of the clear rectangle
  12519. * @param width defines the width of the clear rectangle
  12520. * @param height defines the height of the clear rectangle
  12521. * @param clearColor defines the clear color
  12522. */
  12523. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12524. var gl = this._gl;
  12525. // Save state
  12526. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12527. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12528. // Change state
  12529. gl.enable(gl.SCISSOR_TEST);
  12530. gl.scissor(x, y, width, height);
  12531. // Clear
  12532. this.clear(clearColor, true, true, true);
  12533. // Restore state
  12534. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12535. if (curScissor === true) {
  12536. gl.enable(gl.SCISSOR_TEST);
  12537. }
  12538. else {
  12539. gl.disable(gl.SCISSOR_TEST);
  12540. }
  12541. };
  12542. /** @hidden */
  12543. Engine.prototype._viewport = function (x, y, width, height) {
  12544. if (x !== this._viewportCached.x ||
  12545. y !== this._viewportCached.y ||
  12546. width !== this._viewportCached.z ||
  12547. height !== this._viewportCached.w) {
  12548. this._viewportCached.x = x;
  12549. this._viewportCached.y = y;
  12550. this._viewportCached.z = width;
  12551. this._viewportCached.w = height;
  12552. this._gl.viewport(x, y, width, height);
  12553. }
  12554. };
  12555. /**
  12556. * Set the WebGL's viewport
  12557. * @param viewport defines the viewport element to be used
  12558. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12559. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12560. */
  12561. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12562. var width = requiredWidth || this.getRenderWidth();
  12563. var height = requiredHeight || this.getRenderHeight();
  12564. var x = viewport.x || 0;
  12565. var y = viewport.y || 0;
  12566. this._cachedViewport = viewport;
  12567. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12568. };
  12569. /**
  12570. * Directly set the WebGL Viewport
  12571. * @param x defines the x coordinate of the viewport (in screen space)
  12572. * @param y defines the y coordinate of the viewport (in screen space)
  12573. * @param width defines the width of the viewport (in screen space)
  12574. * @param height defines the height of the viewport (in screen space)
  12575. * @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
  12576. */
  12577. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12578. var currentViewport = this._cachedViewport;
  12579. this._cachedViewport = null;
  12580. this._viewport(x, y, width, height);
  12581. return currentViewport;
  12582. };
  12583. /**
  12584. * Begin a new frame
  12585. */
  12586. Engine.prototype.beginFrame = function () {
  12587. this.onBeginFrameObservable.notifyObservers(this);
  12588. this._measureFps();
  12589. };
  12590. /**
  12591. * Enf the current frame
  12592. */
  12593. Engine.prototype.endFrame = function () {
  12594. // Force a flush in case we are using a bad OS.
  12595. if (this._badOS) {
  12596. this.flushFramebuffer();
  12597. }
  12598. // Submit frame to the vr device, if enabled
  12599. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12600. // TODO: We should only submit the frame if we read frameData successfully.
  12601. this._vrDisplay.submitFrame();
  12602. }
  12603. this.onEndFrameObservable.notifyObservers(this);
  12604. };
  12605. /**
  12606. * Resize the view according to the canvas' size
  12607. */
  12608. Engine.prototype.resize = function () {
  12609. // We're not resizing the size of the canvas while in VR mode & presenting
  12610. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12611. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12612. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12613. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12614. }
  12615. };
  12616. /**
  12617. * Force a specific size of the canvas
  12618. * @param width defines the new canvas' width
  12619. * @param height defines the new canvas' height
  12620. */
  12621. Engine.prototype.setSize = function (width, height) {
  12622. if (!this._renderingCanvas) {
  12623. return;
  12624. }
  12625. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12626. return;
  12627. }
  12628. this._renderingCanvas.width = width;
  12629. this._renderingCanvas.height = height;
  12630. for (var index = 0; index < this.scenes.length; index++) {
  12631. var scene = this.scenes[index];
  12632. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12633. var cam = scene.cameras[camIndex];
  12634. cam._currentRenderId = 0;
  12635. }
  12636. }
  12637. if (this.onResizeObservable.hasObservers) {
  12638. this.onResizeObservable.notifyObservers(this);
  12639. }
  12640. };
  12641. // WebVR functions
  12642. /**
  12643. * Gets a boolean indicating if a webVR device was detected
  12644. * @returns true if a webVR device was detected
  12645. */
  12646. Engine.prototype.isVRDevicePresent = function () {
  12647. return !!this._vrDisplay;
  12648. };
  12649. /**
  12650. * Gets the current webVR device
  12651. * @returns the current webVR device (or null)
  12652. */
  12653. Engine.prototype.getVRDevice = function () {
  12654. return this._vrDisplay;
  12655. };
  12656. /**
  12657. * Initializes a webVR display and starts listening to display change events
  12658. * The onVRDisplayChangedObservable will be notified upon these changes
  12659. * @returns The onVRDisplayChangedObservable
  12660. */
  12661. Engine.prototype.initWebVR = function () {
  12662. this.initWebVRAsync();
  12663. return this.onVRDisplayChangedObservable;
  12664. };
  12665. /**
  12666. * Initializes a webVR display and starts listening to display change events
  12667. * The onVRDisplayChangedObservable will be notified upon these changes
  12668. * @returns A promise containing a VRDisplay and if vr is supported
  12669. */
  12670. Engine.prototype.initWebVRAsync = function () {
  12671. var _this = this;
  12672. var notifyObservers = function () {
  12673. var eventArgs = {
  12674. vrDisplay: _this._vrDisplay,
  12675. vrSupported: _this._vrSupported
  12676. };
  12677. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12678. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12679. };
  12680. if (!this._onVrDisplayConnect) {
  12681. this._onVrDisplayConnect = function (event) {
  12682. _this._vrDisplay = event.display;
  12683. notifyObservers();
  12684. };
  12685. this._onVrDisplayDisconnect = function () {
  12686. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12687. _this._vrDisplay = undefined;
  12688. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12689. notifyObservers();
  12690. };
  12691. this._onVrDisplayPresentChange = function () {
  12692. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12693. };
  12694. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12695. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12696. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12697. }
  12698. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12699. this._webVRInitPromise.then(notifyObservers);
  12700. return this._webVRInitPromise;
  12701. };
  12702. /**
  12703. * Call this function to switch to webVR mode
  12704. * Will do nothing if webVR is not supported or if there is no webVR device
  12705. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12706. */
  12707. Engine.prototype.enableVR = function () {
  12708. var _this = this;
  12709. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12710. var onResolved = function () {
  12711. _this.onVRRequestPresentComplete.notifyObservers(true);
  12712. _this._onVRFullScreenTriggered();
  12713. };
  12714. var onRejected = function () {
  12715. _this.onVRRequestPresentComplete.notifyObservers(false);
  12716. };
  12717. this.onVRRequestPresentStart.notifyObservers(this);
  12718. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12719. }
  12720. };
  12721. /**
  12722. * Call this function to leave webVR mode
  12723. * Will do nothing if webVR is not supported or if there is no webVR device
  12724. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12725. */
  12726. Engine.prototype.disableVR = function () {
  12727. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12728. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12729. }
  12730. };
  12731. Engine.prototype._getVRDisplaysAsync = function () {
  12732. var _this = this;
  12733. return new Promise(function (res, rej) {
  12734. if (navigator.getVRDisplays) {
  12735. navigator.getVRDisplays().then(function (devices) {
  12736. _this._vrSupported = true;
  12737. // note that devices may actually be an empty array. This is fine;
  12738. // we expect this._vrDisplay to be undefined in this case.
  12739. _this._vrDisplay = devices[0];
  12740. res({
  12741. vrDisplay: _this._vrDisplay,
  12742. vrSupported: _this._vrSupported
  12743. });
  12744. });
  12745. }
  12746. else {
  12747. _this._vrDisplay = undefined;
  12748. _this._vrSupported = false;
  12749. res({
  12750. vrDisplay: _this._vrDisplay,
  12751. vrSupported: _this._vrSupported
  12752. });
  12753. }
  12754. });
  12755. };
  12756. /**
  12757. * Binds the frame buffer to the specified texture.
  12758. * @param texture The texture to render to or null for the default canvas
  12759. * @param faceIndex The face of the texture to render to in case of cube texture
  12760. * @param requiredWidth The width of the target to render to
  12761. * @param requiredHeight The height of the target to render to
  12762. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12763. * @param depthStencilTexture The depth stencil texture to use to render
  12764. * @param lodLevel defines le lod level to bind to the frame buffer
  12765. */
  12766. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12767. if (lodLevel === void 0) { lodLevel = 0; }
  12768. if (this._currentRenderTarget) {
  12769. this.unBindFramebuffer(this._currentRenderTarget);
  12770. }
  12771. this._currentRenderTarget = texture;
  12772. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12773. var gl = this._gl;
  12774. if (texture.isCube) {
  12775. if (faceIndex === undefined) {
  12776. faceIndex = 0;
  12777. }
  12778. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12779. if (depthStencilTexture) {
  12780. if (depthStencilTexture._generateStencilBuffer) {
  12781. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12782. }
  12783. else {
  12784. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12785. }
  12786. }
  12787. }
  12788. if (this._cachedViewport && !forceFullscreenViewport) {
  12789. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12790. }
  12791. else {
  12792. if (!requiredWidth) {
  12793. requiredWidth = texture.width;
  12794. if (lodLevel) {
  12795. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12796. }
  12797. }
  12798. if (!requiredHeight) {
  12799. requiredHeight = texture.height;
  12800. if (lodLevel) {
  12801. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12802. }
  12803. }
  12804. this._viewport(0, 0, requiredWidth, requiredHeight);
  12805. }
  12806. this.wipeCaches();
  12807. };
  12808. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12809. if (this._currentFramebuffer !== framebuffer) {
  12810. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12811. this._currentFramebuffer = framebuffer;
  12812. }
  12813. };
  12814. /**
  12815. * Unbind the current render target texture from the webGL context
  12816. * @param texture defines the render target texture to unbind
  12817. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12818. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12819. */
  12820. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12821. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12822. this._currentRenderTarget = null;
  12823. // If MSAA, we need to bitblt back to main texture
  12824. var gl = this._gl;
  12825. if (texture._MSAAFramebuffer) {
  12826. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12827. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12828. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12829. }
  12830. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12831. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12832. gl.generateMipmap(gl.TEXTURE_2D);
  12833. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12834. }
  12835. if (onBeforeUnbind) {
  12836. if (texture._MSAAFramebuffer) {
  12837. // Bind the correct framebuffer
  12838. this.bindUnboundFramebuffer(texture._framebuffer);
  12839. }
  12840. onBeforeUnbind();
  12841. }
  12842. this.bindUnboundFramebuffer(null);
  12843. };
  12844. /**
  12845. * Unbind a list of render target textures from the webGL context
  12846. * This is used only when drawBuffer extension or webGL2 are active
  12847. * @param textures defines the render target textures to unbind
  12848. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12849. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12850. */
  12851. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12852. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12853. this._currentRenderTarget = null;
  12854. // If MSAA, we need to bitblt back to main texture
  12855. var gl = this._gl;
  12856. if (textures[0]._MSAAFramebuffer) {
  12857. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12858. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12859. var attachments = textures[0]._attachments;
  12860. if (!attachments) {
  12861. attachments = new Array(textures.length);
  12862. textures[0]._attachments = attachments;
  12863. }
  12864. for (var i = 0; i < textures.length; i++) {
  12865. var texture = textures[i];
  12866. for (var j = 0; j < attachments.length; j++) {
  12867. attachments[j] = gl.NONE;
  12868. }
  12869. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12870. gl.readBuffer(attachments[i]);
  12871. gl.drawBuffers(attachments);
  12872. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12873. }
  12874. for (var i = 0; i < attachments.length; i++) {
  12875. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12876. }
  12877. gl.drawBuffers(attachments);
  12878. }
  12879. for (var i = 0; i < textures.length; i++) {
  12880. var texture = textures[i];
  12881. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12882. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12883. gl.generateMipmap(gl.TEXTURE_2D);
  12884. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12885. }
  12886. }
  12887. if (onBeforeUnbind) {
  12888. if (textures[0]._MSAAFramebuffer) {
  12889. // Bind the correct framebuffer
  12890. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12891. }
  12892. onBeforeUnbind();
  12893. }
  12894. this.bindUnboundFramebuffer(null);
  12895. };
  12896. /**
  12897. * Force the mipmap generation for the given render target texture
  12898. * @param texture defines the render target texture to use
  12899. */
  12900. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12901. if (texture.generateMipMaps) {
  12902. var gl = this._gl;
  12903. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12904. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12905. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12906. }
  12907. };
  12908. /**
  12909. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12910. */
  12911. Engine.prototype.flushFramebuffer = function () {
  12912. this._gl.flush();
  12913. };
  12914. /**
  12915. * Unbind the current render target and bind the default framebuffer
  12916. */
  12917. Engine.prototype.restoreDefaultFramebuffer = function () {
  12918. if (this._currentRenderTarget) {
  12919. this.unBindFramebuffer(this._currentRenderTarget);
  12920. }
  12921. else {
  12922. this.bindUnboundFramebuffer(null);
  12923. }
  12924. if (this._cachedViewport) {
  12925. this.setViewport(this._cachedViewport);
  12926. }
  12927. this.wipeCaches();
  12928. };
  12929. // UBOs
  12930. /**
  12931. * Create an uniform buffer
  12932. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12933. * @param elements defines the content of the uniform buffer
  12934. * @returns the webGL uniform buffer
  12935. */
  12936. Engine.prototype.createUniformBuffer = function (elements) {
  12937. var ubo = this._gl.createBuffer();
  12938. if (!ubo) {
  12939. throw new Error("Unable to create uniform buffer");
  12940. }
  12941. this.bindUniformBuffer(ubo);
  12942. if (elements instanceof Float32Array) {
  12943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12944. }
  12945. else {
  12946. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12947. }
  12948. this.bindUniformBuffer(null);
  12949. ubo.references = 1;
  12950. return ubo;
  12951. };
  12952. /**
  12953. * Create a dynamic uniform buffer
  12954. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12955. * @param elements defines the content of the uniform buffer
  12956. * @returns the webGL uniform buffer
  12957. */
  12958. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12959. var ubo = this._gl.createBuffer();
  12960. if (!ubo) {
  12961. throw new Error("Unable to create dynamic uniform buffer");
  12962. }
  12963. this.bindUniformBuffer(ubo);
  12964. if (elements instanceof Float32Array) {
  12965. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12966. }
  12967. else {
  12968. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12969. }
  12970. this.bindUniformBuffer(null);
  12971. ubo.references = 1;
  12972. return ubo;
  12973. };
  12974. /**
  12975. * Update an existing uniform buffer
  12976. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12977. * @param uniformBuffer defines the target uniform buffer
  12978. * @param elements defines the content to update
  12979. * @param offset defines the offset in the uniform buffer where update should start
  12980. * @param count defines the size of the data to update
  12981. */
  12982. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12983. this.bindUniformBuffer(uniformBuffer);
  12984. if (offset === undefined) {
  12985. offset = 0;
  12986. }
  12987. if (count === undefined) {
  12988. if (elements instanceof Float32Array) {
  12989. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12990. }
  12991. else {
  12992. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12993. }
  12994. }
  12995. else {
  12996. if (elements instanceof Float32Array) {
  12997. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12998. }
  12999. else {
  13000. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13001. }
  13002. }
  13003. this.bindUniformBuffer(null);
  13004. };
  13005. // VBOs
  13006. Engine.prototype._resetVertexBufferBinding = function () {
  13007. this.bindArrayBuffer(null);
  13008. this._cachedVertexBuffers = null;
  13009. };
  13010. /**
  13011. * Creates a vertex buffer
  13012. * @param data the data for the vertex buffer
  13013. * @returns the new WebGL static buffer
  13014. */
  13015. Engine.prototype.createVertexBuffer = function (data) {
  13016. var vbo = this._gl.createBuffer();
  13017. if (!vbo) {
  13018. throw new Error("Unable to create vertex buffer");
  13019. }
  13020. this.bindArrayBuffer(vbo);
  13021. if (data instanceof Array) {
  13022. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13023. }
  13024. else {
  13025. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13026. }
  13027. this._resetVertexBufferBinding();
  13028. vbo.references = 1;
  13029. return vbo;
  13030. };
  13031. /**
  13032. * Creates a dynamic vertex buffer
  13033. * @param data the data for the dynamic vertex buffer
  13034. * @returns the new WebGL dynamic buffer
  13035. */
  13036. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13037. var vbo = this._gl.createBuffer();
  13038. if (!vbo) {
  13039. throw new Error("Unable to create dynamic vertex buffer");
  13040. }
  13041. this.bindArrayBuffer(vbo);
  13042. if (data instanceof Array) {
  13043. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13044. }
  13045. else {
  13046. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13047. }
  13048. this._resetVertexBufferBinding();
  13049. vbo.references = 1;
  13050. return vbo;
  13051. };
  13052. /**
  13053. * Update a dynamic index buffer
  13054. * @param indexBuffer defines the target index buffer
  13055. * @param indices defines the data to update
  13056. * @param offset defines the offset in the target index buffer where update should start
  13057. */
  13058. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13059. if (offset === void 0) { offset = 0; }
  13060. // Force cache update
  13061. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13062. this.bindIndexBuffer(indexBuffer);
  13063. var arrayBuffer;
  13064. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13065. arrayBuffer = indices;
  13066. }
  13067. else {
  13068. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13069. }
  13070. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13071. this._resetIndexBufferBinding();
  13072. };
  13073. /**
  13074. * Updates a dynamic vertex buffer.
  13075. * @param vertexBuffer the vertex buffer to update
  13076. * @param data the data used to update the vertex buffer
  13077. * @param byteOffset the byte offset of the data
  13078. * @param byteLength the byte length of the data
  13079. */
  13080. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13081. this.bindArrayBuffer(vertexBuffer);
  13082. if (byteOffset === undefined) {
  13083. byteOffset = 0;
  13084. }
  13085. if (byteLength === undefined) {
  13086. if (data instanceof Array) {
  13087. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13088. }
  13089. else {
  13090. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13091. }
  13092. }
  13093. else {
  13094. if (data instanceof Array) {
  13095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13096. }
  13097. else {
  13098. if (data instanceof ArrayBuffer) {
  13099. data = new Uint8Array(data, byteOffset, byteLength);
  13100. }
  13101. else {
  13102. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13103. }
  13104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13105. }
  13106. }
  13107. this._resetVertexBufferBinding();
  13108. };
  13109. Engine.prototype._resetIndexBufferBinding = function () {
  13110. this.bindIndexBuffer(null);
  13111. this._cachedIndexBuffer = null;
  13112. };
  13113. /**
  13114. * Creates a new index buffer
  13115. * @param indices defines the content of the index buffer
  13116. * @param updatable defines if the index buffer must be updatable
  13117. * @returns a new webGL buffer
  13118. */
  13119. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13120. var vbo = this._gl.createBuffer();
  13121. if (!vbo) {
  13122. throw new Error("Unable to create index buffer");
  13123. }
  13124. this.bindIndexBuffer(vbo);
  13125. // Check for 32 bits indices
  13126. var arrayBuffer;
  13127. var need32Bits = false;
  13128. if (indices instanceof Uint16Array) {
  13129. arrayBuffer = indices;
  13130. }
  13131. else {
  13132. //check 32 bit support
  13133. if (this._caps.uintIndices) {
  13134. if (indices instanceof Uint32Array) {
  13135. arrayBuffer = indices;
  13136. need32Bits = true;
  13137. }
  13138. else {
  13139. //number[] or Int32Array, check if 32 bit is necessary
  13140. for (var index = 0; index < indices.length; index++) {
  13141. if (indices[index] > 65535) {
  13142. need32Bits = true;
  13143. break;
  13144. }
  13145. }
  13146. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13147. }
  13148. }
  13149. else {
  13150. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13151. arrayBuffer = new Uint16Array(indices);
  13152. }
  13153. }
  13154. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13155. this._resetIndexBufferBinding();
  13156. vbo.references = 1;
  13157. vbo.is32Bits = need32Bits;
  13158. return vbo;
  13159. };
  13160. /**
  13161. * Bind a webGL buffer to the webGL context
  13162. * @param buffer defines the buffer to bind
  13163. */
  13164. Engine.prototype.bindArrayBuffer = function (buffer) {
  13165. if (!this._vaoRecordInProgress) {
  13166. this._unbindVertexArrayObject();
  13167. }
  13168. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13169. };
  13170. /**
  13171. * Bind an uniform buffer to the current webGL context
  13172. * @param buffer defines the buffer to bind
  13173. */
  13174. Engine.prototype.bindUniformBuffer = function (buffer) {
  13175. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13176. };
  13177. /**
  13178. * Bind a buffer to the current webGL context at a given location
  13179. * @param buffer defines the buffer to bind
  13180. * @param location defines the index where to bind the buffer
  13181. */
  13182. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13183. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13184. };
  13185. /**
  13186. * Bind a specific block at a given index in a specific shader program
  13187. * @param shaderProgram defines the shader program
  13188. * @param blockName defines the block name
  13189. * @param index defines the index where to bind the block
  13190. */
  13191. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13192. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13193. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13194. };
  13195. ;
  13196. Engine.prototype.bindIndexBuffer = function (buffer) {
  13197. if (!this._vaoRecordInProgress) {
  13198. this._unbindVertexArrayObject();
  13199. }
  13200. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13201. };
  13202. Engine.prototype.bindBuffer = function (buffer, target) {
  13203. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13204. this._gl.bindBuffer(target, buffer);
  13205. this._currentBoundBuffer[target] = buffer;
  13206. }
  13207. };
  13208. /**
  13209. * update the bound buffer with the given data
  13210. * @param data defines the data to update
  13211. */
  13212. Engine.prototype.updateArrayBuffer = function (data) {
  13213. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13214. };
  13215. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13216. var pointer = this._currentBufferPointers[indx];
  13217. var changed = false;
  13218. if (!pointer.active) {
  13219. changed = true;
  13220. pointer.active = true;
  13221. pointer.index = indx;
  13222. pointer.size = size;
  13223. pointer.type = type;
  13224. pointer.normalized = normalized;
  13225. pointer.stride = stride;
  13226. pointer.offset = offset;
  13227. pointer.buffer = buffer;
  13228. }
  13229. else {
  13230. if (pointer.buffer !== buffer) {
  13231. pointer.buffer = buffer;
  13232. changed = true;
  13233. }
  13234. if (pointer.size !== size) {
  13235. pointer.size = size;
  13236. changed = true;
  13237. }
  13238. if (pointer.type !== type) {
  13239. pointer.type = type;
  13240. changed = true;
  13241. }
  13242. if (pointer.normalized !== normalized) {
  13243. pointer.normalized = normalized;
  13244. changed = true;
  13245. }
  13246. if (pointer.stride !== stride) {
  13247. pointer.stride = stride;
  13248. changed = true;
  13249. }
  13250. if (pointer.offset !== offset) {
  13251. pointer.offset = offset;
  13252. changed = true;
  13253. }
  13254. }
  13255. if (changed || this._vaoRecordInProgress) {
  13256. this.bindArrayBuffer(buffer);
  13257. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13258. }
  13259. };
  13260. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13261. if (indexBuffer == null) {
  13262. return;
  13263. }
  13264. if (this._cachedIndexBuffer !== indexBuffer) {
  13265. this._cachedIndexBuffer = indexBuffer;
  13266. this.bindIndexBuffer(indexBuffer);
  13267. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13268. }
  13269. };
  13270. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13271. var attributes = effect.getAttributesNames();
  13272. if (!this._vaoRecordInProgress) {
  13273. this._unbindVertexArrayObject();
  13274. }
  13275. this.unbindAllAttributes();
  13276. for (var index = 0; index < attributes.length; index++) {
  13277. var order = effect.getAttributeLocation(index);
  13278. if (order >= 0) {
  13279. var vertexBuffer = vertexBuffers[attributes[index]];
  13280. if (!vertexBuffer) {
  13281. continue;
  13282. }
  13283. this._gl.enableVertexAttribArray(order);
  13284. if (!this._vaoRecordInProgress) {
  13285. this._vertexAttribArraysEnabled[order] = true;
  13286. }
  13287. var buffer = vertexBuffer.getBuffer();
  13288. if (buffer) {
  13289. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13290. if (vertexBuffer.getIsInstanced()) {
  13291. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13292. if (!this._vaoRecordInProgress) {
  13293. this._currentInstanceLocations.push(order);
  13294. this._currentInstanceBuffers.push(buffer);
  13295. }
  13296. }
  13297. }
  13298. }
  13299. }
  13300. };
  13301. /**
  13302. * Records a vertex array object
  13303. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13304. * @param vertexBuffers defines the list of vertex buffers to store
  13305. * @param indexBuffer defines the index buffer to store
  13306. * @param effect defines the effect to store
  13307. * @returns the new vertex array object
  13308. */
  13309. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13310. var vao = this._gl.createVertexArray();
  13311. this._vaoRecordInProgress = true;
  13312. this._gl.bindVertexArray(vao);
  13313. this._mustWipeVertexAttributes = true;
  13314. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13315. this.bindIndexBuffer(indexBuffer);
  13316. this._vaoRecordInProgress = false;
  13317. this._gl.bindVertexArray(null);
  13318. return vao;
  13319. };
  13320. /**
  13321. * Bind a specific vertex array object
  13322. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13323. * @param vertexArrayObject defines the vertex array object to bind
  13324. * @param indexBuffer defines the index buffer to bind
  13325. */
  13326. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13327. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13328. this._cachedVertexArrayObject = vertexArrayObject;
  13329. this._gl.bindVertexArray(vertexArrayObject);
  13330. this._cachedVertexBuffers = null;
  13331. this._cachedIndexBuffer = null;
  13332. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13333. this._mustWipeVertexAttributes = true;
  13334. }
  13335. };
  13336. /**
  13337. * Bind webGl buffers directly to the webGL context
  13338. * @param vertexBuffer defines the vertex buffer to bind
  13339. * @param indexBuffer defines the index buffer to bind
  13340. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13341. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13342. * @param effect defines the effect associated with the vertex buffer
  13343. */
  13344. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13345. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13346. this._cachedVertexBuffers = vertexBuffer;
  13347. this._cachedEffectForVertexBuffers = effect;
  13348. var attributesCount = effect.getAttributesCount();
  13349. this._unbindVertexArrayObject();
  13350. this.unbindAllAttributes();
  13351. var offset = 0;
  13352. for (var index = 0; index < attributesCount; index++) {
  13353. if (index < vertexDeclaration.length) {
  13354. var order = effect.getAttributeLocation(index);
  13355. if (order >= 0) {
  13356. this._gl.enableVertexAttribArray(order);
  13357. this._vertexAttribArraysEnabled[order] = true;
  13358. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13359. }
  13360. offset += vertexDeclaration[index] * 4;
  13361. }
  13362. }
  13363. }
  13364. this._bindIndexBufferWithCache(indexBuffer);
  13365. };
  13366. Engine.prototype._unbindVertexArrayObject = function () {
  13367. if (!this._cachedVertexArrayObject) {
  13368. return;
  13369. }
  13370. this._cachedVertexArrayObject = null;
  13371. this._gl.bindVertexArray(null);
  13372. };
  13373. /**
  13374. * Bind a list of vertex buffers to the webGL context
  13375. * @param vertexBuffers defines the list of vertex buffers to bind
  13376. * @param indexBuffer defines the index buffer to bind
  13377. * @param effect defines the effect associated with the vertex buffers
  13378. */
  13379. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13380. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13381. this._cachedVertexBuffers = vertexBuffers;
  13382. this._cachedEffectForVertexBuffers = effect;
  13383. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13384. }
  13385. this._bindIndexBufferWithCache(indexBuffer);
  13386. };
  13387. /**
  13388. * Unbind all instance attributes
  13389. */
  13390. Engine.prototype.unbindInstanceAttributes = function () {
  13391. var boundBuffer;
  13392. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13393. var instancesBuffer = this._currentInstanceBuffers[i];
  13394. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13395. boundBuffer = instancesBuffer;
  13396. this.bindArrayBuffer(instancesBuffer);
  13397. }
  13398. var offsetLocation = this._currentInstanceLocations[i];
  13399. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13400. }
  13401. this._currentInstanceBuffers.length = 0;
  13402. this._currentInstanceLocations.length = 0;
  13403. };
  13404. /**
  13405. * Release and free the memory of a vertex array object
  13406. * @param vao defines the vertex array object to delete
  13407. */
  13408. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13409. this._gl.deleteVertexArray(vao);
  13410. };
  13411. /** @hidden */
  13412. Engine.prototype._releaseBuffer = function (buffer) {
  13413. buffer.references--;
  13414. if (buffer.references === 0) {
  13415. this._gl.deleteBuffer(buffer);
  13416. return true;
  13417. }
  13418. return false;
  13419. };
  13420. /**
  13421. * Creates a webGL buffer to use with instanciation
  13422. * @param capacity defines the size of the buffer
  13423. * @returns the webGL buffer
  13424. */
  13425. Engine.prototype.createInstancesBuffer = function (capacity) {
  13426. var buffer = this._gl.createBuffer();
  13427. if (!buffer) {
  13428. throw new Error("Unable to create instance buffer");
  13429. }
  13430. buffer.capacity = capacity;
  13431. this.bindArrayBuffer(buffer);
  13432. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13433. return buffer;
  13434. };
  13435. /**
  13436. * Delete a webGL buffer used with instanciation
  13437. * @param buffer defines the webGL buffer to delete
  13438. */
  13439. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13440. this._gl.deleteBuffer(buffer);
  13441. };
  13442. /**
  13443. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13444. * @param instancesBuffer defines the webGL buffer to update and bind
  13445. * @param data defines the data to store in the buffer
  13446. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13447. */
  13448. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13449. this.bindArrayBuffer(instancesBuffer);
  13450. if (data) {
  13451. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13452. }
  13453. if (offsetLocations[0].index !== undefined) {
  13454. var stride = 0;
  13455. for (var i = 0; i < offsetLocations.length; i++) {
  13456. var ai = offsetLocations[i];
  13457. stride += ai.attributeSize * 4;
  13458. }
  13459. for (var i = 0; i < offsetLocations.length; i++) {
  13460. var ai = offsetLocations[i];
  13461. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13462. this._gl.enableVertexAttribArray(ai.index);
  13463. this._vertexAttribArraysEnabled[ai.index] = true;
  13464. }
  13465. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13466. this._gl.vertexAttribDivisor(ai.index, 1);
  13467. this._currentInstanceLocations.push(ai.index);
  13468. this._currentInstanceBuffers.push(instancesBuffer);
  13469. }
  13470. }
  13471. else {
  13472. for (var index = 0; index < 4; index++) {
  13473. var offsetLocation = offsetLocations[index];
  13474. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13475. this._gl.enableVertexAttribArray(offsetLocation);
  13476. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13477. }
  13478. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13479. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13480. this._currentInstanceLocations.push(offsetLocation);
  13481. this._currentInstanceBuffers.push(instancesBuffer);
  13482. }
  13483. }
  13484. };
  13485. /**
  13486. * Apply all cached states (depth, culling, stencil and alpha)
  13487. */
  13488. Engine.prototype.applyStates = function () {
  13489. this._depthCullingState.apply(this._gl);
  13490. this._stencilState.apply(this._gl);
  13491. this._alphaState.apply(this._gl);
  13492. };
  13493. /**
  13494. * Send a draw order
  13495. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13496. * @param indexStart defines the starting index
  13497. * @param indexCount defines the number of index to draw
  13498. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13499. */
  13500. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13501. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13502. };
  13503. /**
  13504. * Draw a list of points
  13505. * @param verticesStart defines the index of first vertex to draw
  13506. * @param verticesCount defines the count of vertices to draw
  13507. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13508. */
  13509. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13510. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13511. };
  13512. /**
  13513. * Draw a list of unindexed primitives
  13514. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13515. * @param verticesStart defines the index of first vertex to draw
  13516. * @param verticesCount defines the count of vertices to draw
  13517. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13518. */
  13519. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13520. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13521. };
  13522. /**
  13523. * Draw a list of indexed primitives
  13524. * @param fillMode defines the primitive to use
  13525. * @param indexStart defines the starting index
  13526. * @param indexCount defines the number of index to draw
  13527. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13528. */
  13529. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13530. // Apply states
  13531. this.applyStates();
  13532. this._drawCalls.addCount(1, false);
  13533. // Render
  13534. var drawMode = this._drawMode(fillMode);
  13535. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13536. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13537. if (instancesCount) {
  13538. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13539. }
  13540. else {
  13541. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13542. }
  13543. };
  13544. /**
  13545. * Draw a list of unindexed primitives
  13546. * @param fillMode defines the primitive to use
  13547. * @param verticesStart defines the index of first vertex to draw
  13548. * @param verticesCount defines the count of vertices to draw
  13549. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13550. */
  13551. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13552. // Apply states
  13553. this.applyStates();
  13554. this._drawCalls.addCount(1, false);
  13555. var drawMode = this._drawMode(fillMode);
  13556. if (instancesCount) {
  13557. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13558. }
  13559. else {
  13560. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13561. }
  13562. };
  13563. Engine.prototype._drawMode = function (fillMode) {
  13564. switch (fillMode) {
  13565. // Triangle views
  13566. case BABYLON.Material.TriangleFillMode:
  13567. return this._gl.TRIANGLES;
  13568. case BABYLON.Material.PointFillMode:
  13569. return this._gl.POINTS;
  13570. case BABYLON.Material.WireFrameFillMode:
  13571. return this._gl.LINES;
  13572. // Draw modes
  13573. case BABYLON.Material.PointListDrawMode:
  13574. return this._gl.POINTS;
  13575. case BABYLON.Material.LineListDrawMode:
  13576. return this._gl.LINES;
  13577. case BABYLON.Material.LineLoopDrawMode:
  13578. return this._gl.LINE_LOOP;
  13579. case BABYLON.Material.LineStripDrawMode:
  13580. return this._gl.LINE_STRIP;
  13581. case BABYLON.Material.TriangleStripDrawMode:
  13582. return this._gl.TRIANGLE_STRIP;
  13583. case BABYLON.Material.TriangleFanDrawMode:
  13584. return this._gl.TRIANGLE_FAN;
  13585. default:
  13586. return this._gl.TRIANGLES;
  13587. }
  13588. };
  13589. // Shaders
  13590. /** @hidden */
  13591. Engine.prototype._releaseEffect = function (effect) {
  13592. if (this._compiledEffects[effect._key]) {
  13593. delete this._compiledEffects[effect._key];
  13594. this._deleteProgram(effect.getProgram());
  13595. }
  13596. };
  13597. /** @hidden */
  13598. Engine.prototype._deleteProgram = function (program) {
  13599. if (program) {
  13600. program.__SPECTOR_rebuildProgram = null;
  13601. if (program.transformFeedback) {
  13602. this.deleteTransformFeedback(program.transformFeedback);
  13603. program.transformFeedback = null;
  13604. }
  13605. this._gl.deleteProgram(program);
  13606. }
  13607. };
  13608. /**
  13609. * Create a new effect (used to store vertex/fragment shaders)
  13610. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13611. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13612. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13613. * @param samplers defines an array of string used to represent textures
  13614. * @param defines defines the string containing the defines to use to compile the shaders
  13615. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13616. * @param onCompiled defines a function to call when the effect creation is successful
  13617. * @param onError defines a function to call when the effect creation has failed
  13618. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13619. * @returns the new Effect
  13620. */
  13621. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13622. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13623. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13624. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13625. if (this._compiledEffects[name]) {
  13626. var compiledEffect = this._compiledEffects[name];
  13627. if (onCompiled && compiledEffect.isReady()) {
  13628. onCompiled(compiledEffect);
  13629. }
  13630. return compiledEffect;
  13631. }
  13632. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13633. effect._key = name;
  13634. this._compiledEffects[name] = effect;
  13635. return effect;
  13636. };
  13637. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13638. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13639. };
  13640. ;
  13641. Engine.prototype._compileRawShader = function (source, type) {
  13642. var gl = this._gl;
  13643. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13644. gl.shaderSource(shader, source);
  13645. gl.compileShader(shader);
  13646. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13647. var log = gl.getShaderInfoLog(shader);
  13648. if (log) {
  13649. throw new Error(log);
  13650. }
  13651. }
  13652. if (!shader) {
  13653. throw new Error("Something went wrong while compile the shader.");
  13654. }
  13655. return shader;
  13656. };
  13657. ;
  13658. /**
  13659. * Directly creates a webGL program
  13660. * @param vertexCode defines the vertex shader code to use
  13661. * @param fragmentCode defines the fragment shader code to use
  13662. * @param context defines the webGL context to use (if not set, the current one will be used)
  13663. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13664. * @returns the new webGL program
  13665. */
  13666. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13667. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13668. context = context || this._gl;
  13669. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13670. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13671. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13672. };
  13673. /**
  13674. * Creates a webGL program
  13675. * @param vertexCode defines the vertex shader code to use
  13676. * @param fragmentCode defines the fragment shader code to use
  13677. * @param defines defines the string containing the defines to use to compile the shaders
  13678. * @param context defines the webGL context to use (if not set, the current one will be used)
  13679. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13680. * @returns the new webGL program
  13681. */
  13682. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13683. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13684. context = context || this._gl;
  13685. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13686. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13687. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13688. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13689. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13690. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13691. return program;
  13692. };
  13693. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13694. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13695. var shaderProgram = context.createProgram();
  13696. if (!shaderProgram) {
  13697. throw new Error("Unable to create program");
  13698. }
  13699. context.attachShader(shaderProgram, vertexShader);
  13700. context.attachShader(shaderProgram, fragmentShader);
  13701. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13702. var transformFeedback = this.createTransformFeedback();
  13703. this.bindTransformFeedback(transformFeedback);
  13704. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13705. shaderProgram.transformFeedback = transformFeedback;
  13706. }
  13707. context.linkProgram(shaderProgram);
  13708. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13709. this.bindTransformFeedback(null);
  13710. }
  13711. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13712. if (!linked) {
  13713. var error = context.getProgramInfoLog(shaderProgram);
  13714. if (error) {
  13715. throw new Error(error);
  13716. }
  13717. }
  13718. if (this.validateShaderPrograms) {
  13719. context.validateProgram(shaderProgram);
  13720. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13721. if (!validated) {
  13722. var error = context.getProgramInfoLog(shaderProgram);
  13723. if (error) {
  13724. throw new Error(error);
  13725. }
  13726. }
  13727. }
  13728. context.deleteShader(vertexShader);
  13729. context.deleteShader(fragmentShader);
  13730. return shaderProgram;
  13731. };
  13732. /**
  13733. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13734. * @param shaderProgram defines the webGL program to use
  13735. * @param uniformsNames defines the list of uniform names
  13736. * @returns an array of webGL uniform locations
  13737. */
  13738. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13739. var results = new Array();
  13740. for (var index = 0; index < uniformsNames.length; index++) {
  13741. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13742. }
  13743. return results;
  13744. };
  13745. /**
  13746. * Gets the lsit of active attributes for a given webGL program
  13747. * @param shaderProgram defines the webGL program to use
  13748. * @param attributesNames defines the list of attribute names to get
  13749. * @returns an array of indices indicating the offset of each attribute
  13750. */
  13751. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13752. var results = [];
  13753. for (var index = 0; index < attributesNames.length; index++) {
  13754. try {
  13755. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13756. }
  13757. catch (e) {
  13758. results.push(-1);
  13759. }
  13760. }
  13761. return results;
  13762. };
  13763. /**
  13764. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13765. * @param effect defines the effect to activate
  13766. */
  13767. Engine.prototype.enableEffect = function (effect) {
  13768. if (!effect) {
  13769. return;
  13770. }
  13771. // Use program
  13772. this.bindSamplers(effect);
  13773. this._currentEffect = effect;
  13774. if (effect.onBind) {
  13775. effect.onBind(effect);
  13776. }
  13777. effect.onBindObservable.notifyObservers(effect);
  13778. };
  13779. /**
  13780. * Set the value of an uniform to an array of int32
  13781. * @param uniform defines the webGL uniform location where to store the value
  13782. * @param array defines the array of int32 to store
  13783. */
  13784. Engine.prototype.setIntArray = function (uniform, array) {
  13785. if (!uniform)
  13786. return;
  13787. this._gl.uniform1iv(uniform, array);
  13788. };
  13789. /**
  13790. * Set the value of an uniform to an array of int32 (stored as vec2)
  13791. * @param uniform defines the webGL uniform location where to store the value
  13792. * @param array defines the array of int32 to store
  13793. */
  13794. Engine.prototype.setIntArray2 = function (uniform, array) {
  13795. if (!uniform || array.length % 2 !== 0)
  13796. return;
  13797. this._gl.uniform2iv(uniform, array);
  13798. };
  13799. /**
  13800. * Set the value of an uniform to an array of int32 (stored as vec3)
  13801. * @param uniform defines the webGL uniform location where to store the value
  13802. * @param array defines the array of int32 to store
  13803. */
  13804. Engine.prototype.setIntArray3 = function (uniform, array) {
  13805. if (!uniform || array.length % 3 !== 0)
  13806. return;
  13807. this._gl.uniform3iv(uniform, array);
  13808. };
  13809. /**
  13810. * Set the value of an uniform to an array of int32 (stored as vec4)
  13811. * @param uniform defines the webGL uniform location where to store the value
  13812. * @param array defines the array of int32 to store
  13813. */
  13814. Engine.prototype.setIntArray4 = function (uniform, array) {
  13815. if (!uniform || array.length % 4 !== 0)
  13816. return;
  13817. this._gl.uniform4iv(uniform, array);
  13818. };
  13819. /**
  13820. * Set the value of an uniform to an array of float32
  13821. * @param uniform defines the webGL uniform location where to store the value
  13822. * @param array defines the array of float32 to store
  13823. */
  13824. Engine.prototype.setFloatArray = function (uniform, array) {
  13825. if (!uniform)
  13826. return;
  13827. this._gl.uniform1fv(uniform, array);
  13828. };
  13829. /**
  13830. * Set the value of an uniform to an array of float32 (stored as vec2)
  13831. * @param uniform defines the webGL uniform location where to store the value
  13832. * @param array defines the array of float32 to store
  13833. */
  13834. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13835. if (!uniform || array.length % 2 !== 0)
  13836. return;
  13837. this._gl.uniform2fv(uniform, array);
  13838. };
  13839. /**
  13840. * Set the value of an uniform to an array of float32 (stored as vec3)
  13841. * @param uniform defines the webGL uniform location where to store the value
  13842. * @param array defines the array of float32 to store
  13843. */
  13844. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13845. if (!uniform || array.length % 3 !== 0)
  13846. return;
  13847. this._gl.uniform3fv(uniform, array);
  13848. };
  13849. /**
  13850. * Set the value of an uniform to an array of float32 (stored as vec4)
  13851. * @param uniform defines the webGL uniform location where to store the value
  13852. * @param array defines the array of float32 to store
  13853. */
  13854. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13855. if (!uniform || array.length % 4 !== 0)
  13856. return;
  13857. this._gl.uniform4fv(uniform, array);
  13858. };
  13859. /**
  13860. * Set the value of an uniform to an array of number
  13861. * @param uniform defines the webGL uniform location where to store the value
  13862. * @param array defines the array of number to store
  13863. */
  13864. Engine.prototype.setArray = function (uniform, array) {
  13865. if (!uniform)
  13866. return;
  13867. this._gl.uniform1fv(uniform, array);
  13868. };
  13869. /**
  13870. * Set the value of an uniform to an array of number (stored as vec2)
  13871. * @param uniform defines the webGL uniform location where to store the value
  13872. * @param array defines the array of number to store
  13873. */
  13874. Engine.prototype.setArray2 = function (uniform, array) {
  13875. if (!uniform || array.length % 2 !== 0)
  13876. return;
  13877. this._gl.uniform2fv(uniform, array);
  13878. };
  13879. /**
  13880. * Set the value of an uniform to an array of number (stored as vec3)
  13881. * @param uniform defines the webGL uniform location where to store the value
  13882. * @param array defines the array of number to store
  13883. */
  13884. Engine.prototype.setArray3 = function (uniform, array) {
  13885. if (!uniform || array.length % 3 !== 0)
  13886. return;
  13887. this._gl.uniform3fv(uniform, array);
  13888. };
  13889. /**
  13890. * Set the value of an uniform to an array of number (stored as vec4)
  13891. * @param uniform defines the webGL uniform location where to store the value
  13892. * @param array defines the array of number to store
  13893. */
  13894. Engine.prototype.setArray4 = function (uniform, array) {
  13895. if (!uniform || array.length % 4 !== 0)
  13896. return;
  13897. this._gl.uniform4fv(uniform, array);
  13898. };
  13899. /**
  13900. * Set the value of an uniform to an array of float32 (stored as matrices)
  13901. * @param uniform defines the webGL uniform location where to store the value
  13902. * @param matrices defines the array of float32 to store
  13903. */
  13904. Engine.prototype.setMatrices = function (uniform, matrices) {
  13905. if (!uniform)
  13906. return;
  13907. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13908. };
  13909. /**
  13910. * Set the value of an uniform to a matrix
  13911. * @param uniform defines the webGL uniform location where to store the value
  13912. * @param matrix defines the matrix to store
  13913. */
  13914. Engine.prototype.setMatrix = function (uniform, matrix) {
  13915. if (!uniform)
  13916. return;
  13917. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13918. };
  13919. /**
  13920. * Set the value of an uniform to a matrix (3x3)
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13923. */
  13924. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13928. };
  13929. /**
  13930. * Set the value of an uniform to a matrix (2x2)
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13933. */
  13934. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13935. if (!uniform)
  13936. return;
  13937. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13938. };
  13939. /**
  13940. * Set the value of an uniform to a number (int)
  13941. * @param uniform defines the webGL uniform location where to store the value
  13942. * @param value defines the int number to store
  13943. */
  13944. Engine.prototype.setInt = function (uniform, value) {
  13945. if (!uniform)
  13946. return;
  13947. this._gl.uniform1i(uniform, value);
  13948. };
  13949. /**
  13950. * Set the value of an uniform to a number (float)
  13951. * @param uniform defines the webGL uniform location where to store the value
  13952. * @param value defines the float number to store
  13953. */
  13954. Engine.prototype.setFloat = function (uniform, value) {
  13955. if (!uniform)
  13956. return;
  13957. this._gl.uniform1f(uniform, value);
  13958. };
  13959. /**
  13960. * Set the value of an uniform to a vec2
  13961. * @param uniform defines the webGL uniform location where to store the value
  13962. * @param x defines the 1st component of the value
  13963. * @param y defines the 2nd component of the value
  13964. */
  13965. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13966. if (!uniform)
  13967. return;
  13968. this._gl.uniform2f(uniform, x, y);
  13969. };
  13970. /**
  13971. * Set the value of an uniform to a vec3
  13972. * @param uniform defines the webGL uniform location where to store the value
  13973. * @param x defines the 1st component of the value
  13974. * @param y defines the 2nd component of the value
  13975. * @param z defines the 3rd component of the value
  13976. */
  13977. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13978. if (!uniform)
  13979. return;
  13980. this._gl.uniform3f(uniform, x, y, z);
  13981. };
  13982. /**
  13983. * Set the value of an uniform to a boolean
  13984. * @param uniform defines the webGL uniform location where to store the value
  13985. * @param bool defines the boolean to store
  13986. */
  13987. Engine.prototype.setBool = function (uniform, bool) {
  13988. if (!uniform)
  13989. return;
  13990. this._gl.uniform1i(uniform, bool);
  13991. };
  13992. /**
  13993. * Set the value of an uniform to a vec4
  13994. * @param uniform defines the webGL uniform location where to store the value
  13995. * @param x defines the 1st component of the value
  13996. * @param y defines the 2nd component of the value
  13997. * @param z defines the 3rd component of the value
  13998. * @param w defines the 4th component of the value
  13999. */
  14000. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14001. if (!uniform)
  14002. return;
  14003. this._gl.uniform4f(uniform, x, y, z, w);
  14004. };
  14005. /**
  14006. * Set the value of an uniform to a Color3
  14007. * @param uniform defines the webGL uniform location where to store the value
  14008. * @param color3 defines the color to store
  14009. */
  14010. Engine.prototype.setColor3 = function (uniform, color3) {
  14011. if (!uniform)
  14012. return;
  14013. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14014. };
  14015. /**
  14016. * Set the value of an uniform to a Color3 and an alpha value
  14017. * @param uniform defines the webGL uniform location where to store the value
  14018. * @param color3 defines the color to store
  14019. * @param alpha defines the alpha component to store
  14020. */
  14021. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14022. if (!uniform)
  14023. return;
  14024. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14025. };
  14026. /**
  14027. * Sets a Color4 on a uniform variable
  14028. * @param uniform defines the uniform location
  14029. * @param color4 defines the value to be set
  14030. */
  14031. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14032. if (!uniform)
  14033. return;
  14034. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14035. };
  14036. // States
  14037. /**
  14038. * Set various states to the webGL context
  14039. * @param culling defines backface culling state
  14040. * @param zOffset defines the value to apply to zOffset (0 by default)
  14041. * @param force defines if states must be applied even if cache is up to date
  14042. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14043. */
  14044. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14045. if (zOffset === void 0) { zOffset = 0; }
  14046. if (reverseSide === void 0) { reverseSide = false; }
  14047. // Culling
  14048. if (this._depthCullingState.cull !== culling || force) {
  14049. this._depthCullingState.cull = culling;
  14050. }
  14051. // Cull face
  14052. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14053. if (this._depthCullingState.cullFace !== cullFace || force) {
  14054. this._depthCullingState.cullFace = cullFace;
  14055. }
  14056. // Z offset
  14057. this.setZOffset(zOffset);
  14058. // Front face
  14059. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14060. if (this._depthCullingState.frontFace !== frontFace || force) {
  14061. this._depthCullingState.frontFace = frontFace;
  14062. }
  14063. };
  14064. /**
  14065. * Set the z offset to apply to current rendering
  14066. * @param value defines the offset to apply
  14067. */
  14068. Engine.prototype.setZOffset = function (value) {
  14069. this._depthCullingState.zOffset = value;
  14070. };
  14071. /**
  14072. * Gets the current value of the zOffset
  14073. * @returns the current zOffset state
  14074. */
  14075. Engine.prototype.getZOffset = function () {
  14076. return this._depthCullingState.zOffset;
  14077. };
  14078. /**
  14079. * Enable or disable depth buffering
  14080. * @param enable defines the state to set
  14081. */
  14082. Engine.prototype.setDepthBuffer = function (enable) {
  14083. this._depthCullingState.depthTest = enable;
  14084. };
  14085. /**
  14086. * Gets a boolean indicating if depth writing is enabled
  14087. * @returns the current depth writing state
  14088. */
  14089. Engine.prototype.getDepthWrite = function () {
  14090. return this._depthCullingState.depthMask;
  14091. };
  14092. /**
  14093. * Enable or disable depth writing
  14094. * @param enable defines the state to set
  14095. */
  14096. Engine.prototype.setDepthWrite = function (enable) {
  14097. this._depthCullingState.depthMask = enable;
  14098. };
  14099. /**
  14100. * Enable or disable color writing
  14101. * @param enable defines the state to set
  14102. */
  14103. Engine.prototype.setColorWrite = function (enable) {
  14104. this._gl.colorMask(enable, enable, enable, enable);
  14105. this._colorWrite = enable;
  14106. };
  14107. /**
  14108. * Gets a boolean indicating if color writing is enabled
  14109. * @returns the current color writing state
  14110. */
  14111. Engine.prototype.getColorWrite = function () {
  14112. return this._colorWrite;
  14113. };
  14114. /**
  14115. * Sets alpha constants used by some alpha blending modes
  14116. * @param r defines the red component
  14117. * @param g defines the green component
  14118. * @param b defines the blue component
  14119. * @param a defines the alpha component
  14120. */
  14121. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14122. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14123. };
  14124. /**
  14125. * Sets the current alpha mode
  14126. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14127. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14128. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14129. */
  14130. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14131. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14132. if (this._alphaMode === mode) {
  14133. return;
  14134. }
  14135. switch (mode) {
  14136. case Engine.ALPHA_DISABLE:
  14137. this._alphaState.alphaBlend = false;
  14138. break;
  14139. case Engine.ALPHA_PREMULTIPLIED:
  14140. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14141. this._alphaState.alphaBlend = true;
  14142. break;
  14143. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14144. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14145. this._alphaState.alphaBlend = true;
  14146. break;
  14147. case Engine.ALPHA_COMBINE:
  14148. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14149. this._alphaState.alphaBlend = true;
  14150. break;
  14151. case Engine.ALPHA_ONEONE:
  14152. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14153. this._alphaState.alphaBlend = true;
  14154. break;
  14155. case Engine.ALPHA_ADD:
  14156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14157. this._alphaState.alphaBlend = true;
  14158. break;
  14159. case Engine.ALPHA_SUBTRACT:
  14160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14161. this._alphaState.alphaBlend = true;
  14162. break;
  14163. case Engine.ALPHA_MULTIPLY:
  14164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14165. this._alphaState.alphaBlend = true;
  14166. break;
  14167. case Engine.ALPHA_MAXIMIZED:
  14168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14169. this._alphaState.alphaBlend = true;
  14170. break;
  14171. case Engine.ALPHA_INTERPOLATE:
  14172. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14173. this._alphaState.alphaBlend = true;
  14174. break;
  14175. case Engine.ALPHA_SCREENMODE:
  14176. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14177. this._alphaState.alphaBlend = true;
  14178. break;
  14179. }
  14180. if (!noDepthWriteChange) {
  14181. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14182. }
  14183. this._alphaMode = mode;
  14184. };
  14185. /**
  14186. * Gets the current alpha mode
  14187. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14188. * @returns the current alpha mode
  14189. */
  14190. Engine.prototype.getAlphaMode = function () {
  14191. return this._alphaMode;
  14192. };
  14193. // Textures
  14194. /**
  14195. * Clears the list of texture accessible through engine.
  14196. * This can help preventing texture load conflict due to name collision.
  14197. */
  14198. Engine.prototype.clearInternalTexturesCache = function () {
  14199. this._internalTexturesCache = [];
  14200. };
  14201. /**
  14202. * Force the entire cache to be cleared
  14203. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14204. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14205. */
  14206. Engine.prototype.wipeCaches = function (bruteForce) {
  14207. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14208. return;
  14209. }
  14210. this._currentEffect = null;
  14211. this._unpackFlipYCached = null;
  14212. this._viewportCached.x = 0;
  14213. this._viewportCached.y = 0;
  14214. this._viewportCached.z = 0;
  14215. this._viewportCached.w = 0;
  14216. if (bruteForce) {
  14217. this.resetTextureCache();
  14218. this._currentProgram = null;
  14219. this._stencilState.reset();
  14220. this._depthCullingState.reset();
  14221. this.setDepthFunctionToLessOrEqual();
  14222. this._alphaState.reset();
  14223. }
  14224. this._resetVertexBufferBinding();
  14225. this._cachedIndexBuffer = null;
  14226. this._cachedEffectForVertexBuffers = null;
  14227. this._unbindVertexArrayObject();
  14228. this.bindIndexBuffer(null);
  14229. };
  14230. /**
  14231. * Set the compressed texture format to use, based on the formats you have, and the formats
  14232. * supported by the hardware / browser.
  14233. *
  14234. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14235. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14236. * to API arguments needed to compressed textures. This puts the burden on the container
  14237. * generator to house the arcane code for determining these for current & future formats.
  14238. *
  14239. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14240. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14241. *
  14242. * Note: The result of this call is not taken into account when a texture is base64.
  14243. *
  14244. * @param formatsAvailable defines the list of those format families you have created
  14245. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14246. *
  14247. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14248. * @returns The extension selected.
  14249. */
  14250. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14251. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14252. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14253. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14254. return this._textureFormatInUse = this._texturesSupported[i];
  14255. }
  14256. }
  14257. }
  14258. // actively set format to nothing, to allow this to be called more than once
  14259. // and possibly fail the 2nd time
  14260. this._textureFormatInUse = null;
  14261. return null;
  14262. };
  14263. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14264. var gl = this._gl;
  14265. var magFilter = gl.NEAREST;
  14266. var minFilter = gl.NEAREST;
  14267. switch (samplingMode) {
  14268. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14269. magFilter = gl.LINEAR;
  14270. if (generateMipMaps) {
  14271. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14272. }
  14273. else {
  14274. minFilter = gl.LINEAR;
  14275. }
  14276. break;
  14277. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14278. magFilter = gl.LINEAR;
  14279. if (generateMipMaps) {
  14280. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14281. }
  14282. else {
  14283. minFilter = gl.LINEAR;
  14284. }
  14285. break;
  14286. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14287. magFilter = gl.NEAREST;
  14288. if (generateMipMaps) {
  14289. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14290. }
  14291. else {
  14292. minFilter = gl.NEAREST;
  14293. }
  14294. break;
  14295. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14296. magFilter = gl.NEAREST;
  14297. if (generateMipMaps) {
  14298. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14299. }
  14300. else {
  14301. minFilter = gl.NEAREST;
  14302. }
  14303. break;
  14304. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14305. magFilter = gl.NEAREST;
  14306. if (generateMipMaps) {
  14307. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14308. }
  14309. else {
  14310. minFilter = gl.LINEAR;
  14311. }
  14312. break;
  14313. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14314. magFilter = gl.NEAREST;
  14315. if (generateMipMaps) {
  14316. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14317. }
  14318. else {
  14319. minFilter = gl.LINEAR;
  14320. }
  14321. break;
  14322. case Engine.TEXTURE_NEAREST_LINEAR:
  14323. magFilter = gl.NEAREST;
  14324. minFilter = gl.LINEAR;
  14325. break;
  14326. case Engine.TEXTURE_NEAREST_NEAREST:
  14327. magFilter = gl.NEAREST;
  14328. minFilter = gl.NEAREST;
  14329. break;
  14330. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14331. magFilter = gl.LINEAR;
  14332. if (generateMipMaps) {
  14333. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14334. }
  14335. else {
  14336. minFilter = gl.NEAREST;
  14337. }
  14338. break;
  14339. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14340. magFilter = gl.LINEAR;
  14341. if (generateMipMaps) {
  14342. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14343. }
  14344. else {
  14345. minFilter = gl.NEAREST;
  14346. }
  14347. break;
  14348. case Engine.TEXTURE_LINEAR_LINEAR:
  14349. magFilter = gl.LINEAR;
  14350. minFilter = gl.LINEAR;
  14351. break;
  14352. case Engine.TEXTURE_LINEAR_NEAREST:
  14353. magFilter = gl.LINEAR;
  14354. minFilter = gl.NEAREST;
  14355. break;
  14356. }
  14357. return {
  14358. min: minFilter,
  14359. mag: magFilter
  14360. };
  14361. };
  14362. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14363. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14364. var img;
  14365. var onload = function () {
  14366. loadedImages[index] = img;
  14367. loadedImages._internalCount++;
  14368. if (scene) {
  14369. scene._removePendingData(img);
  14370. }
  14371. if (loadedImages._internalCount === 6) {
  14372. onfinish(loadedImages);
  14373. }
  14374. };
  14375. var onerror = function (message, exception) {
  14376. if (scene) {
  14377. scene._removePendingData(img);
  14378. }
  14379. if (onErrorCallBack) {
  14380. onErrorCallBack(message, exception);
  14381. }
  14382. };
  14383. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14384. if (scene) {
  14385. scene._addPendingData(img);
  14386. }
  14387. };
  14388. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14389. if (onError === void 0) { onError = null; }
  14390. var loadedImages = [];
  14391. loadedImages._internalCount = 0;
  14392. for (var index = 0; index < 6; index++) {
  14393. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14394. }
  14395. };
  14396. ;
  14397. /** @hidden */
  14398. Engine.prototype._createTexture = function () {
  14399. var texture = this._gl.createTexture();
  14400. if (!texture) {
  14401. throw new Error("Unable to create texture");
  14402. }
  14403. return texture;
  14404. };
  14405. /**
  14406. * Usually called from BABYLON.Texture.ts.
  14407. * Passed information to create a WebGLTexture
  14408. * @param urlArg defines a value which contains one of the following:
  14409. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14410. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14411. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14412. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14413. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14414. * @param scene needed for loading to the correct scene
  14415. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14416. * @param onLoad optional callback to be called upon successful completion
  14417. * @param onError optional callback to be called upon failure
  14418. * @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
  14419. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14420. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14421. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14422. */
  14423. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14424. var _this = this;
  14425. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14426. if (onLoad === void 0) { onLoad = null; }
  14427. if (onError === void 0) { onError = null; }
  14428. if (buffer === void 0) { buffer = null; }
  14429. if (fallback === void 0) { fallback = null; }
  14430. if (format === void 0) { format = null; }
  14431. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14432. var fromData = url.substr(0, 5) === "data:";
  14433. var fromBlob = url.substr(0, 5) === "blob:";
  14434. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14435. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14436. // establish the file extension, if possible
  14437. var lastDot = url.lastIndexOf('.');
  14438. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14439. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14440. var isTGA = (extension.indexOf(".tga") === 0);
  14441. // determine if a ktx file should be substituted
  14442. var isKTX = false;
  14443. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14444. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14445. isKTX = true;
  14446. }
  14447. if (scene) {
  14448. scene._addPendingData(texture);
  14449. }
  14450. texture.url = url;
  14451. texture.generateMipMaps = !noMipmap;
  14452. texture.samplingMode = samplingMode;
  14453. texture.invertY = invertY;
  14454. if (!this._doNotHandleContextLost) {
  14455. // Keep a link to the buffer only if we plan to handle context lost
  14456. texture._buffer = buffer;
  14457. }
  14458. var onLoadObserver = null;
  14459. if (onLoad && !fallback) {
  14460. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14461. }
  14462. if (!fallback)
  14463. this._internalTexturesCache.push(texture);
  14464. var onerror = function (message, exception) {
  14465. if (scene) {
  14466. scene._removePendingData(texture);
  14467. }
  14468. if (onLoadObserver && !isKTX) {
  14469. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14470. texture.onLoadedObservable.remove(onLoadObserver);
  14471. }
  14472. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14473. if (isKTX) {
  14474. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14475. }
  14476. else if (BABYLON.Tools.UseFallbackTexture) {
  14477. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14478. }
  14479. if (onError) {
  14480. onError(message || "Unknown error", exception);
  14481. }
  14482. };
  14483. var callback = null;
  14484. // processing for non-image formats
  14485. if (isKTX || isTGA || isDDS) {
  14486. if (isKTX) {
  14487. callback = function (data) {
  14488. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14489. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14490. ktx.uploadLevels(texture, !noMipmap);
  14491. return false;
  14492. }, samplingMode);
  14493. };
  14494. }
  14495. else if (isTGA) {
  14496. callback = function (arrayBuffer) {
  14497. var data = new Uint8Array(arrayBuffer);
  14498. var header = BABYLON.TGATools.GetTGAHeader(data);
  14499. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14500. BABYLON.TGATools.UploadContent(texture, data);
  14501. return false;
  14502. }, samplingMode);
  14503. };
  14504. }
  14505. else if (isDDS) {
  14506. callback = function (data) {
  14507. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14508. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14509. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14510. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 1);
  14511. return false;
  14512. }, samplingMode);
  14513. };
  14514. }
  14515. if (!buffer) {
  14516. this._loadFile(url, function (data) {
  14517. if (callback) {
  14518. callback(data);
  14519. }
  14520. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14521. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14522. });
  14523. }
  14524. else {
  14525. if (callback) {
  14526. callback(buffer);
  14527. }
  14528. }
  14529. // image format processing
  14530. }
  14531. else {
  14532. var onload = function (img) {
  14533. if (fromBlob && !_this._doNotHandleContextLost) {
  14534. // We need to store the image if we need to rebuild the texture
  14535. // in case of a webgl context lost
  14536. texture._buffer = img;
  14537. }
  14538. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14539. var gl = _this._gl;
  14540. var isPot = (img.width === potWidth && img.height === potHeight);
  14541. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14542. if (isPot) {
  14543. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14544. return false;
  14545. }
  14546. var maxTextureSize = _this._caps.maxTextureSize;
  14547. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14548. _this._prepareWorkingCanvas();
  14549. if (!_this._workingCanvas || !_this._workingContext) {
  14550. return false;
  14551. }
  14552. _this._workingCanvas.width = potWidth;
  14553. _this._workingCanvas.height = potHeight;
  14554. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14555. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14556. texture.width = potWidth;
  14557. texture.height = potHeight;
  14558. return false;
  14559. }
  14560. else {
  14561. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14562. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14563. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14564. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14565. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14566. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14569. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14570. _this._releaseTexture(source_1);
  14571. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14572. continuationCallback();
  14573. });
  14574. }
  14575. return true;
  14576. }, samplingMode);
  14577. };
  14578. if (!fromData || isBase64) {
  14579. if (buffer instanceof HTMLImageElement) {
  14580. onload(buffer);
  14581. }
  14582. else {
  14583. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14584. }
  14585. }
  14586. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14587. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14588. }
  14589. else {
  14590. onload(buffer);
  14591. }
  14592. }
  14593. return texture;
  14594. };
  14595. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14596. var _this = this;
  14597. var rtt = this.createRenderTargetTexture({
  14598. width: destination.width,
  14599. height: destination.height,
  14600. }, {
  14601. generateMipMaps: false,
  14602. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14603. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14604. generateDepthBuffer: false,
  14605. generateStencilBuffer: false
  14606. });
  14607. if (!this._rescalePostProcess) {
  14608. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14609. }
  14610. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14611. _this._rescalePostProcess.onApply = function (effect) {
  14612. effect._bindTexture("textureSampler", source);
  14613. };
  14614. var hostingScene = scene;
  14615. if (!hostingScene) {
  14616. hostingScene = _this.scenes[_this.scenes.length - 1];
  14617. }
  14618. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14619. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14620. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14621. _this.unBindFramebuffer(rtt);
  14622. _this._releaseTexture(rtt);
  14623. if (onComplete) {
  14624. onComplete();
  14625. }
  14626. });
  14627. };
  14628. /**
  14629. * Update a raw texture
  14630. * @param texture defines the texture to update
  14631. * @param data defines the data to store in the texture
  14632. * @param format defines the format of the data
  14633. * @param invertY defines if data must be stored with Y axis inverted
  14634. * @param compression defines the compression used (null by default)
  14635. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14636. */
  14637. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14638. if (compression === void 0) { compression = null; }
  14639. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14640. if (!texture) {
  14641. return;
  14642. }
  14643. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14644. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14645. // babylon's internalFormat but gl's texImage2D format
  14646. var internalFormat = this._getInternalFormat(format);
  14647. var textureType = this._getWebGLTextureType(type);
  14648. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14649. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14650. if (!this._doNotHandleContextLost) {
  14651. texture._bufferView = data;
  14652. texture.format = format;
  14653. texture.type = type;
  14654. texture.invertY = invertY;
  14655. texture._compression = compression;
  14656. }
  14657. if (texture.width % 4 !== 0) {
  14658. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14659. }
  14660. if (compression && data) {
  14661. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14662. }
  14663. else {
  14664. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14665. }
  14666. if (texture.generateMipMaps) {
  14667. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14668. }
  14669. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14670. // this.resetTextureCache();
  14671. texture.isReady = true;
  14672. };
  14673. /**
  14674. * Creates a raw texture
  14675. * @param data defines the data to store in the texture
  14676. * @param width defines the width of the texture
  14677. * @param height defines the height of the texture
  14678. * @param format defines the format of the data
  14679. * @param generateMipMaps defines if the engine should generate the mip levels
  14680. * @param invertY defines if data must be stored with Y axis inverted
  14681. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14682. * @param compression defines the compression used (null by default)
  14683. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14684. * @returns the raw texture inside an InternalTexture
  14685. */
  14686. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14687. if (compression === void 0) { compression = null; }
  14688. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14689. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14690. texture.baseWidth = width;
  14691. texture.baseHeight = height;
  14692. texture.width = width;
  14693. texture.height = height;
  14694. texture.format = format;
  14695. texture.generateMipMaps = generateMipMaps;
  14696. texture.samplingMode = samplingMode;
  14697. texture.invertY = invertY;
  14698. texture._compression = compression;
  14699. texture.type = type;
  14700. if (!this._doNotHandleContextLost) {
  14701. texture._bufferView = data;
  14702. }
  14703. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14704. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14705. // Filters
  14706. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14707. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14708. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14709. if (generateMipMaps) {
  14710. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14711. }
  14712. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14713. this._internalTexturesCache.push(texture);
  14714. return texture;
  14715. };
  14716. /** @hidden */
  14717. Engine.prototype._unpackFlipY = function (value) {
  14718. if (this._unpackFlipYCached !== value) {
  14719. this._unpackFlipYCached = value;
  14720. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14721. }
  14722. };
  14723. /** @hidden */
  14724. Engine.prototype._getUnpackAlignement = function () {
  14725. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14726. };
  14727. /**
  14728. * Creates a dynamic texture
  14729. * @param width defines the width of the texture
  14730. * @param height defines the height of the texture
  14731. * @param generateMipMaps defines if the engine should generate the mip levels
  14732. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14733. * @returns the dynamic texture inside an InternalTexture
  14734. */
  14735. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14736. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14737. texture.baseWidth = width;
  14738. texture.baseHeight = height;
  14739. if (generateMipMaps) {
  14740. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14741. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14742. }
  14743. // this.resetTextureCache();
  14744. texture.width = width;
  14745. texture.height = height;
  14746. texture.isReady = false;
  14747. texture.generateMipMaps = generateMipMaps;
  14748. texture.samplingMode = samplingMode;
  14749. this.updateTextureSamplingMode(samplingMode, texture);
  14750. this._internalTexturesCache.push(texture);
  14751. return texture;
  14752. };
  14753. /**
  14754. * Update the sampling mode of a given texture
  14755. * @param samplingMode defines the required sampling mode
  14756. * @param texture defines the texture to update
  14757. */
  14758. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14759. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14760. if (texture.isCube) {
  14761. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14762. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14763. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14764. }
  14765. else if (texture.is3D) {
  14766. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14767. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14768. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14769. }
  14770. else {
  14771. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14772. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14773. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14774. }
  14775. texture.samplingMode = samplingMode;
  14776. };
  14777. /**
  14778. * Update the content of a dynamic texture
  14779. * @param texture defines the texture to update
  14780. * @param canvas defines the canvas containing the source
  14781. * @param invertY defines if data must be stored with Y axis inverted
  14782. * @param premulAlpha defines if alpha is stored as premultiplied
  14783. * @param format defines the format of the data
  14784. */
  14785. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14786. if (premulAlpha === void 0) { premulAlpha = false; }
  14787. if (!texture) {
  14788. return;
  14789. }
  14790. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14791. this._unpackFlipY(invertY);
  14792. if (premulAlpha) {
  14793. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14794. }
  14795. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14796. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14797. if (texture.generateMipMaps) {
  14798. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14799. }
  14800. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14801. if (premulAlpha) {
  14802. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14803. }
  14804. texture.isReady = true;
  14805. };
  14806. /**
  14807. * Update a video texture
  14808. * @param texture defines the texture to update
  14809. * @param video defines the video element to use
  14810. * @param invertY defines if data must be stored with Y axis inverted
  14811. */
  14812. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14813. if (!texture || texture._isDisabled) {
  14814. return;
  14815. }
  14816. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14817. this._unpackFlipY(!invertY); // Video are upside down by default
  14818. try {
  14819. // Testing video texture support
  14820. if (this._videoTextureSupported === undefined) {
  14821. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14822. if (this._gl.getError() !== 0) {
  14823. this._videoTextureSupported = false;
  14824. }
  14825. else {
  14826. this._videoTextureSupported = true;
  14827. }
  14828. }
  14829. // Copy video through the current working canvas if video texture is not supported
  14830. if (!this._videoTextureSupported) {
  14831. if (!texture._workingCanvas) {
  14832. texture._workingCanvas = document.createElement("canvas");
  14833. var context = texture._workingCanvas.getContext("2d");
  14834. if (!context) {
  14835. throw new Error("Unable to get 2d context");
  14836. }
  14837. texture._workingContext = context;
  14838. texture._workingCanvas.width = texture.width;
  14839. texture._workingCanvas.height = texture.height;
  14840. }
  14841. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14842. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14843. }
  14844. else {
  14845. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14846. }
  14847. if (texture.generateMipMaps) {
  14848. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14849. }
  14850. if (!wasPreviouslyBound) {
  14851. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14852. }
  14853. // this.resetTextureCache();
  14854. texture.isReady = true;
  14855. }
  14856. catch (ex) {
  14857. // Something unexpected
  14858. // Let's disable the texture
  14859. texture._isDisabled = true;
  14860. }
  14861. };
  14862. /**
  14863. * Updates a depth texture Comparison Mode and Function.
  14864. * If the comparison Function is equal to 0, the mode will be set to none.
  14865. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14866. * @param texture The texture to set the comparison function for
  14867. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14868. */
  14869. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14870. if (this.webGLVersion === 1) {
  14871. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14872. return;
  14873. }
  14874. var gl = this._gl;
  14875. if (texture.isCube) {
  14876. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14877. if (comparisonFunction === 0) {
  14878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14880. }
  14881. else {
  14882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14884. }
  14885. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14886. }
  14887. else {
  14888. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14889. if (comparisonFunction === 0) {
  14890. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14891. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14892. }
  14893. else {
  14894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14896. }
  14897. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14898. }
  14899. texture._comparisonFunction = comparisonFunction;
  14900. };
  14901. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14902. var width = size.width || size;
  14903. var height = size.height || size;
  14904. internalTexture.baseWidth = width;
  14905. internalTexture.baseHeight = height;
  14906. internalTexture.width = width;
  14907. internalTexture.height = height;
  14908. internalTexture.isReady = true;
  14909. internalTexture.samples = 1;
  14910. internalTexture.generateMipMaps = false;
  14911. internalTexture._generateDepthBuffer = true;
  14912. internalTexture._generateStencilBuffer = generateStencil;
  14913. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14914. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14915. internalTexture._comparisonFunction = comparisonFunction;
  14916. var gl = this._gl;
  14917. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14918. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14919. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14920. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14921. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14922. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14923. if (comparisonFunction === 0) {
  14924. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14925. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14926. }
  14927. else {
  14928. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14929. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14930. }
  14931. };
  14932. /**
  14933. * Creates a depth stencil texture.
  14934. * This is only available in WebGL 2 or with the depth texture extension available.
  14935. * @param size The size of face edge in the texture.
  14936. * @param options The options defining the texture.
  14937. * @returns The texture
  14938. */
  14939. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14940. if (options.isCube) {
  14941. var width = size.width || size;
  14942. return this._createDepthStencilCubeTexture(width, options);
  14943. }
  14944. else {
  14945. return this._createDepthStencilTexture(size, options);
  14946. }
  14947. };
  14948. /**
  14949. * Creates a depth stencil texture.
  14950. * This is only available in WebGL 2 or with the depth texture extension available.
  14951. * @param size The size of face edge in the texture.
  14952. * @param options The options defining the texture.
  14953. * @returns The texture
  14954. */
  14955. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14956. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14957. if (!this._caps.depthTextureExtension) {
  14958. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14959. return internalTexture;
  14960. }
  14961. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14962. var gl = this._gl;
  14963. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14964. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14965. if (this.webGLVersion > 1) {
  14966. if (internalOptions.generateStencil) {
  14967. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14968. }
  14969. else {
  14970. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14971. }
  14972. }
  14973. else {
  14974. if (internalOptions.generateStencil) {
  14975. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14976. }
  14977. else {
  14978. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14979. }
  14980. }
  14981. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14982. return internalTexture;
  14983. };
  14984. /**
  14985. * Creates a depth stencil cube texture.
  14986. * This is only available in WebGL 2.
  14987. * @param size The size of face edge in the cube texture.
  14988. * @param options The options defining the cube texture.
  14989. * @returns The cube texture
  14990. */
  14991. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14992. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14993. internalTexture.isCube = true;
  14994. if (this.webGLVersion === 1) {
  14995. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14996. return internalTexture;
  14997. }
  14998. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14999. var gl = this._gl;
  15000. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15001. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15002. // Create the depth/stencil buffer
  15003. for (var face = 0; face < 6; face++) {
  15004. if (internalOptions.generateStencil) {
  15005. 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);
  15006. }
  15007. else {
  15008. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15009. }
  15010. }
  15011. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15012. return internalTexture;
  15013. };
  15014. /**
  15015. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15016. * @param renderTarget The render target to set the frame buffer for
  15017. */
  15018. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15019. // Create the framebuffer
  15020. var internalTexture = renderTarget.getInternalTexture();
  15021. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15022. return;
  15023. }
  15024. var gl = this._gl;
  15025. var depthStencilTexture = renderTarget.depthStencilTexture;
  15026. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15027. if (depthStencilTexture.isCube) {
  15028. if (depthStencilTexture._generateStencilBuffer) {
  15029. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15030. }
  15031. else {
  15032. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15033. }
  15034. }
  15035. else {
  15036. if (depthStencilTexture._generateStencilBuffer) {
  15037. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15038. }
  15039. else {
  15040. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15041. }
  15042. }
  15043. this.bindUnboundFramebuffer(null);
  15044. };
  15045. /**
  15046. * Creates a new render target texture
  15047. * @param size defines the size of the texture
  15048. * @param options defines the options used to create the texture
  15049. * @returns a new render target texture stored in an InternalTexture
  15050. */
  15051. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15052. var fullOptions = new RenderTargetCreationOptions();
  15053. if (options !== undefined && typeof options === "object") {
  15054. fullOptions.generateMipMaps = options.generateMipMaps;
  15055. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15056. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15057. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15058. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15059. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15060. }
  15061. else {
  15062. fullOptions.generateMipMaps = options;
  15063. fullOptions.generateDepthBuffer = true;
  15064. fullOptions.generateStencilBuffer = false;
  15065. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15066. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15067. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15068. }
  15069. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15070. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15071. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15072. }
  15073. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15074. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15075. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15076. }
  15077. var gl = this._gl;
  15078. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15079. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15080. var width = size.width || size;
  15081. var height = size.height || size;
  15082. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15083. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15084. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15085. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15086. }
  15087. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15091. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15092. // Create the framebuffer
  15093. var currentFrameBuffer = this._currentFramebuffer;
  15094. var framebuffer = gl.createFramebuffer();
  15095. this.bindUnboundFramebuffer(framebuffer);
  15096. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15097. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15098. if (fullOptions.generateMipMaps) {
  15099. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15100. }
  15101. // Unbind
  15102. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15103. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15104. this.bindUnboundFramebuffer(currentFrameBuffer);
  15105. texture._framebuffer = framebuffer;
  15106. texture.baseWidth = width;
  15107. texture.baseHeight = height;
  15108. texture.width = width;
  15109. texture.height = height;
  15110. texture.isReady = true;
  15111. texture.samples = 1;
  15112. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15113. texture.samplingMode = fullOptions.samplingMode;
  15114. texture.type = fullOptions.type;
  15115. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15116. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15117. // this.resetTextureCache();
  15118. this._internalTexturesCache.push(texture);
  15119. return texture;
  15120. };
  15121. /**
  15122. * Create a multi render target texture
  15123. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15124. * @param size defines the size of the texture
  15125. * @param options defines the creation options
  15126. * @returns the cube texture as an InternalTexture
  15127. */
  15128. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15129. var generateMipMaps = false;
  15130. var generateDepthBuffer = true;
  15131. var generateStencilBuffer = false;
  15132. var generateDepthTexture = false;
  15133. var textureCount = 1;
  15134. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15135. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15136. var types = new Array();
  15137. var samplingModes = new Array();
  15138. if (options !== undefined) {
  15139. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15140. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15141. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15142. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15143. textureCount = options.textureCount || 1;
  15144. if (options.types) {
  15145. types = options.types;
  15146. }
  15147. if (options.samplingModes) {
  15148. samplingModes = options.samplingModes;
  15149. }
  15150. }
  15151. var gl = this._gl;
  15152. // Create the framebuffer
  15153. var framebuffer = gl.createFramebuffer();
  15154. this.bindUnboundFramebuffer(framebuffer);
  15155. var width = size.width || size;
  15156. var height = size.height || size;
  15157. var textures = [];
  15158. var attachments = [];
  15159. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15160. for (var i = 0; i < textureCount; i++) {
  15161. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15162. var type = types[i] || defaultType;
  15163. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15164. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15165. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15166. }
  15167. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15168. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15169. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15170. }
  15171. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15172. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15173. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15174. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15175. }
  15176. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15177. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15178. textures.push(texture);
  15179. attachments.push(attachment);
  15180. gl.activeTexture(gl["TEXTURE" + i]);
  15181. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15182. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15186. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15187. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15188. if (generateMipMaps) {
  15189. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15190. }
  15191. // Unbind
  15192. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15193. texture._framebuffer = framebuffer;
  15194. texture._depthStencilBuffer = depthStencilBuffer;
  15195. texture.baseWidth = width;
  15196. texture.baseHeight = height;
  15197. texture.width = width;
  15198. texture.height = height;
  15199. texture.isReady = true;
  15200. texture.samples = 1;
  15201. texture.generateMipMaps = generateMipMaps;
  15202. texture.samplingMode = samplingMode;
  15203. texture.type = type;
  15204. texture._generateDepthBuffer = generateDepthBuffer;
  15205. texture._generateStencilBuffer = generateStencilBuffer;
  15206. texture._attachments = attachments;
  15207. this._internalTexturesCache.push(texture);
  15208. }
  15209. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15210. // Depth texture
  15211. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15212. gl.activeTexture(gl.TEXTURE0);
  15213. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15215. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15218. 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);
  15219. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15220. depthTexture._framebuffer = framebuffer;
  15221. depthTexture.baseWidth = width;
  15222. depthTexture.baseHeight = height;
  15223. depthTexture.width = width;
  15224. depthTexture.height = height;
  15225. depthTexture.isReady = true;
  15226. depthTexture.samples = 1;
  15227. depthTexture.generateMipMaps = generateMipMaps;
  15228. depthTexture.samplingMode = gl.NEAREST;
  15229. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15230. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15231. textures.push(depthTexture);
  15232. this._internalTexturesCache.push(depthTexture);
  15233. }
  15234. gl.drawBuffers(attachments);
  15235. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15236. this.bindUnboundFramebuffer(null);
  15237. this.resetTextureCache();
  15238. return textures;
  15239. };
  15240. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15241. if (samples === void 0) { samples = 1; }
  15242. var depthStencilBuffer = null;
  15243. var gl = this._gl;
  15244. // Create the depth/stencil buffer
  15245. if (generateStencilBuffer) {
  15246. depthStencilBuffer = gl.createRenderbuffer();
  15247. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15248. if (samples > 1) {
  15249. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15250. }
  15251. else {
  15252. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15253. }
  15254. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15255. }
  15256. else if (generateDepthBuffer) {
  15257. depthStencilBuffer = gl.createRenderbuffer();
  15258. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15259. if (samples > 1) {
  15260. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15261. }
  15262. else {
  15263. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15264. }
  15265. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15266. }
  15267. return depthStencilBuffer;
  15268. };
  15269. /**
  15270. * Updates the sample count of a render target texture
  15271. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15272. * @param texture defines the texture to update
  15273. * @param samples defines the sample count to set
  15274. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15275. */
  15276. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15277. if (this.webGLVersion < 2 || !texture) {
  15278. return 1;
  15279. }
  15280. if (texture.samples === samples) {
  15281. return samples;
  15282. }
  15283. var gl = this._gl;
  15284. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15285. // Dispose previous render buffers
  15286. if (texture._depthStencilBuffer) {
  15287. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15288. texture._depthStencilBuffer = null;
  15289. }
  15290. if (texture._MSAAFramebuffer) {
  15291. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15292. texture._MSAAFramebuffer = null;
  15293. }
  15294. if (texture._MSAARenderBuffer) {
  15295. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15296. texture._MSAARenderBuffer = null;
  15297. }
  15298. if (samples > 1) {
  15299. var framebuffer = gl.createFramebuffer();
  15300. if (!framebuffer) {
  15301. throw new Error("Unable to create multi sampled framebuffer");
  15302. }
  15303. texture._MSAAFramebuffer = framebuffer;
  15304. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15305. var colorRenderbuffer = gl.createRenderbuffer();
  15306. if (!colorRenderbuffer) {
  15307. throw new Error("Unable to create multi sampled framebuffer");
  15308. }
  15309. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15310. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15311. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15312. texture._MSAARenderBuffer = colorRenderbuffer;
  15313. }
  15314. else {
  15315. this.bindUnboundFramebuffer(texture._framebuffer);
  15316. }
  15317. texture.samples = samples;
  15318. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15319. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15320. this.bindUnboundFramebuffer(null);
  15321. return samples;
  15322. };
  15323. /**
  15324. * Update the sample count for a given multiple render target texture
  15325. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15326. * @param textures defines the textures to update
  15327. * @param samples defines the sample count to set
  15328. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15329. */
  15330. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15331. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15332. return 1;
  15333. }
  15334. if (textures[0].samples === samples) {
  15335. return samples;
  15336. }
  15337. var gl = this._gl;
  15338. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15339. // Dispose previous render buffers
  15340. if (textures[0]._depthStencilBuffer) {
  15341. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15342. textures[0]._depthStencilBuffer = null;
  15343. }
  15344. if (textures[0]._MSAAFramebuffer) {
  15345. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15346. textures[0]._MSAAFramebuffer = null;
  15347. }
  15348. for (var i = 0; i < textures.length; i++) {
  15349. if (textures[i]._MSAARenderBuffer) {
  15350. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15351. textures[i]._MSAARenderBuffer = null;
  15352. }
  15353. }
  15354. if (samples > 1) {
  15355. var framebuffer = gl.createFramebuffer();
  15356. if (!framebuffer) {
  15357. throw new Error("Unable to create multi sampled framebuffer");
  15358. }
  15359. this.bindUnboundFramebuffer(framebuffer);
  15360. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15361. var attachments = [];
  15362. for (var i = 0; i < textures.length; i++) {
  15363. var texture = textures[i];
  15364. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15365. var colorRenderbuffer = gl.createRenderbuffer();
  15366. if (!colorRenderbuffer) {
  15367. throw new Error("Unable to create multi sampled framebuffer");
  15368. }
  15369. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15370. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15371. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15372. texture._MSAAFramebuffer = framebuffer;
  15373. texture._MSAARenderBuffer = colorRenderbuffer;
  15374. texture.samples = samples;
  15375. texture._depthStencilBuffer = depthStencilBuffer;
  15376. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15377. attachments.push(attachment);
  15378. }
  15379. gl.drawBuffers(attachments);
  15380. }
  15381. else {
  15382. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15383. }
  15384. this.bindUnboundFramebuffer(null);
  15385. return samples;
  15386. };
  15387. /** @hidden */
  15388. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15389. if (faceIndex === void 0) { faceIndex = 0; }
  15390. if (lod === void 0) { lod = 0; }
  15391. var gl = this._gl;
  15392. var target = gl.TEXTURE_2D;
  15393. if (texture.isCube) {
  15394. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15395. }
  15396. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15397. };
  15398. /** @hidden */
  15399. Engine.prototype._uploadDataToTextureDirectly = function (texture, width, height, imageData, faceIndex, lod) {
  15400. if (faceIndex === void 0) { faceIndex = 0; }
  15401. if (lod === void 0) { lod = 0; }
  15402. var gl = this._gl;
  15403. var textureType = this._getWebGLTextureType(texture.type);
  15404. var format = this._getInternalFormat(texture.format);
  15405. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15406. this._unpackFlipY(texture.invertY);
  15407. var target = gl.TEXTURE_2D;
  15408. if (texture.isCube) {
  15409. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15410. }
  15411. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15412. };
  15413. /** @hidden */
  15414. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15415. if (faceIndex === void 0) { faceIndex = 0; }
  15416. if (lod === void 0) { lod = 0; }
  15417. var gl = this._gl;
  15418. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15419. this._bindTextureDirectly(bindTarget, texture, true);
  15420. this._uploadDataToTextureDirectly(texture, texture.width, texture.height, imageData, faceIndex, lod);
  15421. this._bindTextureDirectly(bindTarget, null, true);
  15422. };
  15423. /** @hidden */
  15424. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15425. if (faceIndex === void 0) { faceIndex = 0; }
  15426. if (lod === void 0) { lod = 0; }
  15427. var gl = this._gl;
  15428. var textureType = this._getWebGLTextureType(texture.type);
  15429. var format = this._getInternalFormat(texture.format);
  15430. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15431. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15432. this._bindTextureDirectly(bindTarget, texture, true);
  15433. this._unpackFlipY(texture.invertY);
  15434. var target = gl.TEXTURE_2D;
  15435. if (texture.isCube) {
  15436. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15437. }
  15438. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15439. this._bindTextureDirectly(bindTarget, null, true);
  15440. };
  15441. /**
  15442. * Creates a new render target cube texture
  15443. * @param size defines the size of the texture
  15444. * @param options defines the options used to create the texture
  15445. * @returns a new render target cube texture stored in an InternalTexture
  15446. */
  15447. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15448. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15449. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15450. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15451. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15452. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15453. }
  15454. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15455. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15456. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15457. }
  15458. var gl = this._gl;
  15459. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15460. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15461. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15462. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15463. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15464. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15465. }
  15466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15467. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15468. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15470. for (var face = 0; face < 6; face++) {
  15471. 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);
  15472. }
  15473. // Create the framebuffer
  15474. var framebuffer = gl.createFramebuffer();
  15475. this.bindUnboundFramebuffer(framebuffer);
  15476. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15477. // MipMaps
  15478. if (fullOptions.generateMipMaps) {
  15479. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15480. }
  15481. // Unbind
  15482. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15483. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15484. this.bindUnboundFramebuffer(null);
  15485. texture._framebuffer = framebuffer;
  15486. texture.width = size;
  15487. texture.height = size;
  15488. texture.isReady = true;
  15489. texture.isCube = true;
  15490. texture.samples = 1;
  15491. texture.generateMipMaps = fullOptions.generateMipMaps;
  15492. texture.samplingMode = fullOptions.samplingMode;
  15493. texture.type = fullOptions.type;
  15494. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15495. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15496. this._internalTexturesCache.push(texture);
  15497. return texture;
  15498. };
  15499. /**
  15500. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15501. * @param rootUrl defines the url where the file to load is located
  15502. * @param scene defines the current scene
  15503. * @param lodScale defines scale to apply to the mip map selection
  15504. * @param lodOffset defines offset to apply to the mip map selection
  15505. * @param onLoad defines an optional callback raised when the texture is loaded
  15506. * @param onError defines an optional callback raised if there is an issue to load the texture
  15507. * @param format defines the format of the data
  15508. * @param forcedExtension defines the extension to use to pick the right loader
  15509. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15510. * @returns the cube texture as an InternalTexture
  15511. */
  15512. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15513. var _this = this;
  15514. if (onLoad === void 0) { onLoad = null; }
  15515. if (onError === void 0) { onError = null; }
  15516. if (forcedExtension === void 0) { forcedExtension = null; }
  15517. if (createPolynomials === void 0) { createPolynomials = true; }
  15518. var callback = function (loadData) {
  15519. if (!loadData) {
  15520. if (onLoad) {
  15521. onLoad(null);
  15522. }
  15523. return;
  15524. }
  15525. var texture = loadData.texture;
  15526. if (!createPolynomials) {
  15527. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15528. }
  15529. else if (loadData.info.sphericalPolynomial) {
  15530. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15531. }
  15532. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15533. if (_this._caps.textureLOD) {
  15534. // Do not add extra process if texture lod is supported.
  15535. if (onLoad) {
  15536. onLoad(texture);
  15537. }
  15538. return;
  15539. }
  15540. var mipSlices = 3;
  15541. var gl = _this._gl;
  15542. var width = loadData.width;
  15543. if (!width) {
  15544. return;
  15545. }
  15546. var textures = [];
  15547. for (var i = 0; i < mipSlices; i++) {
  15548. //compute LOD from even spacing in smoothness (matching shader calculation)
  15549. var smoothness = i / (mipSlices - 1);
  15550. var roughness = 1 - smoothness;
  15551. var minLODIndex = lodOffset; // roughness = 0
  15552. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15553. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15554. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15555. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15556. glTextureFromLod.isCube = true;
  15557. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15560. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15561. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15562. if (loadData.isDDS) {
  15563. var info = loadData.info;
  15564. var data = loadData.data;
  15565. _this._unpackFlipY(info.isCompressed);
  15566. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, true, 6, mipmapIndex);
  15567. }
  15568. else {
  15569. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15570. }
  15571. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15572. // Wrap in a base texture for easy binding.
  15573. var lodTexture = new BABYLON.BaseTexture(scene);
  15574. lodTexture.isCube = true;
  15575. lodTexture._texture = glTextureFromLod;
  15576. glTextureFromLod.isReady = true;
  15577. textures.push(lodTexture);
  15578. }
  15579. texture._lodTextureHigh = textures[2];
  15580. texture._lodTextureMid = textures[1];
  15581. texture._lodTextureLow = textures[0];
  15582. if (onLoad) {
  15583. onLoad(texture);
  15584. }
  15585. };
  15586. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15587. };
  15588. /**
  15589. * Creates a cube texture
  15590. * @param rootUrl defines the url where the files to load is located
  15591. * @param scene defines the current scene
  15592. * @param files defines the list of files to load (1 per face)
  15593. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15594. * @param onLoad defines an optional callback raised when the texture is loaded
  15595. * @param onError defines an optional callback raised if there is an issue to load the texture
  15596. * @param format defines the format of the data
  15597. * @param forcedExtension defines the extension to use to pick the right loader
  15598. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15599. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15600. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15601. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15602. * @returns the cube texture as an InternalTexture
  15603. */
  15604. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15605. var _this = this;
  15606. if (onLoad === void 0) { onLoad = null; }
  15607. if (onError === void 0) { onError = null; }
  15608. if (forcedExtension === void 0) { forcedExtension = null; }
  15609. if (createPolynomials === void 0) { createPolynomials = false; }
  15610. if (lodScale === void 0) { lodScale = 0; }
  15611. if (lodOffset === void 0) { lodOffset = 0; }
  15612. if (fallback === void 0) { fallback = null; }
  15613. var gl = this._gl;
  15614. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15615. texture.isCube = true;
  15616. texture.url = rootUrl;
  15617. texture.generateMipMaps = !noMipmap;
  15618. texture._lodGenerationScale = lodScale;
  15619. texture._lodGenerationOffset = lodOffset;
  15620. if (!this._doNotHandleContextLost) {
  15621. texture._extension = forcedExtension;
  15622. texture._files = files;
  15623. }
  15624. var isKTX = false;
  15625. var isDDS = false;
  15626. var isEnv = false;
  15627. var lastDot = rootUrl.lastIndexOf('.');
  15628. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15629. if (this._textureFormatInUse && !fallback) {
  15630. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15631. isKTX = true;
  15632. }
  15633. else {
  15634. isDDS = (extension === ".dds");
  15635. isEnv = (extension === ".env");
  15636. }
  15637. var onerror = function (request, exception) {
  15638. if (isKTX) {
  15639. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15640. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15641. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15642. }
  15643. if (onError && request) {
  15644. onError(request.status + " " + request.statusText, exception);
  15645. }
  15646. };
  15647. if (isKTX) {
  15648. this._loadFile(rootUrl, function (data) {
  15649. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15650. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15651. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15652. _this._unpackFlipY(true);
  15653. ktx.uploadLevels(texture, !noMipmap);
  15654. _this.setCubeMapTextureParams(gl, loadMipmap);
  15655. texture.width = ktx.pixelWidth;
  15656. texture.height = ktx.pixelHeight;
  15657. texture.isReady = true;
  15658. }, undefined, undefined, true, onerror);
  15659. }
  15660. else if (isEnv) {
  15661. this._loadFile(rootUrl, function (data) {
  15662. data = data;
  15663. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15664. if (info) {
  15665. texture.width = info.width;
  15666. texture.height = info.width;
  15667. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  15668. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  15669. texture.isReady = true;
  15670. if (onLoad) {
  15671. onLoad();
  15672. }
  15673. });
  15674. }
  15675. else if (onError) {
  15676. onError("Can not parse the environment file", null);
  15677. }
  15678. }, undefined, undefined, true, onerror);
  15679. }
  15680. else if (isDDS) {
  15681. if (files && files.length === 6) {
  15682. this._cascadeLoadFiles(scene, function (imgs) {
  15683. var info;
  15684. var loadMipmap = false;
  15685. var width = 0;
  15686. for (var index = 0; index < imgs.length; index++) {
  15687. var data = imgs[index];
  15688. info = BABYLON.DDSTools.GetDDSInfo(data);
  15689. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15690. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15691. _this._unpackFlipY(info.isCompressed);
  15692. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6, -1, index);
  15693. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15694. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15695. }
  15696. texture.width = info.width;
  15697. texture.height = info.height;
  15698. texture.type = info.textureType;
  15699. width = info.width;
  15700. }
  15701. _this.setCubeMapTextureParams(gl, loadMipmap);
  15702. texture.isReady = true;
  15703. if (onLoad) {
  15704. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15705. }
  15706. }, files, onError);
  15707. }
  15708. else {
  15709. this._loadFile(rootUrl, function (data) {
  15710. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15711. if (createPolynomials) {
  15712. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15713. }
  15714. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15715. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15716. _this._unpackFlipY(info.isCompressed);
  15717. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6);
  15718. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15719. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15720. }
  15721. _this.setCubeMapTextureParams(gl, loadMipmap);
  15722. texture.width = info.width;
  15723. texture.height = info.height;
  15724. texture.isReady = true;
  15725. texture.type = info.textureType;
  15726. if (onLoad) {
  15727. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15728. }
  15729. }, undefined, undefined, true, onerror);
  15730. }
  15731. }
  15732. else {
  15733. if (!files) {
  15734. throw new Error("Cannot load cubemap because files were not defined");
  15735. }
  15736. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15737. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15738. var height = width;
  15739. _this._prepareWorkingCanvas();
  15740. if (!_this._workingCanvas || !_this._workingContext) {
  15741. return;
  15742. }
  15743. _this._workingCanvas.width = width;
  15744. _this._workingCanvas.height = height;
  15745. var faces = [
  15746. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15747. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15748. ];
  15749. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15750. _this._unpackFlipY(false);
  15751. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15752. for (var index = 0; index < faces.length; index++) {
  15753. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15754. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15755. }
  15756. if (!noMipmap) {
  15757. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15758. }
  15759. _this.setCubeMapTextureParams(gl, !noMipmap);
  15760. texture.width = width;
  15761. texture.height = height;
  15762. texture.isReady = true;
  15763. if (format) {
  15764. texture.format = format;
  15765. }
  15766. texture.onLoadedObservable.notifyObservers(texture);
  15767. texture.onLoadedObservable.clear();
  15768. if (onLoad) {
  15769. onLoad();
  15770. }
  15771. }, files, onError);
  15772. }
  15773. this._internalTexturesCache.push(texture);
  15774. return texture;
  15775. };
  15776. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15781. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15782. // this.resetTextureCache();
  15783. };
  15784. /**
  15785. * Update a raw cube texture
  15786. * @param texture defines the texture to udpdate
  15787. * @param data defines the data to store
  15788. * @param format defines the data format
  15789. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15790. * @param invertY defines if data must be stored with Y axis inverted
  15791. * @param compression defines the compression used (null by default)
  15792. * @param level defines which level of the texture to update
  15793. */
  15794. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15795. if (compression === void 0) { compression = null; }
  15796. if (level === void 0) { level = 0; }
  15797. texture._bufferViewArray = data;
  15798. texture.format = format;
  15799. texture.type = type;
  15800. texture.invertY = invertY;
  15801. texture._compression = compression;
  15802. var gl = this._gl;
  15803. var textureType = this._getWebGLTextureType(type);
  15804. var internalFormat = this._getInternalFormat(format);
  15805. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15806. var needConversion = false;
  15807. if (internalFormat === gl.RGB) {
  15808. internalFormat = gl.RGBA;
  15809. needConversion = true;
  15810. }
  15811. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15812. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15813. if (texture.width % 4 !== 0) {
  15814. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15815. }
  15816. // Data are known to be in +X +Y +Z -X -Y -Z
  15817. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15818. var faceData = data[faceIndex];
  15819. if (compression) {
  15820. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15821. }
  15822. else {
  15823. if (needConversion) {
  15824. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15825. }
  15826. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15827. }
  15828. }
  15829. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15830. if (isPot && texture.generateMipMaps && level === 0) {
  15831. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15832. }
  15833. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15834. // this.resetTextureCache();
  15835. texture.isReady = true;
  15836. };
  15837. /**
  15838. * Creates a new raw cube texture
  15839. * @param data defines the array of data to use to create each face
  15840. * @param size defines the size of the textures
  15841. * @param format defines the format of the data
  15842. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15843. * @param generateMipMaps defines if the engine should generate the mip levels
  15844. * @param invertY defines if data must be stored with Y axis inverted
  15845. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15846. * @param compression defines the compression used (null by default)
  15847. * @returns the cube texture as an InternalTexture
  15848. */
  15849. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15850. if (compression === void 0) { compression = null; }
  15851. var gl = this._gl;
  15852. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15853. texture.isCube = true;
  15854. texture.generateMipMaps = generateMipMaps;
  15855. texture.format = format;
  15856. texture.type = type;
  15857. if (!this._doNotHandleContextLost) {
  15858. texture._bufferViewArray = data;
  15859. }
  15860. var textureType = this._getWebGLTextureType(type);
  15861. var internalFormat = this._getInternalFormat(format);
  15862. if (internalFormat === gl.RGB) {
  15863. internalFormat = gl.RGBA;
  15864. }
  15865. var width = size;
  15866. var height = width;
  15867. texture.width = width;
  15868. texture.height = height;
  15869. // Double check on POT to generate Mips.
  15870. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15871. if (!isPot) {
  15872. generateMipMaps = false;
  15873. }
  15874. // Upload data if needed. The texture won't be ready until then.
  15875. if (data) {
  15876. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15877. }
  15878. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15879. // Filters
  15880. if (data && generateMipMaps) {
  15881. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15882. }
  15883. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15886. }
  15887. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15888. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15889. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15890. }
  15891. else {
  15892. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15894. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15895. }
  15896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15898. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15899. return texture;
  15900. };
  15901. /**
  15902. * Creates a new raw cube texture from a specified url
  15903. * @param url defines the url where the data is located
  15904. * @param scene defines the current scene
  15905. * @param size defines the size of the textures
  15906. * @param format defines the format of the data
  15907. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15908. * @param noMipmap defines if the engine should avoid generating the mip levels
  15909. * @param callback defines a callback used to extract texture data from loaded data
  15910. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15911. * @param onLoad defines a callback called when texture is loaded
  15912. * @param onError defines a callback called if there is an error
  15913. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15914. * @param invertY defines if data must be stored with Y axis inverted
  15915. * @returns the cube texture as an InternalTexture
  15916. */
  15917. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15918. var _this = this;
  15919. if (onLoad === void 0) { onLoad = null; }
  15920. if (onError === void 0) { onError = null; }
  15921. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15922. if (invertY === void 0) { invertY = false; }
  15923. var gl = this._gl;
  15924. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15925. scene._addPendingData(texture);
  15926. texture.url = url;
  15927. this._internalTexturesCache.push(texture);
  15928. var onerror = function (request, exception) {
  15929. scene._removePendingData(texture);
  15930. if (onError && request) {
  15931. onError(request.status + " " + request.statusText, exception);
  15932. }
  15933. };
  15934. var internalCallback = function (data) {
  15935. var width = texture.width;
  15936. var faceDataArrays = callback(data);
  15937. if (!faceDataArrays) {
  15938. return;
  15939. }
  15940. if (mipmapGenerator) {
  15941. var textureType = _this._getWebGLTextureType(type);
  15942. var internalFormat = _this._getInternalFormat(format);
  15943. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15944. var needConversion = false;
  15945. if (internalFormat === gl.RGB) {
  15946. internalFormat = gl.RGBA;
  15947. needConversion = true;
  15948. }
  15949. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15950. _this._unpackFlipY(false);
  15951. var mipData = mipmapGenerator(faceDataArrays);
  15952. for (var level = 0; level < mipData.length; level++) {
  15953. var mipSize = width >> level;
  15954. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15955. var mipFaceData = mipData[level][faceIndex];
  15956. if (needConversion) {
  15957. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15958. }
  15959. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15960. }
  15961. }
  15962. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15963. }
  15964. else {
  15965. texture.generateMipMaps = !noMipmap;
  15966. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15967. }
  15968. texture.isReady = true;
  15969. // this.resetTextureCache();
  15970. scene._removePendingData(texture);
  15971. if (onLoad) {
  15972. onLoad();
  15973. }
  15974. };
  15975. this._loadFile(url, function (data) {
  15976. internalCallback(data);
  15977. }, undefined, scene.database, true, onerror);
  15978. return texture;
  15979. };
  15980. ;
  15981. /**
  15982. * Update a raw 3D texture
  15983. * @param texture defines the texture to update
  15984. * @param data defines the data to store
  15985. * @param format defines the data format
  15986. * @param invertY defines if data must be stored with Y axis inverted
  15987. * @param compression defines the used compression (can be null)
  15988. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15989. */
  15990. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15991. if (compression === void 0) { compression = null; }
  15992. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15993. var internalType = this._getWebGLTextureType(textureType);
  15994. var internalFormat = this._getInternalFormat(format);
  15995. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15996. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15997. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15998. if (!this._doNotHandleContextLost) {
  15999. texture._bufferView = data;
  16000. texture.format = format;
  16001. texture.invertY = invertY;
  16002. texture._compression = compression;
  16003. }
  16004. if (texture.width % 4 !== 0) {
  16005. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16006. }
  16007. if (compression && data) {
  16008. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16009. }
  16010. else {
  16011. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16012. }
  16013. if (texture.generateMipMaps) {
  16014. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16015. }
  16016. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16017. // this.resetTextureCache();
  16018. texture.isReady = true;
  16019. };
  16020. /**
  16021. * Creates a new raw 3D texture
  16022. * @param data defines the data used to create the texture
  16023. * @param width defines the width of the texture
  16024. * @param height defines the height of the texture
  16025. * @param depth defines the depth of the texture
  16026. * @param format defines the format of the texture
  16027. * @param generateMipMaps defines if the engine must generate mip levels
  16028. * @param invertY defines if data must be stored with Y axis inverted
  16029. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16030. * @param compression defines the compressed used (can be null)
  16031. * @param textureType defines the compressed used (can be null)
  16032. * @returns a new raw 3D texture (stored in an InternalTexture)
  16033. */
  16034. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16035. if (compression === void 0) { compression = null; }
  16036. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16037. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16038. texture.baseWidth = width;
  16039. texture.baseHeight = height;
  16040. texture.baseDepth = depth;
  16041. texture.width = width;
  16042. texture.height = height;
  16043. texture.depth = depth;
  16044. texture.format = format;
  16045. texture.type = textureType;
  16046. texture.generateMipMaps = generateMipMaps;
  16047. texture.samplingMode = samplingMode;
  16048. texture.is3D = true;
  16049. if (!this._doNotHandleContextLost) {
  16050. texture._bufferView = data;
  16051. }
  16052. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16053. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16054. // Filters
  16055. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16056. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16057. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16058. if (generateMipMaps) {
  16059. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16060. }
  16061. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16062. this._internalTexturesCache.push(texture);
  16063. return texture;
  16064. };
  16065. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16066. var gl = this._gl;
  16067. if (!gl) {
  16068. return;
  16069. }
  16070. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16071. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16072. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16073. if (!noMipmap && !isCompressed) {
  16074. gl.generateMipmap(gl.TEXTURE_2D);
  16075. }
  16076. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16077. // this.resetTextureCache();
  16078. if (scene) {
  16079. scene._removePendingData(texture);
  16080. }
  16081. texture.onLoadedObservable.notifyObservers(texture);
  16082. texture.onLoadedObservable.clear();
  16083. };
  16084. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16085. var _this = this;
  16086. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16087. var maxTextureSize = this.getCaps().maxTextureSize;
  16088. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16089. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16090. var gl = this._gl;
  16091. if (!gl) {
  16092. return;
  16093. }
  16094. if (!texture._webGLTexture) {
  16095. // this.resetTextureCache();
  16096. if (scene) {
  16097. scene._removePendingData(texture);
  16098. }
  16099. return;
  16100. }
  16101. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16102. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16103. texture.baseWidth = width;
  16104. texture.baseHeight = height;
  16105. texture.width = potWidth;
  16106. texture.height = potHeight;
  16107. texture.isReady = true;
  16108. if (processFunction(potWidth, potHeight, function () {
  16109. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16110. })) {
  16111. // Returning as texture needs extra async steps
  16112. return;
  16113. }
  16114. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16115. };
  16116. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16117. // Create new RGBA data container.
  16118. var rgbaData;
  16119. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16120. rgbaData = new Float32Array(width * height * 4);
  16121. }
  16122. else {
  16123. rgbaData = new Uint32Array(width * height * 4);
  16124. }
  16125. // Convert each pixel.
  16126. for (var x = 0; x < width; x++) {
  16127. for (var y = 0; y < height; y++) {
  16128. var index = (y * width + x) * 3;
  16129. var newIndex = (y * width + x) * 4;
  16130. // Map Old Value to new value.
  16131. rgbaData[newIndex + 0] = rgbData[index + 0];
  16132. rgbaData[newIndex + 1] = rgbData[index + 1];
  16133. rgbaData[newIndex + 2] = rgbData[index + 2];
  16134. // Add fully opaque alpha channel.
  16135. rgbaData[newIndex + 3] = 1;
  16136. }
  16137. }
  16138. return rgbaData;
  16139. };
  16140. /** @hidden */
  16141. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16142. var gl = this._gl;
  16143. if (texture._framebuffer) {
  16144. gl.deleteFramebuffer(texture._framebuffer);
  16145. texture._framebuffer = null;
  16146. }
  16147. if (texture._depthStencilBuffer) {
  16148. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16149. texture._depthStencilBuffer = null;
  16150. }
  16151. if (texture._MSAAFramebuffer) {
  16152. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16153. texture._MSAAFramebuffer = null;
  16154. }
  16155. if (texture._MSAARenderBuffer) {
  16156. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16157. texture._MSAARenderBuffer = null;
  16158. }
  16159. };
  16160. /** @hidden */
  16161. Engine.prototype._releaseTexture = function (texture) {
  16162. var gl = this._gl;
  16163. this._releaseFramebufferObjects(texture);
  16164. gl.deleteTexture(texture._webGLTexture);
  16165. // Unbind channels
  16166. this.unbindAllTextures();
  16167. var index = this._internalTexturesCache.indexOf(texture);
  16168. if (index !== -1) {
  16169. this._internalTexturesCache.splice(index, 1);
  16170. }
  16171. // Integrated fixed lod samplers.
  16172. if (texture._lodTextureHigh) {
  16173. texture._lodTextureHigh.dispose();
  16174. }
  16175. if (texture._lodTextureMid) {
  16176. texture._lodTextureMid.dispose();
  16177. }
  16178. if (texture._lodTextureLow) {
  16179. texture._lodTextureLow.dispose();
  16180. }
  16181. // Set output texture of post process to null if the texture has been released/disposed
  16182. this.scenes.forEach(function (scene) {
  16183. scene.postProcesses.forEach(function (postProcess) {
  16184. if (postProcess._outputTexture == texture) {
  16185. postProcess._outputTexture = null;
  16186. }
  16187. });
  16188. scene.cameras.forEach(function (camera) {
  16189. camera._postProcesses.forEach(function (postProcess) {
  16190. if (postProcess) {
  16191. if (postProcess._outputTexture == texture) {
  16192. postProcess._outputTexture = null;
  16193. }
  16194. }
  16195. });
  16196. });
  16197. });
  16198. };
  16199. Engine.prototype.setProgram = function (program) {
  16200. if (this._currentProgram !== program) {
  16201. this._gl.useProgram(program);
  16202. this._currentProgram = program;
  16203. }
  16204. };
  16205. /**
  16206. * Binds an effect to the webGL context
  16207. * @param effect defines the effect to bind
  16208. */
  16209. Engine.prototype.bindSamplers = function (effect) {
  16210. this.setProgram(effect.getProgram());
  16211. var samplers = effect.getSamplers();
  16212. for (var index = 0; index < samplers.length; index++) {
  16213. var uniform = effect.getUniform(samplers[index]);
  16214. if (uniform) {
  16215. this._boundUniforms[index] = uniform;
  16216. }
  16217. }
  16218. this._currentEffect = null;
  16219. };
  16220. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16221. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16222. return;
  16223. }
  16224. // Remove
  16225. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16226. // Bind last to it
  16227. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16228. // Bind to dummy
  16229. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16230. };
  16231. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16232. if (!internalTexture) {
  16233. return -1;
  16234. }
  16235. internalTexture._initialSlot = channel;
  16236. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16237. if (channel !== internalTexture._designatedSlot) {
  16238. this._textureCollisions.addCount(1, false);
  16239. }
  16240. }
  16241. else {
  16242. if (channel !== internalTexture._designatedSlot) {
  16243. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16244. return internalTexture._designatedSlot;
  16245. }
  16246. else {
  16247. // No slot for this texture, let's pick a new one (if we find a free slot)
  16248. if (this._nextFreeTextureSlots.length) {
  16249. return this._nextFreeTextureSlots[0];
  16250. }
  16251. // We need to recycle the oldest bound texture, sorry.
  16252. this._textureCollisions.addCount(1, false);
  16253. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16254. }
  16255. }
  16256. }
  16257. return channel;
  16258. };
  16259. Engine.prototype._linkTrackers = function (previous, next) {
  16260. previous.next = next;
  16261. next.previous = previous;
  16262. };
  16263. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16264. var currentSlot = internalTexture._designatedSlot;
  16265. if (currentSlot === -1) {
  16266. return -1;
  16267. }
  16268. internalTexture._designatedSlot = -1;
  16269. if (this.disableTextureBindingOptimization) {
  16270. return -1;
  16271. }
  16272. // Remove from bound list
  16273. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16274. // Free the slot
  16275. this._boundTexturesCache[currentSlot] = null;
  16276. this._nextFreeTextureSlots.push(currentSlot);
  16277. return currentSlot;
  16278. };
  16279. Engine.prototype._activateCurrentTexture = function () {
  16280. if (this._currentTextureChannel !== this._activeChannel) {
  16281. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16282. this._currentTextureChannel = this._activeChannel;
  16283. }
  16284. };
  16285. /** @hidden */
  16286. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16287. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16288. if (force === void 0) { force = false; }
  16289. var wasPreviouslyBound = false;
  16290. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16291. this._activeChannel = texture._designatedSlot;
  16292. }
  16293. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16294. var isTextureForRendering = texture && texture._initialSlot > -1;
  16295. if (currentTextureBound !== texture || force) {
  16296. if (currentTextureBound) {
  16297. this._removeDesignatedSlot(currentTextureBound);
  16298. }
  16299. this._activateCurrentTexture();
  16300. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16301. this._boundTexturesCache[this._activeChannel] = texture;
  16302. if (texture) {
  16303. if (!this.disableTextureBindingOptimization) {
  16304. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16305. if (slotIndex > -1) {
  16306. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16307. }
  16308. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16309. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16310. }
  16311. texture._designatedSlot = this._activeChannel;
  16312. }
  16313. }
  16314. else if (forTextureDataUpdate) {
  16315. wasPreviouslyBound = true;
  16316. this._activateCurrentTexture();
  16317. }
  16318. if (isTextureForRendering && !forTextureDataUpdate) {
  16319. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16320. }
  16321. return wasPreviouslyBound;
  16322. };
  16323. /** @hidden */
  16324. Engine.prototype._bindTexture = function (channel, texture) {
  16325. if (channel < 0) {
  16326. return;
  16327. }
  16328. if (texture) {
  16329. channel = this._getCorrectTextureChannel(channel, texture);
  16330. }
  16331. this._activeChannel = channel;
  16332. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16333. };
  16334. /**
  16335. * Sets a texture to the webGL context from a postprocess
  16336. * @param channel defines the channel to use
  16337. * @param postProcess defines the source postprocess
  16338. */
  16339. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16340. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16341. };
  16342. /**
  16343. * Binds the output of the passed in post process to the texture channel specified
  16344. * @param channel The channel the texture should be bound to
  16345. * @param postProcess The post process which's output should be bound
  16346. */
  16347. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16348. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16349. };
  16350. /**
  16351. * Unbind all textures from the webGL context
  16352. */
  16353. Engine.prototype.unbindAllTextures = function () {
  16354. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16355. this._activeChannel = channel;
  16356. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16357. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16358. if (this.webGLVersion > 1) {
  16359. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16360. }
  16361. }
  16362. };
  16363. /**
  16364. * Sets a texture to the according uniform.
  16365. * @param channel The texture channel
  16366. * @param uniform The uniform to set
  16367. * @param texture The texture to apply
  16368. */
  16369. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16370. if (channel < 0) {
  16371. return;
  16372. }
  16373. if (uniform) {
  16374. this._boundUniforms[channel] = uniform;
  16375. }
  16376. this._setTexture(channel, texture);
  16377. };
  16378. /**
  16379. * Sets a depth stencil texture from a render target to the according uniform.
  16380. * @param channel The texture channel
  16381. * @param uniform The uniform to set
  16382. * @param texture The render target texture containing the depth stencil texture to apply
  16383. */
  16384. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16385. if (channel < 0) {
  16386. return;
  16387. }
  16388. if (uniform) {
  16389. this._boundUniforms[channel] = uniform;
  16390. }
  16391. if (!texture || !texture.depthStencilTexture) {
  16392. this._setTexture(channel, null);
  16393. }
  16394. else {
  16395. this._setTexture(channel, texture, false, true);
  16396. }
  16397. };
  16398. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16399. var uniform = this._boundUniforms[sourceSlot];
  16400. if (uniform._currentState === destination) {
  16401. return;
  16402. }
  16403. this._gl.uniform1i(uniform, destination);
  16404. uniform._currentState = destination;
  16405. };
  16406. Engine.prototype._getTextureWrapMode = function (mode) {
  16407. switch (mode) {
  16408. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16409. return this._gl.REPEAT;
  16410. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16411. return this._gl.CLAMP_TO_EDGE;
  16412. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16413. return this._gl.MIRRORED_REPEAT;
  16414. }
  16415. return this._gl.REPEAT;
  16416. };
  16417. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16418. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16419. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16420. // Not ready?
  16421. if (!texture) {
  16422. if (this._boundTexturesCache[channel] != null) {
  16423. this._activeChannel = channel;
  16424. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16425. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16426. if (this.webGLVersion > 1) {
  16427. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16428. }
  16429. }
  16430. return false;
  16431. }
  16432. // Video
  16433. if (texture.video) {
  16434. this._activeChannel = channel;
  16435. texture.update();
  16436. }
  16437. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16438. texture.delayLoad();
  16439. return false;
  16440. }
  16441. var internalTexture;
  16442. if (depthStencilTexture) {
  16443. internalTexture = texture.depthStencilTexture;
  16444. }
  16445. else if (texture.isReady()) {
  16446. internalTexture = texture.getInternalTexture();
  16447. }
  16448. else if (texture.isCube) {
  16449. internalTexture = this.emptyCubeTexture;
  16450. }
  16451. else if (texture.is3D) {
  16452. internalTexture = this.emptyTexture3D;
  16453. }
  16454. else {
  16455. internalTexture = this.emptyTexture;
  16456. }
  16457. if (!isPartOfTextureArray) {
  16458. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16459. }
  16460. var needToBind = true;
  16461. if (this._boundTexturesCache[channel] === internalTexture) {
  16462. this._moveBoundTextureOnTop(internalTexture);
  16463. if (!isPartOfTextureArray) {
  16464. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16465. }
  16466. needToBind = false;
  16467. }
  16468. this._activeChannel = channel;
  16469. if (internalTexture && internalTexture.is3D) {
  16470. if (needToBind) {
  16471. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16472. }
  16473. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16474. internalTexture._cachedWrapU = texture.wrapU;
  16475. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16476. }
  16477. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16478. internalTexture._cachedWrapV = texture.wrapV;
  16479. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16480. }
  16481. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16482. internalTexture._cachedWrapR = texture.wrapR;
  16483. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16484. }
  16485. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16486. }
  16487. else if (internalTexture && internalTexture.isCube) {
  16488. if (needToBind) {
  16489. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16490. }
  16491. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16492. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16493. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16494. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16495. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16496. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16497. }
  16498. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16499. }
  16500. else {
  16501. if (needToBind) {
  16502. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16503. }
  16504. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16505. internalTexture._cachedWrapU = texture.wrapU;
  16506. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16507. }
  16508. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16509. internalTexture._cachedWrapV = texture.wrapV;
  16510. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16511. }
  16512. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16513. }
  16514. return true;
  16515. };
  16516. /**
  16517. * Sets an array of texture to the webGL context
  16518. * @param channel defines the channel where the texture array must be set
  16519. * @param uniform defines the associated uniform location
  16520. * @param textures defines the array of textures to bind
  16521. */
  16522. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16523. if (channel < 0 || !uniform) {
  16524. return;
  16525. }
  16526. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16527. this._textureUnits = new Int32Array(textures.length);
  16528. }
  16529. for (var i = 0; i < textures.length; i++) {
  16530. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16531. }
  16532. this._gl.uniform1iv(uniform, this._textureUnits);
  16533. for (var index = 0; index < textures.length; index++) {
  16534. this._setTexture(this._textureUnits[index], textures[index], true);
  16535. }
  16536. };
  16537. /** @hidden */
  16538. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16539. var internalTexture = texture.getInternalTexture();
  16540. if (!internalTexture) {
  16541. return;
  16542. }
  16543. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16544. var value = texture.anisotropicFilteringLevel;
  16545. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16546. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16547. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16548. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16549. }
  16550. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16551. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16552. internalTexture._cachedAnisotropicFilteringLevel = value;
  16553. }
  16554. };
  16555. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16556. this._bindTextureDirectly(target, texture, true, true);
  16557. this._gl.texParameterf(target, parameter, value);
  16558. };
  16559. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16560. if (texture) {
  16561. this._bindTextureDirectly(target, texture, true, true);
  16562. }
  16563. this._gl.texParameteri(target, parameter, value);
  16564. };
  16565. /**
  16566. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16567. * @param x defines the x coordinate of the rectangle where pixels must be read
  16568. * @param y defines the y coordinate of the rectangle where pixels must be read
  16569. * @param width defines the width of the rectangle where pixels must be read
  16570. * @param height defines the height of the rectangle where pixels must be read
  16571. * @returns a Uint8Array containing RGBA colors
  16572. */
  16573. Engine.prototype.readPixels = function (x, y, width, height) {
  16574. var data = new Uint8Array(height * width * 4);
  16575. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16576. return data;
  16577. };
  16578. /**
  16579. * Add an externaly attached data from its key.
  16580. * This method call will fail and return false, if such key already exists.
  16581. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16582. * @param key the unique key that identifies the data
  16583. * @param data the data object to associate to the key for this Engine instance
  16584. * @return true if no such key were already present and the data was added successfully, false otherwise
  16585. */
  16586. Engine.prototype.addExternalData = function (key, data) {
  16587. if (!this._externalData) {
  16588. this._externalData = new BABYLON.StringDictionary();
  16589. }
  16590. return this._externalData.add(key, data);
  16591. };
  16592. /**
  16593. * Get an externaly attached data from its key
  16594. * @param key the unique key that identifies the data
  16595. * @return the associated data, if present (can be null), or undefined if not present
  16596. */
  16597. Engine.prototype.getExternalData = function (key) {
  16598. if (!this._externalData) {
  16599. this._externalData = new BABYLON.StringDictionary();
  16600. }
  16601. return this._externalData.get(key);
  16602. };
  16603. /**
  16604. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16605. * @param key the unique key that identifies the data
  16606. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16607. * @return the associated data, can be null if the factory returned null.
  16608. */
  16609. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16610. if (!this._externalData) {
  16611. this._externalData = new BABYLON.StringDictionary();
  16612. }
  16613. return this._externalData.getOrAddWithFactory(key, factory);
  16614. };
  16615. /**
  16616. * Remove an externaly attached data from the Engine instance
  16617. * @param key the unique key that identifies the data
  16618. * @return true if the data was successfully removed, false if it doesn't exist
  16619. */
  16620. Engine.prototype.removeExternalData = function (key) {
  16621. if (!this._externalData) {
  16622. this._externalData = new BABYLON.StringDictionary();
  16623. }
  16624. return this._externalData.remove(key);
  16625. };
  16626. /**
  16627. * Unbind all vertex attributes from the webGL context
  16628. */
  16629. Engine.prototype.unbindAllAttributes = function () {
  16630. if (this._mustWipeVertexAttributes) {
  16631. this._mustWipeVertexAttributes = false;
  16632. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16633. this._gl.disableVertexAttribArray(i);
  16634. this._vertexAttribArraysEnabled[i] = false;
  16635. this._currentBufferPointers[i].active = false;
  16636. }
  16637. return;
  16638. }
  16639. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16640. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16641. continue;
  16642. }
  16643. this._gl.disableVertexAttribArray(i);
  16644. this._vertexAttribArraysEnabled[i] = false;
  16645. this._currentBufferPointers[i].active = false;
  16646. }
  16647. };
  16648. /**
  16649. * 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
  16650. */
  16651. Engine.prototype.releaseEffects = function () {
  16652. for (var name in this._compiledEffects) {
  16653. this._deleteProgram(this._compiledEffects[name]._program);
  16654. }
  16655. this._compiledEffects = {};
  16656. };
  16657. /**
  16658. * Dispose and release all associated resources
  16659. */
  16660. Engine.prototype.dispose = function () {
  16661. this.hideLoadingUI();
  16662. this.stopRenderLoop();
  16663. // Release postProcesses
  16664. while (this.postProcesses.length) {
  16665. this.postProcesses[0].dispose();
  16666. }
  16667. // Empty texture
  16668. if (this._emptyTexture) {
  16669. this._releaseTexture(this._emptyTexture);
  16670. this._emptyTexture = null;
  16671. }
  16672. if (this._emptyCubeTexture) {
  16673. this._releaseTexture(this._emptyCubeTexture);
  16674. this._emptyCubeTexture = null;
  16675. }
  16676. // Rescale PP
  16677. if (this._rescalePostProcess) {
  16678. this._rescalePostProcess.dispose();
  16679. }
  16680. // Release scenes
  16681. while (this.scenes.length) {
  16682. this.scenes[0].dispose();
  16683. }
  16684. // Release audio engine
  16685. if (Engine.audioEngine) {
  16686. Engine.audioEngine.dispose();
  16687. }
  16688. // Release effects
  16689. this.releaseEffects();
  16690. // Unbind
  16691. this.unbindAllAttributes();
  16692. this._boundUniforms = [];
  16693. if (this._dummyFramebuffer) {
  16694. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16695. }
  16696. //WebVR
  16697. this.disableVR();
  16698. // Events
  16699. if (BABYLON.Tools.IsWindowObjectExist()) {
  16700. window.removeEventListener("blur", this._onBlur);
  16701. window.removeEventListener("focus", this._onFocus);
  16702. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16703. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16704. if (this._renderingCanvas) {
  16705. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16706. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16707. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16708. if (!this._doNotHandleContextLost) {
  16709. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16710. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16711. }
  16712. }
  16713. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16714. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16715. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16716. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16717. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16718. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16719. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16720. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16721. if (this._onVrDisplayConnect) {
  16722. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16723. if (this._onVrDisplayDisconnect) {
  16724. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16725. }
  16726. if (this._onVrDisplayPresentChange) {
  16727. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16728. }
  16729. this._onVrDisplayConnect = null;
  16730. this._onVrDisplayDisconnect = null;
  16731. }
  16732. }
  16733. // Remove from Instances
  16734. var index = Engine.Instances.indexOf(this);
  16735. if (index >= 0) {
  16736. Engine.Instances.splice(index, 1);
  16737. }
  16738. this._workingCanvas = null;
  16739. this._workingContext = null;
  16740. this._currentBufferPointers = [];
  16741. this._renderingCanvas = null;
  16742. this._currentProgram = null;
  16743. this._bindedRenderFunction = null;
  16744. this.onResizeObservable.clear();
  16745. this.onCanvasBlurObservable.clear();
  16746. this.onCanvasFocusObservable.clear();
  16747. this.onCanvasPointerOutObservable.clear();
  16748. this.onBeginFrameObservable.clear();
  16749. this.onEndFrameObservable.clear();
  16750. BABYLON.Effect.ResetCache();
  16751. // Abort active requests
  16752. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16753. var request = _a[_i];
  16754. request.abort();
  16755. }
  16756. };
  16757. // Loading screen
  16758. /**
  16759. * Display the loading screen
  16760. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16761. */
  16762. Engine.prototype.displayLoadingUI = function () {
  16763. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16764. return;
  16765. }
  16766. var loadingScreen = this.loadingScreen;
  16767. if (loadingScreen) {
  16768. loadingScreen.displayLoadingUI();
  16769. }
  16770. };
  16771. /**
  16772. * Hide the loading screen
  16773. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16774. */
  16775. Engine.prototype.hideLoadingUI = function () {
  16776. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16777. return;
  16778. }
  16779. var loadingScreen = this.loadingScreen;
  16780. if (loadingScreen) {
  16781. loadingScreen.hideLoadingUI();
  16782. }
  16783. };
  16784. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16785. /**
  16786. * Gets the current loading screen object
  16787. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16788. */
  16789. get: function () {
  16790. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16791. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16792. return this._loadingScreen;
  16793. },
  16794. /**
  16795. * Sets the current loading screen object
  16796. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16797. */
  16798. set: function (loadingScreen) {
  16799. this._loadingScreen = loadingScreen;
  16800. },
  16801. enumerable: true,
  16802. configurable: true
  16803. });
  16804. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16805. /**
  16806. * Sets the current loading screen text
  16807. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16808. */
  16809. set: function (text) {
  16810. this.loadingScreen.loadingUIText = text;
  16811. },
  16812. enumerable: true,
  16813. configurable: true
  16814. });
  16815. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16816. /**
  16817. * Sets the current loading screen background color
  16818. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16819. */
  16820. set: function (color) {
  16821. this.loadingScreen.loadingUIBackgroundColor = color;
  16822. },
  16823. enumerable: true,
  16824. configurable: true
  16825. });
  16826. /**
  16827. * Attach a new callback raised when context lost event is fired
  16828. * @param callback defines the callback to call
  16829. */
  16830. Engine.prototype.attachContextLostEvent = function (callback) {
  16831. if (this._renderingCanvas) {
  16832. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16833. }
  16834. };
  16835. /**
  16836. * Attach a new callback raised when context restored event is fired
  16837. * @param callback defines the callback to call
  16838. */
  16839. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16840. if (this._renderingCanvas) {
  16841. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16842. }
  16843. };
  16844. /**
  16845. * Gets the source code of the vertex shader associated with a specific webGL program
  16846. * @param program defines the program to use
  16847. * @returns a string containing the source code of the vertex shader associated with the program
  16848. */
  16849. Engine.prototype.getVertexShaderSource = function (program) {
  16850. var shaders = this._gl.getAttachedShaders(program);
  16851. if (!shaders) {
  16852. return null;
  16853. }
  16854. return this._gl.getShaderSource(shaders[0]);
  16855. };
  16856. /**
  16857. * Gets the source code of the fragment shader associated with a specific webGL program
  16858. * @param program defines the program to use
  16859. * @returns a string containing the source code of the fragment shader associated with the program
  16860. */
  16861. Engine.prototype.getFragmentShaderSource = function (program) {
  16862. var shaders = this._gl.getAttachedShaders(program);
  16863. if (!shaders) {
  16864. return null;
  16865. }
  16866. return this._gl.getShaderSource(shaders[1]);
  16867. };
  16868. /**
  16869. * Get the current error code of the webGL context
  16870. * @returns the error code
  16871. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16872. */
  16873. Engine.prototype.getError = function () {
  16874. return this._gl.getError();
  16875. };
  16876. // FPS
  16877. /**
  16878. * Gets the current framerate
  16879. * @returns a number representing the framerate
  16880. */
  16881. Engine.prototype.getFps = function () {
  16882. return this._fps;
  16883. };
  16884. /**
  16885. * Gets the time spent between current and previous frame
  16886. * @returns a number representing the delta time in ms
  16887. */
  16888. Engine.prototype.getDeltaTime = function () {
  16889. return this._deltaTime;
  16890. };
  16891. Engine.prototype._measureFps = function () {
  16892. this._performanceMonitor.sampleFrame();
  16893. this._fps = this._performanceMonitor.averageFPS;
  16894. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16895. };
  16896. /** @hidden */
  16897. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16898. if (faceIndex === void 0) { faceIndex = -1; }
  16899. if (level === void 0) { level = 0; }
  16900. var gl = this._gl;
  16901. if (!this._dummyFramebuffer) {
  16902. var dummy = gl.createFramebuffer();
  16903. if (!dummy) {
  16904. throw new Error("Unable to create dummy framebuffer");
  16905. }
  16906. this._dummyFramebuffer = dummy;
  16907. }
  16908. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16909. if (faceIndex > -1) {
  16910. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16911. }
  16912. else {
  16913. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16914. }
  16915. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16916. var buffer;
  16917. switch (readType) {
  16918. case gl.UNSIGNED_BYTE:
  16919. buffer = new Uint8Array(4 * width * height);
  16920. readType = gl.UNSIGNED_BYTE;
  16921. break;
  16922. default:
  16923. buffer = new Float32Array(4 * width * height);
  16924. readType = gl.FLOAT;
  16925. break;
  16926. }
  16927. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16928. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16929. return buffer;
  16930. };
  16931. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16932. if (this._webGLVersion > 1) {
  16933. return this._caps.colorBufferFloat;
  16934. }
  16935. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16936. };
  16937. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16938. if (this._webGLVersion > 1) {
  16939. return this._caps.colorBufferFloat;
  16940. }
  16941. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16942. };
  16943. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16944. Engine.prototype._canRenderToFramebuffer = function (type) {
  16945. var gl = this._gl;
  16946. //clear existing errors
  16947. while (gl.getError() !== gl.NO_ERROR) { }
  16948. var successful = true;
  16949. var texture = gl.createTexture();
  16950. gl.bindTexture(gl.TEXTURE_2D, texture);
  16951. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16952. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16953. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16954. var fb = gl.createFramebuffer();
  16955. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16956. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16957. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16958. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16959. successful = successful && (gl.getError() === gl.NO_ERROR);
  16960. //try render by clearing frame buffer's color buffer
  16961. if (successful) {
  16962. gl.clear(gl.COLOR_BUFFER_BIT);
  16963. successful = successful && (gl.getError() === gl.NO_ERROR);
  16964. }
  16965. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16966. if (successful) {
  16967. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16968. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16969. var readFormat = gl.RGBA;
  16970. var readType = gl.UNSIGNED_BYTE;
  16971. var buffer = new Uint8Array(4);
  16972. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16973. successful = successful && (gl.getError() === gl.NO_ERROR);
  16974. }
  16975. //clean up
  16976. gl.deleteTexture(texture);
  16977. gl.deleteFramebuffer(fb);
  16978. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16979. //clear accumulated errors
  16980. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16981. return successful;
  16982. };
  16983. /** @hidden */
  16984. Engine.prototype._getWebGLTextureType = function (type) {
  16985. if (type === Engine.TEXTURETYPE_FLOAT) {
  16986. return this._gl.FLOAT;
  16987. }
  16988. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16989. // Add Half Float Constant.
  16990. return this._gl.HALF_FLOAT_OES;
  16991. }
  16992. return this._gl.UNSIGNED_BYTE;
  16993. };
  16994. ;
  16995. Engine.prototype._getInternalFormat = function (format) {
  16996. var internalFormat = this._gl.RGBA;
  16997. switch (format) {
  16998. case Engine.TEXTUREFORMAT_ALPHA:
  16999. internalFormat = this._gl.ALPHA;
  17000. break;
  17001. case Engine.TEXTUREFORMAT_LUMINANCE:
  17002. internalFormat = this._gl.LUMINANCE;
  17003. break;
  17004. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17005. internalFormat = this._gl.LUMINANCE_ALPHA;
  17006. break;
  17007. case Engine.TEXTUREFORMAT_RGB:
  17008. internalFormat = this._gl.RGB;
  17009. break;
  17010. case Engine.TEXTUREFORMAT_RGBA:
  17011. internalFormat = this._gl.RGBA;
  17012. break;
  17013. case Engine.TEXTUREFORMAT_R:
  17014. internalFormat = this._gl.RED;
  17015. break;
  17016. case Engine.TEXTUREFORMAT_RG:
  17017. internalFormat = this._gl.RG;
  17018. break;
  17019. }
  17020. return internalFormat;
  17021. };
  17022. /** @hidden */
  17023. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17024. if (this._webGLVersion === 1) {
  17025. if (format !== undefined) {
  17026. switch (format) {
  17027. case Engine.TEXTUREFORMAT_LUMINANCE:
  17028. return this._gl.LUMINANCE;
  17029. case Engine.TEXTUREFORMAT_ALPHA:
  17030. return this._gl.ALPHA;
  17031. }
  17032. }
  17033. return this._gl.RGBA;
  17034. }
  17035. if (type === Engine.TEXTURETYPE_FLOAT) {
  17036. if (format !== undefined) {
  17037. switch (format) {
  17038. case Engine.TEXTUREFORMAT_R:
  17039. return this._gl.R32F;
  17040. case Engine.TEXTUREFORMAT_RG:
  17041. return this._gl.RG32F;
  17042. case Engine.TEXTUREFORMAT_RGB:
  17043. return this._gl.RGB32F;
  17044. }
  17045. }
  17046. return this._gl.RGBA32F;
  17047. }
  17048. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17049. if (format) {
  17050. switch (format) {
  17051. case Engine.TEXTUREFORMAT_R:
  17052. return this._gl.R16F;
  17053. case Engine.TEXTUREFORMAT_RG:
  17054. return this._gl.RG16F;
  17055. case Engine.TEXTUREFORMAT_RGB:
  17056. return this._gl.RGB16F;
  17057. }
  17058. }
  17059. return this._gl.RGBA16F;
  17060. }
  17061. if (format !== undefined) {
  17062. switch (format) {
  17063. case Engine.TEXTUREFORMAT_LUMINANCE:
  17064. return this._gl.LUMINANCE;
  17065. case Engine.TEXTUREFORMAT_RGB:
  17066. return this._gl.RGB;
  17067. case Engine.TEXTUREFORMAT_R:
  17068. return this._gl.R8;
  17069. case Engine.TEXTUREFORMAT_RG:
  17070. return this._gl.RG8;
  17071. case Engine.TEXTUREFORMAT_ALPHA:
  17072. return this._gl.ALPHA;
  17073. }
  17074. }
  17075. return this._gl.RGBA;
  17076. };
  17077. ;
  17078. /** @hidden */
  17079. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17080. if (type === Engine.TEXTURETYPE_FLOAT) {
  17081. return this._gl.RGBA32F;
  17082. }
  17083. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17084. return this._gl.RGBA16F;
  17085. }
  17086. return this._gl.RGBA8;
  17087. };
  17088. ;
  17089. /**
  17090. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17091. * @return the new query
  17092. */
  17093. Engine.prototype.createQuery = function () {
  17094. return this._gl.createQuery();
  17095. };
  17096. /**
  17097. * Delete and release a webGL query
  17098. * @param query defines the query to delete
  17099. * @return the current engine
  17100. */
  17101. Engine.prototype.deleteQuery = function (query) {
  17102. this._gl.deleteQuery(query);
  17103. return this;
  17104. };
  17105. /**
  17106. * Check if a given query has resolved and got its value
  17107. * @param query defines the query to check
  17108. * @returns true if the query got its value
  17109. */
  17110. Engine.prototype.isQueryResultAvailable = function (query) {
  17111. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17112. };
  17113. /**
  17114. * Gets the value of a given query
  17115. * @param query defines the query to check
  17116. * @returns the value of the query
  17117. */
  17118. Engine.prototype.getQueryResult = function (query) {
  17119. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17120. };
  17121. /**
  17122. * Initiates an occlusion query
  17123. * @param algorithmType defines the algorithm to use
  17124. * @param query defines the query to use
  17125. * @returns the current engine
  17126. * @see http://doc.babylonjs.com/features/occlusionquery
  17127. */
  17128. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17129. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17130. this._gl.beginQuery(glAlgorithm, query);
  17131. return this;
  17132. };
  17133. /**
  17134. * Ends an occlusion query
  17135. * @see http://doc.babylonjs.com/features/occlusionquery
  17136. * @param algorithmType defines the algorithm to use
  17137. * @returns the current engine
  17138. */
  17139. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17140. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17141. this._gl.endQuery(glAlgorithm);
  17142. return this;
  17143. };
  17144. /* Time queries */
  17145. Engine.prototype._createTimeQuery = function () {
  17146. var timerQuery = this._caps.timerQuery;
  17147. if (timerQuery.createQueryEXT) {
  17148. return timerQuery.createQueryEXT();
  17149. }
  17150. return this.createQuery();
  17151. };
  17152. Engine.prototype._deleteTimeQuery = function (query) {
  17153. var timerQuery = this._caps.timerQuery;
  17154. if (timerQuery.deleteQueryEXT) {
  17155. timerQuery.deleteQueryEXT(query);
  17156. return;
  17157. }
  17158. this.deleteQuery(query);
  17159. };
  17160. Engine.prototype._getTimeQueryResult = function (query) {
  17161. var timerQuery = this._caps.timerQuery;
  17162. if (timerQuery.getQueryObjectEXT) {
  17163. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17164. }
  17165. return this.getQueryResult(query);
  17166. };
  17167. Engine.prototype._getTimeQueryAvailability = function (query) {
  17168. var timerQuery = this._caps.timerQuery;
  17169. if (timerQuery.getQueryObjectEXT) {
  17170. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17171. }
  17172. return this.isQueryResultAvailable(query);
  17173. };
  17174. /**
  17175. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17176. * Please note that only one query can be issued at a time
  17177. * @returns a time token used to track the time span
  17178. */
  17179. Engine.prototype.startTimeQuery = function () {
  17180. var timerQuery = this._caps.timerQuery;
  17181. if (!timerQuery) {
  17182. return null;
  17183. }
  17184. var token = new BABYLON._TimeToken();
  17185. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17186. if (this._caps.canUseTimestampForTimerQuery) {
  17187. token._startTimeQuery = this._createTimeQuery();
  17188. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17189. }
  17190. else {
  17191. if (this._currentNonTimestampToken) {
  17192. return this._currentNonTimestampToken;
  17193. }
  17194. token._timeElapsedQuery = this._createTimeQuery();
  17195. if (timerQuery.beginQueryEXT) {
  17196. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17197. }
  17198. else {
  17199. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17200. }
  17201. this._currentNonTimestampToken = token;
  17202. }
  17203. return token;
  17204. };
  17205. /**
  17206. * Ends a time query
  17207. * @param token defines the token used to measure the time span
  17208. * @returns the time spent (in ns)
  17209. */
  17210. Engine.prototype.endTimeQuery = function (token) {
  17211. var timerQuery = this._caps.timerQuery;
  17212. if (!timerQuery || !token) {
  17213. return -1;
  17214. }
  17215. if (this._caps.canUseTimestampForTimerQuery) {
  17216. if (!token._startTimeQuery) {
  17217. return -1;
  17218. }
  17219. if (!token._endTimeQuery) {
  17220. token._endTimeQuery = this._createTimeQuery();
  17221. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17222. }
  17223. }
  17224. else if (!token._timeElapsedQueryEnded) {
  17225. if (!token._timeElapsedQuery) {
  17226. return -1;
  17227. }
  17228. if (timerQuery.endQueryEXT) {
  17229. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17230. }
  17231. else {
  17232. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17233. }
  17234. token._timeElapsedQueryEnded = true;
  17235. }
  17236. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17237. var available = false;
  17238. if (token._endTimeQuery) {
  17239. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17240. }
  17241. else if (token._timeElapsedQuery) {
  17242. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17243. }
  17244. if (available && !disjoint) {
  17245. var result = 0;
  17246. if (this._caps.canUseTimestampForTimerQuery) {
  17247. if (!token._startTimeQuery || !token._endTimeQuery) {
  17248. return -1;
  17249. }
  17250. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17251. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17252. result = timeEnd - timeStart;
  17253. this._deleteTimeQuery(token._startTimeQuery);
  17254. this._deleteTimeQuery(token._endTimeQuery);
  17255. token._startTimeQuery = null;
  17256. token._endTimeQuery = null;
  17257. }
  17258. else {
  17259. if (!token._timeElapsedQuery) {
  17260. return -1;
  17261. }
  17262. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17263. this._deleteTimeQuery(token._timeElapsedQuery);
  17264. token._timeElapsedQuery = null;
  17265. token._timeElapsedQueryEnded = false;
  17266. this._currentNonTimestampToken = null;
  17267. }
  17268. return result;
  17269. }
  17270. return -1;
  17271. };
  17272. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17273. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17274. };
  17275. // Transform feedback
  17276. /**
  17277. * Creates a webGL transform feedback object
  17278. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17279. * @returns the webGL transform feedback object
  17280. */
  17281. Engine.prototype.createTransformFeedback = function () {
  17282. return this._gl.createTransformFeedback();
  17283. };
  17284. /**
  17285. * Delete a webGL transform feedback object
  17286. * @param value defines the webGL transform feedback object to delete
  17287. */
  17288. Engine.prototype.deleteTransformFeedback = function (value) {
  17289. this._gl.deleteTransformFeedback(value);
  17290. };
  17291. /**
  17292. * Bind a webGL transform feedback object to the webgl context
  17293. * @param value defines the webGL transform feedback object to bind
  17294. */
  17295. Engine.prototype.bindTransformFeedback = function (value) {
  17296. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17297. };
  17298. /**
  17299. * Begins a transform feedback operation
  17300. * @param usePoints defines if points or triangles must be used
  17301. */
  17302. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17303. if (usePoints === void 0) { usePoints = true; }
  17304. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17305. };
  17306. /**
  17307. * Ends a transform feedback operation
  17308. */
  17309. Engine.prototype.endTransformFeedback = function () {
  17310. this._gl.endTransformFeedback();
  17311. };
  17312. /**
  17313. * Specify the varyings to use with transform feedback
  17314. * @param program defines the associated webGL program
  17315. * @param value defines the list of strings representing the varying names
  17316. */
  17317. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17318. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17319. };
  17320. /**
  17321. * Bind a webGL buffer for a transform feedback operation
  17322. * @param value defines the webGL buffer to bind
  17323. */
  17324. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17325. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17326. };
  17327. /** @hidden */
  17328. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17329. var _this = this;
  17330. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17331. this._activeRequests.push(request);
  17332. request.onCompleteObservable.add(function (request) {
  17333. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17334. });
  17335. return request;
  17336. };
  17337. /** @hidden */
  17338. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17339. var _this = this;
  17340. return new Promise(function (resolve, reject) {
  17341. _this._loadFile(url, function (data) {
  17342. resolve(data);
  17343. }, undefined, database, useArrayBuffer, function (request, exception) {
  17344. reject(exception);
  17345. });
  17346. });
  17347. };
  17348. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17349. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17350. var onload = function (data) {
  17351. loadedFiles[index] = data;
  17352. loadedFiles._internalCount++;
  17353. if (loadedFiles._internalCount === 6) {
  17354. onfinish(loadedFiles);
  17355. }
  17356. };
  17357. var onerror = function (request, exception) {
  17358. if (onErrorCallBack && request) {
  17359. onErrorCallBack(request.status + " " + request.statusText, exception);
  17360. }
  17361. };
  17362. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17363. };
  17364. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17365. if (onError === void 0) { onError = null; }
  17366. var loadedFiles = [];
  17367. loadedFiles._internalCount = 0;
  17368. for (var index = 0; index < 6; index++) {
  17369. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17370. }
  17371. };
  17372. // Statics
  17373. /**
  17374. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17375. * @returns true if the engine can be created
  17376. * @ignorenaming
  17377. */
  17378. Engine.isSupported = function () {
  17379. try {
  17380. var tempcanvas = document.createElement("canvas");
  17381. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17382. return gl != null && !!window.WebGLRenderingContext;
  17383. }
  17384. catch (e) {
  17385. return false;
  17386. }
  17387. };
  17388. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17389. Engine.ExceptionList = [
  17390. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17391. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17392. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17393. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17394. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17395. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17396. ];
  17397. /** Gets the list of created engines */
  17398. Engine.Instances = new Array();
  17399. // Const statics
  17400. /** Defines that alpha blending is disabled */
  17401. Engine.ALPHA_DISABLE = 0;
  17402. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17403. Engine.ALPHA_ADD = 1;
  17404. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17405. Engine.ALPHA_COMBINE = 2;
  17406. /** Defines that alpha blending to DEST - SRC * DEST */
  17407. Engine.ALPHA_SUBTRACT = 3;
  17408. /** Defines that alpha blending to SRC * DEST */
  17409. Engine.ALPHA_MULTIPLY = 4;
  17410. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17411. Engine.ALPHA_MAXIMIZED = 5;
  17412. /** Defines that alpha blending to SRC + DEST */
  17413. Engine.ALPHA_ONEONE = 6;
  17414. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17415. Engine.ALPHA_PREMULTIPLIED = 7;
  17416. /**
  17417. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17418. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17419. */
  17420. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17421. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17422. Engine.ALPHA_INTERPOLATE = 9;
  17423. /**
  17424. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17425. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17426. */
  17427. Engine.ALPHA_SCREENMODE = 10;
  17428. /** Defines that the ressource is not delayed*/
  17429. Engine.DELAYLOADSTATE_NONE = 0;
  17430. /** Defines that the ressource was successfully delay loaded */
  17431. Engine.DELAYLOADSTATE_LOADED = 1;
  17432. /** Defines that the ressource is currently delay loading */
  17433. Engine.DELAYLOADSTATE_LOADING = 2;
  17434. /** Defines that the ressource is delayed and has not started loading */
  17435. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17436. // Depht or Stencil test Constants.
  17437. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17438. Engine.NEVER = 0x0200;
  17439. /** 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 */
  17440. Engine.ALWAYS = 0x0207;
  17441. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17442. Engine.LESS = 0x0201;
  17443. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17444. Engine.EQUAL = 0x0202;
  17445. /** 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 */
  17446. Engine.LEQUAL = 0x0203;
  17447. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17448. Engine.GREATER = 0x0204;
  17449. /** 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 */
  17450. Engine.GEQUAL = 0x0206;
  17451. /** 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 */
  17452. Engine.NOTEQUAL = 0x0205;
  17453. // Stencil Actions Constants.
  17454. /** Passed to stencilOperation to specify that stencil value must be kept */
  17455. Engine.KEEP = 0x1E00;
  17456. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17457. Engine.REPLACE = 0x1E01;
  17458. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17459. Engine.INCR = 0x1E02;
  17460. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17461. Engine.DECR = 0x1E03;
  17462. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17463. Engine.INVERT = 0x150A;
  17464. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17465. Engine.INCR_WRAP = 0x8507;
  17466. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17467. Engine.DECR_WRAP = 0x8508;
  17468. /** Texture is not repeating outside of 0..1 UVs */
  17469. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17470. /** Texture is repeating outside of 0..1 UVs */
  17471. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17472. /** Texture is repeating and mirrored */
  17473. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17474. /** ALPHA */
  17475. Engine.TEXTUREFORMAT_ALPHA = 0;
  17476. /** LUMINANCE */
  17477. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17478. /** LUMINANCE_ALPHA */
  17479. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17480. /** RGB */
  17481. Engine.TEXTUREFORMAT_RGB = 4;
  17482. /** RGBA */
  17483. Engine.TEXTUREFORMAT_RGBA = 5;
  17484. /** R */
  17485. Engine.TEXTUREFORMAT_R = 6;
  17486. /** RG */
  17487. Engine.TEXTUREFORMAT_RG = 7;
  17488. /** UNSIGNED_INT */
  17489. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17490. /** FLOAT */
  17491. Engine.TEXTURETYPE_FLOAT = 1;
  17492. /** HALF_FLOAT */
  17493. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17494. /** nearest is mag = nearest and min = nearest and mip = linear */
  17495. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17496. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17497. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17498. /** Trilinear is mag = linear and min = linear and mip = linear */
  17499. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17500. /** nearest is mag = nearest and min = nearest and mip = linear */
  17501. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17502. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17503. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17504. /** Trilinear is mag = linear and min = linear and mip = linear */
  17505. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17506. /** mag = nearest and min = nearest and mip = nearest */
  17507. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17508. /** mag = nearest and min = linear and mip = nearest */
  17509. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17510. /** mag = nearest and min = linear and mip = linear */
  17511. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17512. /** mag = nearest and min = linear and mip = none */
  17513. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17514. /** mag = nearest and min = nearest and mip = none */
  17515. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17516. /** mag = linear and min = nearest and mip = nearest */
  17517. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17518. /** mag = linear and min = nearest and mip = linear */
  17519. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17520. /** mag = linear and min = linear and mip = none */
  17521. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17522. /** mag = linear and min = nearest and mip = none */
  17523. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17524. /** Explicit coordinates mode */
  17525. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17526. /** Spherical coordinates mode */
  17527. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17528. /** Planar coordinates mode */
  17529. Engine.TEXTURE_PLANAR_MODE = 2;
  17530. /** Cubic coordinates mode */
  17531. Engine.TEXTURE_CUBIC_MODE = 3;
  17532. /** Projection coordinates mode */
  17533. Engine.TEXTURE_PROJECTION_MODE = 4;
  17534. /** Skybox coordinates mode */
  17535. Engine.TEXTURE_SKYBOX_MODE = 5;
  17536. /** Inverse Cubic coordinates mode */
  17537. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17538. /** Equirectangular coordinates mode */
  17539. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17540. /** Equirectangular Fixed coordinates mode */
  17541. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17542. /** Equirectangular Fixed Mirrored coordinates mode */
  17543. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17544. // Texture rescaling mode
  17545. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17546. Engine.SCALEMODE_FLOOR = 1;
  17547. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17548. Engine.SCALEMODE_NEAREST = 2;
  17549. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17550. Engine.SCALEMODE_CEILING = 3;
  17551. // Updatable statics so stick with vars here
  17552. /**
  17553. * Gets or sets the epsilon value used by collision engine
  17554. */
  17555. Engine.CollisionsEpsilon = 0.001;
  17556. /**
  17557. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17558. */
  17559. Engine.CodeRepository = "src/";
  17560. /**
  17561. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17562. */
  17563. Engine.ShadersRepository = "src/Shaders/";
  17564. return Engine;
  17565. }());
  17566. BABYLON.Engine = Engine;
  17567. })(BABYLON || (BABYLON = {}));
  17568. //# sourceMappingURL=babylon.engine.js.map
  17569. var BABYLON;
  17570. (function (BABYLON) {
  17571. /**
  17572. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17573. */
  17574. var Node = /** @class */ (function () {
  17575. /**
  17576. * Creates a new Node
  17577. * @param {string} name - the name and id to be given to this node
  17578. * @param {BABYLON.Scene} the scene this node will be added to
  17579. */
  17580. function Node(name, scene) {
  17581. if (scene === void 0) { scene = null; }
  17582. /**
  17583. * Gets or sets a string used to store user defined state for the node
  17584. */
  17585. this.state = "";
  17586. /**
  17587. * Gets or sets an object used to store user defined information for the node
  17588. */
  17589. this.metadata = null;
  17590. /**
  17591. * Gets or sets a boolean used to define if the node must be serialized
  17592. */
  17593. this.doNotSerialize = false;
  17594. /** @hidden */
  17595. this._isDisposed = false;
  17596. /**
  17597. * Gets a list of Animations associated with the node
  17598. */
  17599. this.animations = new Array();
  17600. this._ranges = {};
  17601. this._isEnabled = true;
  17602. this._isReady = true;
  17603. /** @hidden */
  17604. this._currentRenderId = -1;
  17605. this._parentRenderId = -1;
  17606. this._childRenderId = -1;
  17607. this._animationPropertiesOverride = null;
  17608. /**
  17609. * An event triggered when the mesh is disposed
  17610. */
  17611. this.onDisposeObservable = new BABYLON.Observable();
  17612. // Behaviors
  17613. this._behaviors = new Array();
  17614. this.name = name;
  17615. this.id = name;
  17616. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17617. this.uniqueId = this._scene.getUniqueId();
  17618. this._initCache();
  17619. }
  17620. /**
  17621. * Add a new node constructor
  17622. * @param type defines the type name of the node to construct
  17623. * @param constructorFunc defines the constructor function
  17624. */
  17625. Node.AddNodeConstructor = function (type, constructorFunc) {
  17626. this._NodeConstructors[type] = constructorFunc;
  17627. };
  17628. /**
  17629. * Returns a node constructor based on type name
  17630. * @param type defines the type name
  17631. * @param name defines the new node name
  17632. * @param scene defines the hosting scene
  17633. * @param options defines optional options to transmit to constructors
  17634. * @returns the new constructor or null
  17635. */
  17636. Node.Construct = function (type, name, scene, options) {
  17637. var constructorFunc = this._NodeConstructors[type];
  17638. if (!constructorFunc) {
  17639. return null;
  17640. }
  17641. return constructorFunc(name, scene, options);
  17642. };
  17643. /**
  17644. * Gets a boolean indicating if the node has been disposed
  17645. * @returns true if the node was disposed
  17646. */
  17647. Node.prototype.isDisposed = function () {
  17648. return this._isDisposed;
  17649. };
  17650. Object.defineProperty(Node.prototype, "parent", {
  17651. get: function () {
  17652. return this._parentNode;
  17653. },
  17654. /**
  17655. * Gets or sets the parent of the node
  17656. */
  17657. set: function (parent) {
  17658. if (this._parentNode === parent) {
  17659. return;
  17660. }
  17661. // Remove self from list of children of parent
  17662. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17663. var index = this._parentNode._children.indexOf(this);
  17664. if (index !== -1) {
  17665. this._parentNode._children.splice(index, 1);
  17666. }
  17667. }
  17668. // Store new parent
  17669. this._parentNode = parent;
  17670. // Add as child to new parent
  17671. if (this._parentNode) {
  17672. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17673. this._parentNode._children = new Array();
  17674. }
  17675. this._parentNode._children.push(this);
  17676. }
  17677. },
  17678. enumerable: true,
  17679. configurable: true
  17680. });
  17681. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17682. /**
  17683. * Gets or sets the animation properties override
  17684. */
  17685. get: function () {
  17686. if (!this._animationPropertiesOverride) {
  17687. return this._scene.animationPropertiesOverride;
  17688. }
  17689. return this._animationPropertiesOverride;
  17690. },
  17691. set: function (value) {
  17692. this._animationPropertiesOverride = value;
  17693. },
  17694. enumerable: true,
  17695. configurable: true
  17696. });
  17697. /**
  17698. * Gets a string idenfifying the name of the class
  17699. * @returns "Node" string
  17700. */
  17701. Node.prototype.getClassName = function () {
  17702. return "Node";
  17703. };
  17704. Object.defineProperty(Node.prototype, "onDispose", {
  17705. /**
  17706. * Sets a callback that will be raised when the node will be disposed
  17707. */
  17708. set: function (callback) {
  17709. if (this._onDisposeObserver) {
  17710. this.onDisposeObservable.remove(this._onDisposeObserver);
  17711. }
  17712. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17713. },
  17714. enumerable: true,
  17715. configurable: true
  17716. });
  17717. /**
  17718. * Gets the scene of the node
  17719. * @returns a {BABYLON.Scene}
  17720. */
  17721. Node.prototype.getScene = function () {
  17722. return this._scene;
  17723. };
  17724. /**
  17725. * Gets the engine of the node
  17726. * @returns a {BABYLON.Engine}
  17727. */
  17728. Node.prototype.getEngine = function () {
  17729. return this._scene.getEngine();
  17730. };
  17731. /**
  17732. * Attach a behavior to the node
  17733. * @see http://doc.babylonjs.com/features/behaviour
  17734. * @param behavior defines the behavior to attach
  17735. * @returns the current Node
  17736. */
  17737. Node.prototype.addBehavior = function (behavior) {
  17738. var _this = this;
  17739. var index = this._behaviors.indexOf(behavior);
  17740. if (index !== -1) {
  17741. return this;
  17742. }
  17743. behavior.init();
  17744. if (this._scene.isLoading) {
  17745. // We defer the attach when the scene will be loaded
  17746. this._scene.onDataLoadedObservable.addOnce(function () {
  17747. behavior.attach(_this);
  17748. });
  17749. }
  17750. else {
  17751. behavior.attach(this);
  17752. }
  17753. this._behaviors.push(behavior);
  17754. return this;
  17755. };
  17756. /**
  17757. * Remove an attached behavior
  17758. * @see http://doc.babylonjs.com/features/behaviour
  17759. * @param behavior defines the behavior to attach
  17760. * @returns the current Node
  17761. */
  17762. Node.prototype.removeBehavior = function (behavior) {
  17763. var index = this._behaviors.indexOf(behavior);
  17764. if (index === -1) {
  17765. return this;
  17766. }
  17767. this._behaviors[index].detach();
  17768. this._behaviors.splice(index, 1);
  17769. return this;
  17770. };
  17771. Object.defineProperty(Node.prototype, "behaviors", {
  17772. /**
  17773. * Gets the list of attached behaviors
  17774. * @see http://doc.babylonjs.com/features/behaviour
  17775. */
  17776. get: function () {
  17777. return this._behaviors;
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. /**
  17783. * Gets an attached behavior by name
  17784. * @param name defines the name of the behavior to look for
  17785. * @see http://doc.babylonjs.com/features/behaviour
  17786. * @returns null if behavior was not found else the requested behavior
  17787. */
  17788. Node.prototype.getBehaviorByName = function (name) {
  17789. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17790. var behavior = _a[_i];
  17791. if (behavior.name === name) {
  17792. return behavior;
  17793. }
  17794. }
  17795. return null;
  17796. };
  17797. /**
  17798. * Returns the world matrix of the node
  17799. * @returns a matrix containing the node's world matrix
  17800. */
  17801. Node.prototype.getWorldMatrix = function () {
  17802. return BABYLON.Matrix.Identity();
  17803. };
  17804. /** @hidden */
  17805. Node.prototype._getWorldMatrixDeterminant = function () {
  17806. return 1;
  17807. };
  17808. // override it in derived class if you add new variables to the cache
  17809. // and call the parent class method
  17810. /** @hidden */
  17811. Node.prototype._initCache = function () {
  17812. this._cache = {};
  17813. this._cache.parent = undefined;
  17814. };
  17815. /** @hidden */
  17816. Node.prototype.updateCache = function (force) {
  17817. if (!force && this.isSynchronized())
  17818. return;
  17819. this._cache.parent = this.parent;
  17820. this._updateCache();
  17821. };
  17822. // override it in derived class if you add new variables to the cache
  17823. // and call the parent class method if !ignoreParentClass
  17824. /** @hidden */
  17825. Node.prototype._updateCache = function (ignoreParentClass) {
  17826. };
  17827. // override it in derived class if you add new variables to the cache
  17828. /** @hidden */
  17829. Node.prototype._isSynchronized = function () {
  17830. return true;
  17831. };
  17832. /** @hidden */
  17833. Node.prototype._markSyncedWithParent = function () {
  17834. if (this.parent) {
  17835. this._parentRenderId = this.parent._childRenderId;
  17836. }
  17837. };
  17838. /** @hidden */
  17839. Node.prototype.isSynchronizedWithParent = function () {
  17840. if (!this.parent) {
  17841. return true;
  17842. }
  17843. if (this._parentRenderId !== this.parent._childRenderId) {
  17844. return false;
  17845. }
  17846. return this.parent.isSynchronized();
  17847. };
  17848. /** @hidden */
  17849. Node.prototype.isSynchronized = function (updateCache) {
  17850. var check = this.hasNewParent();
  17851. check = check || !this.isSynchronizedWithParent();
  17852. check = check || !this._isSynchronized();
  17853. if (updateCache)
  17854. this.updateCache(true);
  17855. return !check;
  17856. };
  17857. /** @hidden */
  17858. Node.prototype.hasNewParent = function (update) {
  17859. if (this._cache.parent === this.parent)
  17860. return false;
  17861. if (update)
  17862. this._cache.parent = this.parent;
  17863. return true;
  17864. };
  17865. /**
  17866. * Is this node ready to be used/rendered
  17867. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17868. * @return true if the node is ready
  17869. */
  17870. Node.prototype.isReady = function (completeCheck) {
  17871. if (completeCheck === void 0) { completeCheck = false; }
  17872. return this._isReady;
  17873. };
  17874. /**
  17875. * Is this node enabled?
  17876. * 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
  17877. * @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
  17878. * @return whether this node (and its parent) is enabled
  17879. */
  17880. Node.prototype.isEnabled = function (checkAncestors) {
  17881. if (checkAncestors === void 0) { checkAncestors = true; }
  17882. if (checkAncestors === false) {
  17883. return this._isEnabled;
  17884. }
  17885. if (this._isEnabled === false) {
  17886. return false;
  17887. }
  17888. if (this.parent !== undefined && this.parent !== null) {
  17889. return this.parent.isEnabled(checkAncestors);
  17890. }
  17891. return true;
  17892. };
  17893. /**
  17894. * Set the enabled state of this node
  17895. * @param value defines the new enabled state
  17896. */
  17897. Node.prototype.setEnabled = function (value) {
  17898. this._isEnabled = value;
  17899. };
  17900. /**
  17901. * Is this node a descendant of the given node?
  17902. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17903. * @param ancestor defines the parent node to inspect
  17904. * @returns a boolean indicating if this node is a descendant of the given node
  17905. */
  17906. Node.prototype.isDescendantOf = function (ancestor) {
  17907. if (this.parent) {
  17908. if (this.parent === ancestor) {
  17909. return true;
  17910. }
  17911. return this.parent.isDescendantOf(ancestor);
  17912. }
  17913. return false;
  17914. };
  17915. /** @hidden */
  17916. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17917. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17918. if (!this._children) {
  17919. return;
  17920. }
  17921. for (var index = 0; index < this._children.length; index++) {
  17922. var item = this._children[index];
  17923. if (!predicate || predicate(item)) {
  17924. results.push(item);
  17925. }
  17926. if (!directDescendantsOnly) {
  17927. item._getDescendants(results, false, predicate);
  17928. }
  17929. }
  17930. };
  17931. /**
  17932. * Will return all nodes that have this node as ascendant
  17933. * @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
  17934. * @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
  17935. * @return all children nodes of all types
  17936. */
  17937. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17938. var results = new Array();
  17939. this._getDescendants(results, directDescendantsOnly, predicate);
  17940. return results;
  17941. };
  17942. /**
  17943. * Get all child-meshes of this node
  17944. * @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
  17945. * @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
  17946. * @returns an array of {BABYLON.AbstractMesh}
  17947. */
  17948. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17949. var results = [];
  17950. this._getDescendants(results, directDescendantsOnly, function (node) {
  17951. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17952. });
  17953. return results;
  17954. };
  17955. /**
  17956. * Get all child-transformNodes of this node
  17957. * @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
  17958. * @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
  17959. * @returns an array of {BABYLON.TransformNode}
  17960. */
  17961. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17962. var results = [];
  17963. this._getDescendants(results, directDescendantsOnly, function (node) {
  17964. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17965. });
  17966. return results;
  17967. };
  17968. /**
  17969. * Get all direct children of this node
  17970. * @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
  17971. * @returns an array of {BABYLON.Node}
  17972. */
  17973. Node.prototype.getChildren = function (predicate) {
  17974. return this.getDescendants(true, predicate);
  17975. };
  17976. /** @hidden */
  17977. Node.prototype._setReady = function (state) {
  17978. if (state === this._isReady) {
  17979. return;
  17980. }
  17981. if (!state) {
  17982. this._isReady = false;
  17983. return;
  17984. }
  17985. if (this.onReady) {
  17986. this.onReady(this);
  17987. }
  17988. this._isReady = true;
  17989. };
  17990. /**
  17991. * Get an animation by name
  17992. * @param name defines the name of the animation to look for
  17993. * @returns null if not found else the requested animation
  17994. */
  17995. Node.prototype.getAnimationByName = function (name) {
  17996. for (var i = 0; i < this.animations.length; i++) {
  17997. var animation = this.animations[i];
  17998. if (animation.name === name) {
  17999. return animation;
  18000. }
  18001. }
  18002. return null;
  18003. };
  18004. /**
  18005. * Creates an animation range for this node
  18006. * @param name defines the name of the range
  18007. * @param from defines the starting key
  18008. * @param to defines the end key
  18009. */
  18010. Node.prototype.createAnimationRange = function (name, from, to) {
  18011. // check name not already in use
  18012. if (!this._ranges[name]) {
  18013. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18014. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18015. if (this.animations[i]) {
  18016. this.animations[i].createRange(name, from, to);
  18017. }
  18018. }
  18019. }
  18020. };
  18021. /**
  18022. * Delete a specific animation range
  18023. * @param name defines the name of the range to delete
  18024. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18025. */
  18026. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18027. if (deleteFrames === void 0) { deleteFrames = true; }
  18028. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18029. if (this.animations[i]) {
  18030. this.animations[i].deleteRange(name, deleteFrames);
  18031. }
  18032. }
  18033. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18034. };
  18035. /**
  18036. * Get an animation range by name
  18037. * @param name defines the name of the animation range to look for
  18038. * @returns null if not found else the requested animation range
  18039. */
  18040. Node.prototype.getAnimationRange = function (name) {
  18041. return this._ranges[name];
  18042. };
  18043. /**
  18044. * Will start the animation sequence
  18045. * @param name defines the range frames for animation sequence
  18046. * @param loop defines if the animation should loop (false by default)
  18047. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18048. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18049. * @returns the object created for this animation. If range does not exist, it will return null
  18050. */
  18051. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18052. var range = this.getAnimationRange(name);
  18053. if (!range) {
  18054. return null;
  18055. }
  18056. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18057. };
  18058. /**
  18059. * Serialize animation ranges into a JSON compatible object
  18060. * @returns serialization object
  18061. */
  18062. Node.prototype.serializeAnimationRanges = function () {
  18063. var serializationRanges = [];
  18064. for (var name in this._ranges) {
  18065. var localRange = this._ranges[name];
  18066. if (!localRange) {
  18067. continue;
  18068. }
  18069. var range = {};
  18070. range.name = name;
  18071. range.from = localRange.from;
  18072. range.to = localRange.to;
  18073. serializationRanges.push(range);
  18074. }
  18075. return serializationRanges;
  18076. };
  18077. /**
  18078. * Computes the world matrix of the node
  18079. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18080. * @returns the world matrix
  18081. */
  18082. Node.prototype.computeWorldMatrix = function (force) {
  18083. return BABYLON.Matrix.Identity();
  18084. };
  18085. /**
  18086. * Releases resources associated with this node.
  18087. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18088. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18089. */
  18090. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18091. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18092. if (!doNotRecurse) {
  18093. var nodes = this.getDescendants(true);
  18094. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18095. var node = nodes_1[_i];
  18096. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18097. }
  18098. }
  18099. else {
  18100. var transformNodes = this.getChildTransformNodes(true);
  18101. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18102. var transformNode = transformNodes_1[_a];
  18103. transformNode.parent = null;
  18104. transformNode.computeWorldMatrix(true);
  18105. }
  18106. }
  18107. this.parent = null;
  18108. // Callback
  18109. this.onDisposeObservable.notifyObservers(this);
  18110. this.onDisposeObservable.clear();
  18111. // Behaviors
  18112. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18113. var behavior = _c[_b];
  18114. behavior.detach();
  18115. }
  18116. this._behaviors = [];
  18117. this._isDisposed = true;
  18118. };
  18119. /**
  18120. * Parse animation range data from a serialization object and store them into a given node
  18121. * @param node defines where to store the animation ranges
  18122. * @param parsedNode defines the serialization object to read data from
  18123. * @param scene defines the hosting scene
  18124. */
  18125. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18126. if (parsedNode.ranges) {
  18127. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18128. var data = parsedNode.ranges[index];
  18129. node.createAnimationRange(data.name, data.from, data.to);
  18130. }
  18131. }
  18132. };
  18133. Node._NodeConstructors = {};
  18134. __decorate([
  18135. BABYLON.serialize()
  18136. ], Node.prototype, "name", void 0);
  18137. __decorate([
  18138. BABYLON.serialize()
  18139. ], Node.prototype, "id", void 0);
  18140. __decorate([
  18141. BABYLON.serialize()
  18142. ], Node.prototype, "uniqueId", void 0);
  18143. __decorate([
  18144. BABYLON.serialize()
  18145. ], Node.prototype, "state", void 0);
  18146. __decorate([
  18147. BABYLON.serialize()
  18148. ], Node.prototype, "metadata", void 0);
  18149. return Node;
  18150. }());
  18151. BABYLON.Node = Node;
  18152. })(BABYLON || (BABYLON = {}));
  18153. //# sourceMappingURL=babylon.node.js.map
  18154. var BABYLON;
  18155. (function (BABYLON) {
  18156. var BoundingSphere = /** @class */ (function () {
  18157. /**
  18158. * Creates a new bounding sphere
  18159. * @param min defines the minimum vector (in local space)
  18160. * @param max defines the maximum vector (in local space)
  18161. */
  18162. function BoundingSphere(min, max) {
  18163. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18164. this.reConstruct(min, max);
  18165. }
  18166. /**
  18167. * Recreates the entire bounding sphere from scratch
  18168. * @param min defines the new minimum vector (in local space)
  18169. * @param max defines the new maximum vector (in local space)
  18170. */
  18171. BoundingSphere.prototype.reConstruct = function (min, max) {
  18172. this.minimum = min.clone();
  18173. this.maximum = max.clone();
  18174. var distance = BABYLON.Vector3.Distance(min, max);
  18175. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18176. this.radius = distance * 0.5;
  18177. this.centerWorld = BABYLON.Vector3.Zero();
  18178. this._update(BABYLON.Matrix.Identity());
  18179. };
  18180. // Methods
  18181. BoundingSphere.prototype._update = function (world) {
  18182. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18183. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18184. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18185. };
  18186. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18187. for (var i = 0; i < 6; i++) {
  18188. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18189. return false;
  18190. }
  18191. return true;
  18192. };
  18193. BoundingSphere.prototype.intersectsPoint = function (point) {
  18194. var x = this.centerWorld.x - point.x;
  18195. var y = this.centerWorld.y - point.y;
  18196. var z = this.centerWorld.z - point.z;
  18197. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18198. if (this.radiusWorld < distance)
  18199. return false;
  18200. return true;
  18201. };
  18202. // Statics
  18203. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18204. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18205. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18206. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18207. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18208. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18209. return false;
  18210. return true;
  18211. };
  18212. return BoundingSphere;
  18213. }());
  18214. BABYLON.BoundingSphere = BoundingSphere;
  18215. })(BABYLON || (BABYLON = {}));
  18216. //# sourceMappingURL=babylon.boundingSphere.js.map
  18217. var BABYLON;
  18218. (function (BABYLON) {
  18219. var BoundingBox = /** @class */ (function () {
  18220. /**
  18221. * Creates a new bounding box
  18222. * @param min defines the minimum vector (in local space)
  18223. * @param max defines the maximum vector (in local space)
  18224. */
  18225. function BoundingBox(min, max) {
  18226. this.vectorsWorld = new Array();
  18227. this.reConstruct(min, max);
  18228. }
  18229. // Methods
  18230. /**
  18231. * Recreates the entire bounding box from scratch
  18232. * @param min defines the new minimum vector (in local space)
  18233. * @param max defines the new maximum vector (in local space)
  18234. */
  18235. BoundingBox.prototype.reConstruct = function (min, max) {
  18236. this.minimum = min.clone();
  18237. this.maximum = max.clone();
  18238. // Bounding vectors
  18239. this.vectors = new Array();
  18240. this.vectors.push(this.minimum.clone());
  18241. this.vectors.push(this.maximum.clone());
  18242. this.vectors.push(this.minimum.clone());
  18243. this.vectors[2].x = this.maximum.x;
  18244. this.vectors.push(this.minimum.clone());
  18245. this.vectors[3].y = this.maximum.y;
  18246. this.vectors.push(this.minimum.clone());
  18247. this.vectors[4].z = this.maximum.z;
  18248. this.vectors.push(this.maximum.clone());
  18249. this.vectors[5].z = this.minimum.z;
  18250. this.vectors.push(this.maximum.clone());
  18251. this.vectors[6].x = this.minimum.x;
  18252. this.vectors.push(this.maximum.clone());
  18253. this.vectors[7].y = this.minimum.y;
  18254. // OBB
  18255. this.center = this.maximum.add(this.minimum).scale(0.5);
  18256. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18257. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18258. // World
  18259. for (var index = 0; index < this.vectors.length; index++) {
  18260. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18261. }
  18262. this.minimumWorld = BABYLON.Vector3.Zero();
  18263. this.maximumWorld = BABYLON.Vector3.Zero();
  18264. this.centerWorld = BABYLON.Vector3.Zero();
  18265. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18266. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18267. };
  18268. BoundingBox.prototype.getWorldMatrix = function () {
  18269. return this._worldMatrix;
  18270. };
  18271. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18272. this._worldMatrix.copyFrom(matrix);
  18273. return this;
  18274. };
  18275. BoundingBox.prototype._update = function (world) {
  18276. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18277. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18278. for (var index = 0; index < this.vectors.length; index++) {
  18279. var v = this.vectorsWorld[index];
  18280. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18281. if (v.x < this.minimumWorld.x)
  18282. this.minimumWorld.x = v.x;
  18283. if (v.y < this.minimumWorld.y)
  18284. this.minimumWorld.y = v.y;
  18285. if (v.z < this.minimumWorld.z)
  18286. this.minimumWorld.z = v.z;
  18287. if (v.x > this.maximumWorld.x)
  18288. this.maximumWorld.x = v.x;
  18289. if (v.y > this.maximumWorld.y)
  18290. this.maximumWorld.y = v.y;
  18291. if (v.z > this.maximumWorld.z)
  18292. this.maximumWorld.z = v.z;
  18293. }
  18294. // Extend
  18295. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18296. this.extendSizeWorld.scaleInPlace(0.5);
  18297. // OBB
  18298. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18299. this.centerWorld.scaleInPlace(0.5);
  18300. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18301. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18302. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18303. this._worldMatrix = world;
  18304. };
  18305. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18306. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18307. };
  18308. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18309. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18310. };
  18311. BoundingBox.prototype.intersectsPoint = function (point) {
  18312. var delta = -BABYLON.Epsilon;
  18313. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18314. return false;
  18315. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18316. return false;
  18317. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18318. return false;
  18319. return true;
  18320. };
  18321. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18322. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18323. };
  18324. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18325. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18326. return false;
  18327. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18328. return false;
  18329. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18330. return false;
  18331. return true;
  18332. };
  18333. // Statics
  18334. BoundingBox.Intersects = function (box0, box1) {
  18335. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18336. return false;
  18337. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18338. return false;
  18339. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18340. return false;
  18341. return true;
  18342. };
  18343. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18344. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18345. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18346. return (num <= (sphereRadius * sphereRadius));
  18347. };
  18348. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18349. for (var p = 0; p < 6; p++) {
  18350. for (var i = 0; i < 8; i++) {
  18351. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18352. return false;
  18353. }
  18354. }
  18355. }
  18356. return true;
  18357. };
  18358. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18359. for (var p = 0; p < 6; p++) {
  18360. var inCount = 8;
  18361. for (var i = 0; i < 8; i++) {
  18362. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18363. --inCount;
  18364. }
  18365. else {
  18366. break;
  18367. }
  18368. }
  18369. if (inCount === 0)
  18370. return false;
  18371. }
  18372. return true;
  18373. };
  18374. return BoundingBox;
  18375. }());
  18376. BABYLON.BoundingBox = BoundingBox;
  18377. })(BABYLON || (BABYLON = {}));
  18378. //# sourceMappingURL=babylon.boundingBox.js.map
  18379. var BABYLON;
  18380. (function (BABYLON) {
  18381. var computeBoxExtents = function (axis, box) {
  18382. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18383. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18384. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18385. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18386. var r = r0 + r1 + r2;
  18387. return {
  18388. min: p - r,
  18389. max: p + r
  18390. };
  18391. };
  18392. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18393. var axisOverlap = function (axis, box0, box1) {
  18394. var result0 = computeBoxExtents(axis, box0);
  18395. var result1 = computeBoxExtents(axis, box1);
  18396. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18397. };
  18398. var BoundingInfo = /** @class */ (function () {
  18399. function BoundingInfo(minimum, maximum) {
  18400. this.minimum = minimum;
  18401. this.maximum = maximum;
  18402. this._isLocked = false;
  18403. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18404. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18405. }
  18406. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18407. get: function () {
  18408. return this._isLocked;
  18409. },
  18410. set: function (value) {
  18411. this._isLocked = value;
  18412. },
  18413. enumerable: true,
  18414. configurable: true
  18415. });
  18416. // Methods
  18417. BoundingInfo.prototype.update = function (world) {
  18418. if (this._isLocked) {
  18419. return;
  18420. }
  18421. this.boundingBox._update(world);
  18422. this.boundingSphere._update(world);
  18423. };
  18424. /**
  18425. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18426. * @param center New center of the bounding info
  18427. * @param extend New extend of the bounding info
  18428. */
  18429. BoundingInfo.prototype.centerOn = function (center, extend) {
  18430. this.minimum = center.subtract(extend);
  18431. this.maximum = center.add(extend);
  18432. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18433. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18434. return this;
  18435. };
  18436. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18437. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18438. return false;
  18439. return this.boundingBox.isInFrustum(frustumPlanes);
  18440. };
  18441. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18442. /**
  18443. * Gets the world distance between the min and max points of the bounding box
  18444. */
  18445. get: function () {
  18446. var boundingBox = this.boundingBox;
  18447. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18448. return size.length();
  18449. },
  18450. enumerable: true,
  18451. configurable: true
  18452. });
  18453. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18454. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18455. };
  18456. BoundingInfo.prototype._checkCollision = function (collider) {
  18457. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18458. };
  18459. BoundingInfo.prototype.intersectsPoint = function (point) {
  18460. if (!this.boundingSphere.centerWorld) {
  18461. return false;
  18462. }
  18463. if (!this.boundingSphere.intersectsPoint(point)) {
  18464. return false;
  18465. }
  18466. if (!this.boundingBox.intersectsPoint(point)) {
  18467. return false;
  18468. }
  18469. return true;
  18470. };
  18471. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18472. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18473. return false;
  18474. }
  18475. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18476. return false;
  18477. }
  18478. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18479. return false;
  18480. }
  18481. if (!precise) {
  18482. return true;
  18483. }
  18484. var box0 = this.boundingBox;
  18485. var box1 = boundingInfo.boundingBox;
  18486. if (!axisOverlap(box0.directions[0], box0, box1))
  18487. return false;
  18488. if (!axisOverlap(box0.directions[1], box0, box1))
  18489. return false;
  18490. if (!axisOverlap(box0.directions[2], box0, box1))
  18491. return false;
  18492. if (!axisOverlap(box1.directions[0], box0, box1))
  18493. return false;
  18494. if (!axisOverlap(box1.directions[1], box0, box1))
  18495. return false;
  18496. if (!axisOverlap(box1.directions[2], box0, box1))
  18497. return false;
  18498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18499. return false;
  18500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18501. return false;
  18502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18503. return false;
  18504. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18505. return false;
  18506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18507. return false;
  18508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18509. return false;
  18510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18511. return false;
  18512. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18513. return false;
  18514. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18515. return false;
  18516. return true;
  18517. };
  18518. return BoundingInfo;
  18519. }());
  18520. BABYLON.BoundingInfo = BoundingInfo;
  18521. })(BABYLON || (BABYLON = {}));
  18522. //# sourceMappingURL=babylon.boundingInfo.js.map
  18523. var BABYLON;
  18524. (function (BABYLON) {
  18525. var TransformNode = /** @class */ (function (_super) {
  18526. __extends(TransformNode, _super);
  18527. function TransformNode(name, scene, isPure) {
  18528. if (scene === void 0) { scene = null; }
  18529. if (isPure === void 0) { isPure = true; }
  18530. var _this = _super.call(this, name, scene) || this;
  18531. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18532. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18533. _this._up = new BABYLON.Vector3(0, 1, 0);
  18534. _this._right = new BABYLON.Vector3(1, 0, 0);
  18535. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18536. // Properties
  18537. _this._rotation = BABYLON.Vector3.Zero();
  18538. _this._scaling = BABYLON.Vector3.One();
  18539. _this._isDirty = false;
  18540. /**
  18541. * Set the billboard mode. Default is 0.
  18542. *
  18543. * | Value | Type | Description |
  18544. * | --- | --- | --- |
  18545. * | 0 | BILLBOARDMODE_NONE | |
  18546. * | 1 | BILLBOARDMODE_X | |
  18547. * | 2 | BILLBOARDMODE_Y | |
  18548. * | 4 | BILLBOARDMODE_Z | |
  18549. * | 7 | BILLBOARDMODE_ALL | |
  18550. *
  18551. */
  18552. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18553. _this.scalingDeterminant = 1;
  18554. _this.infiniteDistance = false;
  18555. /**
  18556. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18557. * By default the system will update normals to compensate
  18558. */
  18559. _this.ignoreNonUniformScaling = false;
  18560. _this.position = BABYLON.Vector3.Zero();
  18561. _this._localWorld = BABYLON.Matrix.Zero();
  18562. _this._worldMatrix = BABYLON.Matrix.Zero();
  18563. _this._worldMatrixDeterminant = 0;
  18564. _this._absolutePosition = BABYLON.Vector3.Zero();
  18565. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18566. _this._postMultiplyPivotMatrix = false;
  18567. _this._isWorldMatrixFrozen = false;
  18568. /**
  18569. * An event triggered after the world matrix is updated
  18570. */
  18571. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18572. _this._nonUniformScaling = false;
  18573. if (isPure) {
  18574. _this.getScene().addTransformNode(_this);
  18575. }
  18576. return _this;
  18577. }
  18578. /**
  18579. * Gets a string idenfifying the name of the class
  18580. * @returns "TransformNode" string
  18581. */
  18582. TransformNode.prototype.getClassName = function () {
  18583. return "TransformNode";
  18584. };
  18585. Object.defineProperty(TransformNode.prototype, "rotation", {
  18586. /**
  18587. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18588. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18589. * Default : (0.0, 0.0, 0.0)
  18590. */
  18591. get: function () {
  18592. return this._rotation;
  18593. },
  18594. set: function (newRotation) {
  18595. this._rotation = newRotation;
  18596. },
  18597. enumerable: true,
  18598. configurable: true
  18599. });
  18600. Object.defineProperty(TransformNode.prototype, "scaling", {
  18601. /**
  18602. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18603. * Default : (1.0, 1.0, 1.0)
  18604. */
  18605. get: function () {
  18606. return this._scaling;
  18607. },
  18608. /**
  18609. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18610. * Default : (1.0, 1.0, 1.0)
  18611. */
  18612. set: function (newScaling) {
  18613. this._scaling = newScaling;
  18614. },
  18615. enumerable: true,
  18616. configurable: true
  18617. });
  18618. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18619. /**
  18620. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18621. * It's null by default.
  18622. * 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)
  18623. */
  18624. get: function () {
  18625. return this._rotationQuaternion;
  18626. },
  18627. set: function (quaternion) {
  18628. this._rotationQuaternion = quaternion;
  18629. //reset the rotation vector.
  18630. if (quaternion && this.rotation.length()) {
  18631. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18632. }
  18633. },
  18634. enumerable: true,
  18635. configurable: true
  18636. });
  18637. Object.defineProperty(TransformNode.prototype, "forward", {
  18638. /**
  18639. * The forward direction of that transform in world space.
  18640. */
  18641. get: function () {
  18642. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18643. },
  18644. enumerable: true,
  18645. configurable: true
  18646. });
  18647. Object.defineProperty(TransformNode.prototype, "up", {
  18648. /**
  18649. * The up direction of that transform in world space.
  18650. */
  18651. get: function () {
  18652. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18653. },
  18654. enumerable: true,
  18655. configurable: true
  18656. });
  18657. Object.defineProperty(TransformNode.prototype, "right", {
  18658. /**
  18659. * The right direction of that transform in world space.
  18660. */
  18661. get: function () {
  18662. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. /**
  18668. * Returns the latest update of the World matrix
  18669. * Returns a Matrix.
  18670. */
  18671. TransformNode.prototype.getWorldMatrix = function () {
  18672. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18673. this.computeWorldMatrix();
  18674. }
  18675. return this._worldMatrix;
  18676. };
  18677. /** @hidden */
  18678. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18679. return this._worldMatrixDeterminant;
  18680. };
  18681. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18682. /**
  18683. * Returns directly the latest state of the mesh World matrix.
  18684. * A Matrix is returned.
  18685. */
  18686. get: function () {
  18687. return this._worldMatrix;
  18688. },
  18689. enumerable: true,
  18690. configurable: true
  18691. });
  18692. /**
  18693. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18694. * Returns the TransformNode.
  18695. */
  18696. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18697. this._poseMatrix.copyFrom(matrix);
  18698. return this;
  18699. };
  18700. /**
  18701. * Returns the mesh Pose matrix.
  18702. * Returned object : Matrix
  18703. */
  18704. TransformNode.prototype.getPoseMatrix = function () {
  18705. return this._poseMatrix;
  18706. };
  18707. TransformNode.prototype._isSynchronized = function () {
  18708. if (this._isDirty) {
  18709. return false;
  18710. }
  18711. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18712. return false;
  18713. if (this._cache.pivotMatrixUpdated) {
  18714. return false;
  18715. }
  18716. if (this.infiniteDistance) {
  18717. return false;
  18718. }
  18719. if (!this._cache.position.equals(this.position))
  18720. return false;
  18721. if (this.rotationQuaternion) {
  18722. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18723. return false;
  18724. }
  18725. if (!this._cache.rotation.equals(this.rotation))
  18726. return false;
  18727. if (!this._cache.scaling.equals(this.scaling))
  18728. return false;
  18729. return true;
  18730. };
  18731. TransformNode.prototype._initCache = function () {
  18732. _super.prototype._initCache.call(this);
  18733. this._cache.localMatrixUpdated = false;
  18734. this._cache.position = BABYLON.Vector3.Zero();
  18735. this._cache.scaling = BABYLON.Vector3.Zero();
  18736. this._cache.rotation = BABYLON.Vector3.Zero();
  18737. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18738. this._cache.billboardMode = -1;
  18739. };
  18740. TransformNode.prototype.markAsDirty = function (property) {
  18741. if (property === "rotation") {
  18742. this.rotationQuaternion = null;
  18743. }
  18744. this._currentRenderId = Number.MAX_VALUE;
  18745. this._isDirty = true;
  18746. return this;
  18747. };
  18748. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18749. /**
  18750. * Returns the current mesh absolute position.
  18751. * Retuns a Vector3.
  18752. */
  18753. get: function () {
  18754. return this._absolutePosition;
  18755. },
  18756. enumerable: true,
  18757. configurable: true
  18758. });
  18759. /**
  18760. * Sets a new matrix to apply before all other transformation
  18761. * @param matrix defines the transform matrix
  18762. * @returns the current TransformNode
  18763. */
  18764. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18765. return this.setPivotMatrix(matrix, false);
  18766. };
  18767. /**
  18768. * Sets a new pivot matrix to the current node
  18769. * @param matrix defines the new pivot matrix to use
  18770. * @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
  18771. * @returns the current TransformNode
  18772. */
  18773. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18774. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18775. this._pivotMatrix = matrix.clone();
  18776. this._cache.pivotMatrixUpdated = true;
  18777. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18778. if (this._postMultiplyPivotMatrix) {
  18779. if (!this._pivotMatrixInverse) {
  18780. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18781. }
  18782. else {
  18783. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18784. }
  18785. }
  18786. return this;
  18787. };
  18788. /**
  18789. * Returns the mesh pivot matrix.
  18790. * Default : Identity.
  18791. * A Matrix is returned.
  18792. */
  18793. TransformNode.prototype.getPivotMatrix = function () {
  18794. return this._pivotMatrix;
  18795. };
  18796. /**
  18797. * Prevents the World matrix to be computed any longer.
  18798. * Returns the TransformNode.
  18799. */
  18800. TransformNode.prototype.freezeWorldMatrix = function () {
  18801. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18802. this.computeWorldMatrix(true);
  18803. this._isWorldMatrixFrozen = true;
  18804. return this;
  18805. };
  18806. /**
  18807. * Allows back the World matrix computation.
  18808. * Returns the TransformNode.
  18809. */
  18810. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18811. this._isWorldMatrixFrozen = false;
  18812. this.computeWorldMatrix(true);
  18813. return this;
  18814. };
  18815. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18816. /**
  18817. * True if the World matrix has been frozen.
  18818. * Returns a boolean.
  18819. */
  18820. get: function () {
  18821. return this._isWorldMatrixFrozen;
  18822. },
  18823. enumerable: true,
  18824. configurable: true
  18825. });
  18826. /**
  18827. * Retuns the mesh absolute position in the World.
  18828. * Returns a Vector3.
  18829. */
  18830. TransformNode.prototype.getAbsolutePosition = function () {
  18831. this.computeWorldMatrix();
  18832. return this._absolutePosition;
  18833. };
  18834. /**
  18835. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18836. * Returns the TransformNode.
  18837. */
  18838. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18839. if (!absolutePosition) {
  18840. return this;
  18841. }
  18842. var absolutePositionX;
  18843. var absolutePositionY;
  18844. var absolutePositionZ;
  18845. if (absolutePosition.x === undefined) {
  18846. if (arguments.length < 3) {
  18847. return this;
  18848. }
  18849. absolutePositionX = arguments[0];
  18850. absolutePositionY = arguments[1];
  18851. absolutePositionZ = arguments[2];
  18852. }
  18853. else {
  18854. absolutePositionX = absolutePosition.x;
  18855. absolutePositionY = absolutePosition.y;
  18856. absolutePositionZ = absolutePosition.z;
  18857. }
  18858. if (this.parent) {
  18859. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18860. invertParentWorldMatrix.invert();
  18861. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18862. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18863. }
  18864. else {
  18865. this.position.x = absolutePositionX;
  18866. this.position.y = absolutePositionY;
  18867. this.position.z = absolutePositionZ;
  18868. }
  18869. return this;
  18870. };
  18871. /**
  18872. * Sets the mesh position in its local space.
  18873. * Returns the TransformNode.
  18874. */
  18875. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18876. this.computeWorldMatrix();
  18877. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18878. return this;
  18879. };
  18880. /**
  18881. * Returns the mesh position in the local space from the current World matrix values.
  18882. * Returns a new Vector3.
  18883. */
  18884. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18885. this.computeWorldMatrix();
  18886. var invLocalWorldMatrix = this._localWorld.clone();
  18887. invLocalWorldMatrix.invert();
  18888. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18889. };
  18890. /**
  18891. * Translates the mesh along the passed Vector3 in its local space.
  18892. * Returns the TransformNode.
  18893. */
  18894. TransformNode.prototype.locallyTranslate = function (vector3) {
  18895. this.computeWorldMatrix(true);
  18896. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18897. return this;
  18898. };
  18899. /**
  18900. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18901. * @param targetPoint the position (must be in same space as current mesh) to look at
  18902. * @param yawCor optional yaw (y-axis) correction in radians
  18903. * @param pitchCor optional pitch (x-axis) correction in radians
  18904. * @param rollCor optional roll (z-axis) correction in radians
  18905. * @param space the choosen space of the target
  18906. * @returns the TransformNode.
  18907. */
  18908. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18909. if (yawCor === void 0) { yawCor = 0; }
  18910. if (pitchCor === void 0) { pitchCor = 0; }
  18911. if (rollCor === void 0) { rollCor = 0; }
  18912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18913. var dv = TransformNode._lookAtVectorCache;
  18914. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18915. targetPoint.subtractToRef(pos, dv);
  18916. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18917. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18918. var pitch = Math.atan2(dv.y, len);
  18919. if (this.rotationQuaternion) {
  18920. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18921. }
  18922. else {
  18923. this.rotation.x = pitch + pitchCor;
  18924. this.rotation.y = yaw + yawCor;
  18925. this.rotation.z = rollCor;
  18926. }
  18927. return this;
  18928. };
  18929. /**
  18930. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18931. * This Vector3 is expressed in the World space.
  18932. */
  18933. TransformNode.prototype.getDirection = function (localAxis) {
  18934. var result = BABYLON.Vector3.Zero();
  18935. this.getDirectionToRef(localAxis, result);
  18936. return result;
  18937. };
  18938. /**
  18939. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18940. * localAxis is expressed in the mesh local space.
  18941. * result is computed in the Wordl space from the mesh World matrix.
  18942. * Returns the TransformNode.
  18943. */
  18944. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18945. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18946. return this;
  18947. };
  18948. /**
  18949. * Sets a new pivot point to the current node
  18950. * @param point defines the new pivot point to use
  18951. * @param space defines if the point is in world or local space (local by default)
  18952. * @returns the current TransformNode
  18953. */
  18954. TransformNode.prototype.setPivotPoint = function (point, space) {
  18955. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18956. if (this.getScene().getRenderId() == 0) {
  18957. this.computeWorldMatrix(true);
  18958. }
  18959. var wm = this.getWorldMatrix();
  18960. if (space == BABYLON.Space.WORLD) {
  18961. var tmat = BABYLON.Tmp.Matrix[0];
  18962. wm.invertToRef(tmat);
  18963. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18964. }
  18965. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18966. };
  18967. /**
  18968. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18969. */
  18970. TransformNode.prototype.getPivotPoint = function () {
  18971. var point = BABYLON.Vector3.Zero();
  18972. this.getPivotPointToRef(point);
  18973. return point;
  18974. };
  18975. /**
  18976. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18977. * Returns the TransformNode.
  18978. */
  18979. TransformNode.prototype.getPivotPointToRef = function (result) {
  18980. result.x = -this._pivotMatrix.m[12];
  18981. result.y = -this._pivotMatrix.m[13];
  18982. result.z = -this._pivotMatrix.m[14];
  18983. return this;
  18984. };
  18985. /**
  18986. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18987. */
  18988. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18989. var point = BABYLON.Vector3.Zero();
  18990. this.getAbsolutePivotPointToRef(point);
  18991. return point;
  18992. };
  18993. /**
  18994. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18995. * Returns the TransformNode.
  18996. */
  18997. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18998. result.x = this._pivotMatrix.m[12];
  18999. result.y = this._pivotMatrix.m[13];
  19000. result.z = this._pivotMatrix.m[14];
  19001. this.getPivotPointToRef(result);
  19002. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19003. return this;
  19004. };
  19005. /**
  19006. * Defines the passed node as the parent of the current node.
  19007. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19008. * Returns the TransformNode.
  19009. */
  19010. TransformNode.prototype.setParent = function (node) {
  19011. if (!node && !this.parent) {
  19012. return this;
  19013. }
  19014. if (!node) {
  19015. var rotation = BABYLON.Tmp.Quaternion[0];
  19016. var position = BABYLON.Tmp.Vector3[0];
  19017. var scale = BABYLON.Tmp.Vector3[1];
  19018. if (this.parent && this.parent.computeWorldMatrix) {
  19019. this.parent.computeWorldMatrix(true);
  19020. }
  19021. this.computeWorldMatrix(true);
  19022. this.getWorldMatrix().decompose(scale, rotation, position);
  19023. if (this.rotationQuaternion) {
  19024. this.rotationQuaternion.copyFrom(rotation);
  19025. }
  19026. else {
  19027. rotation.toEulerAnglesToRef(this.rotation);
  19028. }
  19029. this.scaling.x = scale.x;
  19030. this.scaling.y = scale.y;
  19031. this.scaling.z = scale.z;
  19032. this.position.x = position.x;
  19033. this.position.y = position.y;
  19034. this.position.z = position.z;
  19035. }
  19036. else {
  19037. var rotation = BABYLON.Tmp.Quaternion[0];
  19038. var position = BABYLON.Tmp.Vector3[0];
  19039. var scale = BABYLON.Tmp.Vector3[1];
  19040. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19041. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19042. this.computeWorldMatrix(true);
  19043. node.computeWorldMatrix(true);
  19044. node.getWorldMatrix().invertToRef(invParentMatrix);
  19045. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19046. diffMatrix.decompose(scale, rotation, position);
  19047. if (this.rotationQuaternion) {
  19048. this.rotationQuaternion.copyFrom(rotation);
  19049. }
  19050. else {
  19051. rotation.toEulerAnglesToRef(this.rotation);
  19052. }
  19053. this.position.x = position.x;
  19054. this.position.y = position.y;
  19055. this.position.z = position.z;
  19056. this.scaling.x = scale.x;
  19057. this.scaling.y = scale.y;
  19058. this.scaling.z = scale.z;
  19059. }
  19060. this.parent = node;
  19061. return this;
  19062. };
  19063. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19064. get: function () {
  19065. return this._nonUniformScaling;
  19066. },
  19067. enumerable: true,
  19068. configurable: true
  19069. });
  19070. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19071. if (this._nonUniformScaling === value) {
  19072. return false;
  19073. }
  19074. this._nonUniformScaling = value;
  19075. return true;
  19076. };
  19077. /**
  19078. * Attach the current TransformNode to another TransformNode associated with a bone
  19079. * @param bone Bone affecting the TransformNode
  19080. * @param affectedTransformNode TransformNode associated with the bone
  19081. */
  19082. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19083. this._transformToBoneReferal = affectedTransformNode;
  19084. this.parent = bone;
  19085. if (bone.getWorldMatrix().determinant() < 0) {
  19086. this.scalingDeterminant *= -1;
  19087. }
  19088. return this;
  19089. };
  19090. TransformNode.prototype.detachFromBone = function () {
  19091. if (!this.parent) {
  19092. return this;
  19093. }
  19094. if (this.parent.getWorldMatrix().determinant() < 0) {
  19095. this.scalingDeterminant *= -1;
  19096. }
  19097. this._transformToBoneReferal = null;
  19098. this.parent = null;
  19099. return this;
  19100. };
  19101. /**
  19102. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19103. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19104. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19105. * The passed axis is also normalized.
  19106. * Returns the TransformNode.
  19107. */
  19108. TransformNode.prototype.rotate = function (axis, amount, space) {
  19109. axis.normalize();
  19110. if (!this.rotationQuaternion) {
  19111. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19112. this.rotation = BABYLON.Vector3.Zero();
  19113. }
  19114. var rotationQuaternion;
  19115. if (!space || space === BABYLON.Space.LOCAL) {
  19116. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19117. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19118. }
  19119. else {
  19120. if (this.parent) {
  19121. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19122. invertParentWorldMatrix.invert();
  19123. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19124. }
  19125. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19126. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19127. }
  19128. return this;
  19129. };
  19130. /**
  19131. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19132. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19133. * The passed axis is also normalized.
  19134. * Returns the TransformNode.
  19135. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19136. */
  19137. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19138. axis.normalize();
  19139. if (!this.rotationQuaternion) {
  19140. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19141. this.rotation.copyFromFloats(0, 0, 0);
  19142. }
  19143. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19144. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19145. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19146. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19147. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19148. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19149. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19150. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19151. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19152. return this;
  19153. };
  19154. /**
  19155. * Translates the mesh along the axis vector for the passed distance in the given space.
  19156. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19157. * Returns the TransformNode.
  19158. */
  19159. TransformNode.prototype.translate = function (axis, distance, space) {
  19160. var displacementVector = axis.scale(distance);
  19161. if (!space || space === BABYLON.Space.LOCAL) {
  19162. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19163. this.setPositionWithLocalVector(tempV3);
  19164. }
  19165. else {
  19166. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19167. }
  19168. return this;
  19169. };
  19170. /**
  19171. * Adds a rotation step to the mesh current rotation.
  19172. * x, y, z are Euler angles expressed in radians.
  19173. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19174. * This means this rotation is made in the mesh local space only.
  19175. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19176. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19177. * ```javascript
  19178. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19179. * ```
  19180. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19181. * 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.
  19182. * Returns the TransformNode.
  19183. */
  19184. TransformNode.prototype.addRotation = function (x, y, z) {
  19185. var rotationQuaternion;
  19186. if (this.rotationQuaternion) {
  19187. rotationQuaternion = this.rotationQuaternion;
  19188. }
  19189. else {
  19190. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19191. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19192. }
  19193. var accumulation = BABYLON.Tmp.Quaternion[0];
  19194. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19195. rotationQuaternion.multiplyInPlace(accumulation);
  19196. if (!this.rotationQuaternion) {
  19197. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19198. }
  19199. return this;
  19200. };
  19201. /**
  19202. * Computes the mesh World matrix and returns it.
  19203. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19204. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19205. * If the parameter `force`is set to `true`, the actual computation is done.
  19206. * Returns the mesh World Matrix.
  19207. */
  19208. TransformNode.prototype.computeWorldMatrix = function (force) {
  19209. if (this._isWorldMatrixFrozen) {
  19210. return this._worldMatrix;
  19211. }
  19212. if (!force && this.isSynchronized(true)) {
  19213. this._currentRenderId = this.getScene().getRenderId();
  19214. return this._worldMatrix;
  19215. }
  19216. this._cache.position.copyFrom(this.position);
  19217. this._cache.scaling.copyFrom(this.scaling);
  19218. this._cache.pivotMatrixUpdated = false;
  19219. this._cache.billboardMode = this.billboardMode;
  19220. this._currentRenderId = this.getScene().getRenderId();
  19221. this._childRenderId = this.getScene().getRenderId();
  19222. this._isDirty = false;
  19223. // Scaling
  19224. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19225. // Rotation
  19226. //rotate, if quaternion is set and rotation was used
  19227. if (this.rotationQuaternion) {
  19228. var len = this.rotation.length();
  19229. if (len) {
  19230. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19231. this.rotation.copyFromFloats(0, 0, 0);
  19232. }
  19233. }
  19234. if (this.rotationQuaternion) {
  19235. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19236. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19237. }
  19238. else {
  19239. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19240. this._cache.rotation.copyFrom(this.rotation);
  19241. }
  19242. // Translation
  19243. var camera = this.getScene().activeCamera;
  19244. if (this.infiniteDistance && !this.parent && camera) {
  19245. var cameraWorldMatrix = camera.getWorldMatrix();
  19246. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19247. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19248. }
  19249. else {
  19250. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19251. }
  19252. // Composing transformations
  19253. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19254. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19255. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19256. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19257. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19258. // Need to decompose each rotation here
  19259. var currentPosition = BABYLON.Tmp.Vector3[3];
  19260. if (this.parent && this.parent.getWorldMatrix) {
  19261. if (this._transformToBoneReferal) {
  19262. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19263. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19264. }
  19265. else {
  19266. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19267. }
  19268. }
  19269. else {
  19270. currentPosition.copyFrom(this.position);
  19271. }
  19272. currentPosition.subtractInPlace(camera.globalPosition);
  19273. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19274. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19275. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19276. }
  19277. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19278. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19279. }
  19280. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19281. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19282. }
  19283. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19284. }
  19285. else {
  19286. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19287. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19288. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19289. }
  19290. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19291. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19292. }
  19293. // Local world
  19294. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19295. // Parent
  19296. if (this.parent && this.parent.getWorldMatrix) {
  19297. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19298. if (this._transformToBoneReferal) {
  19299. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19300. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19301. }
  19302. else {
  19303. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19304. }
  19305. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19306. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19307. this._worldMatrix.copyFrom(this._localWorld);
  19308. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19309. }
  19310. else {
  19311. if (this._transformToBoneReferal) {
  19312. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19313. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19314. }
  19315. else {
  19316. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19317. }
  19318. }
  19319. this._markSyncedWithParent();
  19320. }
  19321. else {
  19322. this._worldMatrix.copyFrom(this._localWorld);
  19323. }
  19324. // Post multiply inverse of pivotMatrix
  19325. if (this._postMultiplyPivotMatrix) {
  19326. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19327. }
  19328. // Normal matrix
  19329. if (!this.ignoreNonUniformScaling) {
  19330. if (this.scaling.isNonUniform) {
  19331. this._updateNonUniformScalingState(true);
  19332. }
  19333. else if (this.parent && this.parent._nonUniformScaling) {
  19334. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19335. }
  19336. else {
  19337. this._updateNonUniformScalingState(false);
  19338. }
  19339. }
  19340. else {
  19341. this._updateNonUniformScalingState(false);
  19342. }
  19343. this._afterComputeWorldMatrix();
  19344. // Absolute position
  19345. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19346. // Callbacks
  19347. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19348. if (!this._poseMatrix) {
  19349. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19350. }
  19351. // Cache the determinant
  19352. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19353. return this._worldMatrix;
  19354. };
  19355. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19356. };
  19357. /**
  19358. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19359. * @param func: callback function to add
  19360. *
  19361. * Returns the TransformNode.
  19362. */
  19363. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19364. this.onAfterWorldMatrixUpdateObservable.add(func);
  19365. return this;
  19366. };
  19367. /**
  19368. * Removes a registered callback function.
  19369. * Returns the TransformNode.
  19370. */
  19371. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19372. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19373. return this;
  19374. };
  19375. /**
  19376. * Clone the current transform node
  19377. * Returns the new transform node
  19378. * @param name Name of the new clone
  19379. * @param newParent New parent for the clone
  19380. * @param doNotCloneChildren Do not clone children hierarchy
  19381. */
  19382. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19383. var _this = this;
  19384. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19385. result.name = name;
  19386. result.id = name;
  19387. if (newParent) {
  19388. result.parent = newParent;
  19389. }
  19390. if (!doNotCloneChildren) {
  19391. // Children
  19392. var directDescendants = this.getDescendants(true);
  19393. for (var index = 0; index < directDescendants.length; index++) {
  19394. var child = directDescendants[index];
  19395. if (child.clone) {
  19396. child.clone(name + "." + child.name, result);
  19397. }
  19398. }
  19399. }
  19400. return result;
  19401. };
  19402. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19403. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19404. serializationObject.type = this.getClassName();
  19405. // Parent
  19406. if (this.parent) {
  19407. serializationObject.parentId = this.parent.id;
  19408. }
  19409. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19410. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19411. }
  19412. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19413. serializationObject.isEnabled = this.isEnabled();
  19414. // Parent
  19415. if (this.parent) {
  19416. serializationObject.parentId = this.parent.id;
  19417. }
  19418. return serializationObject;
  19419. };
  19420. // Statics
  19421. /**
  19422. * Returns a new TransformNode object parsed from the source provided.
  19423. * The parameter `parsedMesh` is the source.
  19424. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19425. */
  19426. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19427. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19428. if (BABYLON.Tags) {
  19429. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19430. }
  19431. if (parsedTransformNode.localMatrix) {
  19432. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19433. }
  19434. else if (parsedTransformNode.pivotMatrix) {
  19435. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19436. }
  19437. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19438. // Parent
  19439. if (parsedTransformNode.parentId) {
  19440. transformNode._waitingParentId = parsedTransformNode.parentId;
  19441. }
  19442. return transformNode;
  19443. };
  19444. /**
  19445. * Releases resources associated with this transform node.
  19446. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19447. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19448. */
  19449. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19450. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19451. // Animations
  19452. this.getScene().stopAnimation(this);
  19453. // Remove from scene
  19454. this.getScene().removeTransformNode(this);
  19455. this.onAfterWorldMatrixUpdateObservable.clear();
  19456. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19457. };
  19458. // Statics
  19459. TransformNode.BILLBOARDMODE_NONE = 0;
  19460. TransformNode.BILLBOARDMODE_X = 1;
  19461. TransformNode.BILLBOARDMODE_Y = 2;
  19462. TransformNode.BILLBOARDMODE_Z = 4;
  19463. TransformNode.BILLBOARDMODE_ALL = 7;
  19464. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19465. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19466. __decorate([
  19467. BABYLON.serializeAsVector3()
  19468. ], TransformNode.prototype, "_rotation", void 0);
  19469. __decorate([
  19470. BABYLON.serializeAsQuaternion()
  19471. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19472. __decorate([
  19473. BABYLON.serializeAsVector3()
  19474. ], TransformNode.prototype, "_scaling", void 0);
  19475. __decorate([
  19476. BABYLON.serialize()
  19477. ], TransformNode.prototype, "billboardMode", void 0);
  19478. __decorate([
  19479. BABYLON.serialize()
  19480. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19481. __decorate([
  19482. BABYLON.serialize()
  19483. ], TransformNode.prototype, "infiniteDistance", void 0);
  19484. __decorate([
  19485. BABYLON.serialize()
  19486. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19487. __decorate([
  19488. BABYLON.serializeAsVector3()
  19489. ], TransformNode.prototype, "position", void 0);
  19490. return TransformNode;
  19491. }(BABYLON.Node));
  19492. BABYLON.TransformNode = TransformNode;
  19493. })(BABYLON || (BABYLON = {}));
  19494. //# sourceMappingURL=babylon.transformNode.js.map
  19495. var BABYLON;
  19496. (function (BABYLON) {
  19497. /**
  19498. * Class used to store all common mesh properties
  19499. */
  19500. var AbstractMesh = /** @class */ (function (_super) {
  19501. __extends(AbstractMesh, _super);
  19502. // Constructor
  19503. /**
  19504. * Creates a new AbstractMesh
  19505. * @param name defines the name of the mesh
  19506. * @param scene defines the hosting scene
  19507. */
  19508. function AbstractMesh(name, scene) {
  19509. if (scene === void 0) { scene = null; }
  19510. var _this = _super.call(this, name, scene, false) || this;
  19511. _this._facetNb = 0; // facet number
  19512. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19513. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19514. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19515. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19516. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19517. _this._subDiv = {
  19518. max: 1,
  19519. X: 1,
  19520. Y: 1,
  19521. Z: 1
  19522. };
  19523. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19524. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19525. // Events
  19526. /**
  19527. * An event triggered when this mesh collides with another one
  19528. */
  19529. _this.onCollideObservable = new BABYLON.Observable();
  19530. /**
  19531. * An event triggered when the collision's position changes
  19532. */
  19533. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19534. /**
  19535. * An event triggered when material is changed
  19536. */
  19537. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19538. // Properties
  19539. /**
  19540. * Gets or sets the orientation for POV movement & rotation
  19541. */
  19542. _this.definedFacingForward = true;
  19543. /**
  19544. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19545. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19546. * * 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.
  19547. * @see http://doc.babylonjs.com/features/occlusionquery
  19548. */
  19549. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19550. /**
  19551. * 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:
  19552. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19553. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19554. * * 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.
  19555. * @see http://doc.babylonjs.com/features/occlusionquery
  19556. */
  19557. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19558. /**
  19559. * 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.
  19560. * The default value is -1 which means don't break the query and wait till the result
  19561. * @see http://doc.babylonjs.com/features/occlusionquery
  19562. */
  19563. _this.occlusionRetryCount = -1;
  19564. _this._occlusionInternalRetryCounter = 0;
  19565. _this._isOccluded = false;
  19566. _this._isOcclusionQueryInProgress = false;
  19567. _this._visibility = 1.0;
  19568. /** Gets or sets the alpha index used to sort transparent meshes
  19569. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19570. */
  19571. _this.alphaIndex = Number.MAX_VALUE;
  19572. /**
  19573. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19574. */
  19575. _this.isVisible = true;
  19576. /**
  19577. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19578. */
  19579. _this.isPickable = true;
  19580. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19581. _this.showSubMeshesBoundingBox = false;
  19582. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19583. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19584. */
  19585. _this.isBlocker = false;
  19586. /**
  19587. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19588. */
  19589. _this.enablePointerMoveEvents = false;
  19590. /**
  19591. * Specifies the rendering group id for this mesh (0 by default)
  19592. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19593. */
  19594. _this.renderingGroupId = 0;
  19595. _this._receiveShadows = false;
  19596. /**
  19597. * Gets or sets a boolean indicating if the outline must be rendered as well
  19598. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19599. */
  19600. _this.renderOutline = false;
  19601. /** Defines color to use when rendering outline */
  19602. _this.outlineColor = BABYLON.Color3.Red();
  19603. /** Define width to use when rendering outline */
  19604. _this.outlineWidth = 0.02;
  19605. /**
  19606. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19607. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19608. */
  19609. _this.renderOverlay = false;
  19610. /** Defines color to use when rendering overlay */
  19611. _this.overlayColor = BABYLON.Color3.Red();
  19612. /** Defines alpha to use when rendering overlay */
  19613. _this.overlayAlpha = 0.5;
  19614. _this._hasVertexAlpha = false;
  19615. _this._useVertexColors = true;
  19616. _this._computeBonesUsingShaders = true;
  19617. _this._numBoneInfluencers = 4;
  19618. _this._applyFog = true;
  19619. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19620. _this.useOctreeForRenderingSelection = true;
  19621. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19622. _this.useOctreeForPicking = true;
  19623. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19624. _this.useOctreeForCollisions = true;
  19625. _this._layerMask = 0x0FFFFFFF;
  19626. /**
  19627. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19628. */
  19629. _this.alwaysSelectAsActiveMesh = false;
  19630. /**
  19631. * Gets or sets the current action manager
  19632. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19633. */
  19634. _this.actionManager = null;
  19635. /**
  19636. * Gets or sets impostor used for physic simulation
  19637. * @see http://doc.babylonjs.com/features/physics_engine
  19638. */
  19639. _this.physicsImpostor = null;
  19640. // Collisions
  19641. _this._checkCollisions = false;
  19642. _this._collisionMask = -1;
  19643. _this._collisionGroup = -1;
  19644. /**
  19645. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19646. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19647. */
  19648. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19649. /**
  19650. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19651. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19652. */
  19653. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19654. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19655. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19656. // Edges
  19657. /**
  19658. * Defines edge width used when edgesRenderer is enabled
  19659. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19660. */
  19661. _this.edgesWidth = 1;
  19662. /**
  19663. * Defines edge color used when edgesRenderer is enabled
  19664. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19665. */
  19666. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19667. // Cache
  19668. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19669. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19670. /** @hidden */
  19671. _this._renderId = 0;
  19672. /** @hidden */
  19673. _this._intersectionsInProgress = new Array();
  19674. /** @hidden */
  19675. _this._unIndexed = false;
  19676. /** @hidden */
  19677. _this._lightSources = new Array();
  19678. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19679. if (collidedMesh === void 0) { collidedMesh = null; }
  19680. //TODO move this to the collision coordinator!
  19681. if (_this.getScene().workerCollisions)
  19682. newPosition.multiplyInPlace(_this._collider._radius);
  19683. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19684. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19685. _this.position.addInPlace(_this._diffPositionForCollisions);
  19686. }
  19687. if (collidedMesh) {
  19688. _this.onCollideObservable.notifyObservers(collidedMesh);
  19689. }
  19690. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19691. };
  19692. _this.getScene().addMesh(_this);
  19693. _this._resyncLightSources();
  19694. return _this;
  19695. }
  19696. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19697. /**
  19698. * No billboard
  19699. */
  19700. get: function () {
  19701. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19707. /** Billboard on X axis */
  19708. get: function () {
  19709. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19715. /** Billboard on Y axis */
  19716. get: function () {
  19717. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19723. /** Billboard on Z axis */
  19724. get: function () {
  19725. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19731. /** Billboard on all axes */
  19732. get: function () {
  19733. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19734. },
  19735. enumerable: true,
  19736. configurable: true
  19737. });
  19738. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19739. /**
  19740. * Gets the number of facets in the mesh
  19741. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19742. */
  19743. get: function () {
  19744. return this._facetNb;
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19750. /**
  19751. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19752. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19753. */
  19754. get: function () {
  19755. return this._partitioningSubdivisions;
  19756. },
  19757. set: function (nb) {
  19758. this._partitioningSubdivisions = nb;
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19764. /**
  19765. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19766. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19767. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19768. */
  19769. get: function () {
  19770. return this._partitioningBBoxRatio;
  19771. },
  19772. set: function (ratio) {
  19773. this._partitioningBBoxRatio = ratio;
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19779. /**
  19780. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19781. * Works only for updatable meshes.
  19782. * Doesn't work with multi-materials
  19783. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19784. */
  19785. get: function () {
  19786. return this._facetDepthSort;
  19787. },
  19788. set: function (sort) {
  19789. this._facetDepthSort = sort;
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19795. /**
  19796. * The location (Vector3) where the facet depth sort must be computed from.
  19797. * By default, the active camera position.
  19798. * Used only when facet depth sort is enabled
  19799. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19800. */
  19801. get: function () {
  19802. return this._facetDepthSortFrom;
  19803. },
  19804. set: function (location) {
  19805. this._facetDepthSortFrom = location;
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19811. /**
  19812. * gets a boolean indicating if facetData is enabled
  19813. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19814. */
  19815. get: function () {
  19816. return this._facetDataEnabled;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. /** @hidden */
  19822. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19823. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19824. return false;
  19825. }
  19826. this._markSubMeshesAsMiscDirty();
  19827. return true;
  19828. };
  19829. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19830. /** Set a function to call when this mesh collides with another one */
  19831. set: function (callback) {
  19832. if (this._onCollideObserver) {
  19833. this.onCollideObservable.remove(this._onCollideObserver);
  19834. }
  19835. this._onCollideObserver = this.onCollideObservable.add(callback);
  19836. },
  19837. enumerable: true,
  19838. configurable: true
  19839. });
  19840. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19841. /** Set a function to call when the collision's position changes */
  19842. set: function (callback) {
  19843. if (this._onCollisionPositionChangeObserver) {
  19844. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19845. }
  19846. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19852. /**
  19853. * 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
  19854. * @see http://doc.babylonjs.com/features/occlusionquery
  19855. */
  19856. get: function () {
  19857. return this._isOccluded;
  19858. },
  19859. set: function (value) {
  19860. this._isOccluded = value;
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19866. /**
  19867. * Flag to check the progress status of the query
  19868. * @see http://doc.babylonjs.com/features/occlusionquery
  19869. */
  19870. get: function () {
  19871. return this._isOcclusionQueryInProgress;
  19872. },
  19873. enumerable: true,
  19874. configurable: true
  19875. });
  19876. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19877. /**
  19878. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19879. */
  19880. get: function () {
  19881. return this._visibility;
  19882. },
  19883. /**
  19884. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19885. */
  19886. set: function (value) {
  19887. if (this._visibility === value) {
  19888. return;
  19889. }
  19890. this._visibility = value;
  19891. this._markSubMeshesAsMiscDirty();
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(AbstractMesh.prototype, "material", {
  19897. /** Gets or sets current material */
  19898. get: function () {
  19899. return this._material;
  19900. },
  19901. set: function (value) {
  19902. if (this._material === value) {
  19903. return;
  19904. }
  19905. this._material = value;
  19906. if (this.onMaterialChangedObservable.hasObservers) {
  19907. this.onMaterialChangedObservable.notifyObservers(this);
  19908. }
  19909. if (!this.subMeshes) {
  19910. return;
  19911. }
  19912. this._unBindEffect();
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19918. /**
  19919. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19920. * @see http://doc.babylonjs.com/babylon101/shadows
  19921. */
  19922. get: function () {
  19923. return this._receiveShadows;
  19924. },
  19925. set: function (value) {
  19926. if (this._receiveShadows === value) {
  19927. return;
  19928. }
  19929. this._receiveShadows = value;
  19930. this._markSubMeshesAsLightDirty();
  19931. },
  19932. enumerable: true,
  19933. configurable: true
  19934. });
  19935. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19936. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19937. get: function () {
  19938. return this._hasVertexAlpha;
  19939. },
  19940. set: function (value) {
  19941. if (this._hasVertexAlpha === value) {
  19942. return;
  19943. }
  19944. this._hasVertexAlpha = value;
  19945. this._markSubMeshesAsAttributesDirty();
  19946. this._markSubMeshesAsMiscDirty();
  19947. },
  19948. enumerable: true,
  19949. configurable: true
  19950. });
  19951. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19952. /** 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) */
  19953. get: function () {
  19954. return this._useVertexColors;
  19955. },
  19956. set: function (value) {
  19957. if (this._useVertexColors === value) {
  19958. return;
  19959. }
  19960. this._useVertexColors = value;
  19961. this._markSubMeshesAsAttributesDirty();
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19967. /**
  19968. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19969. */
  19970. get: function () {
  19971. return this._computeBonesUsingShaders;
  19972. },
  19973. set: function (value) {
  19974. if (this._computeBonesUsingShaders === value) {
  19975. return;
  19976. }
  19977. this._computeBonesUsingShaders = value;
  19978. this._markSubMeshesAsAttributesDirty();
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19984. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19985. get: function () {
  19986. return this._numBoneInfluencers;
  19987. },
  19988. set: function (value) {
  19989. if (this._numBoneInfluencers === value) {
  19990. return;
  19991. }
  19992. this._numBoneInfluencers = value;
  19993. this._markSubMeshesAsAttributesDirty();
  19994. },
  19995. enumerable: true,
  19996. configurable: true
  19997. });
  19998. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19999. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20000. get: function () {
  20001. return this._applyFog;
  20002. },
  20003. set: function (value) {
  20004. if (this._applyFog === value) {
  20005. return;
  20006. }
  20007. this._applyFog = value;
  20008. this._markSubMeshesAsMiscDirty();
  20009. },
  20010. enumerable: true,
  20011. configurable: true
  20012. });
  20013. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20014. /**
  20015. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20016. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20017. */
  20018. get: function () {
  20019. return this._layerMask;
  20020. },
  20021. set: function (value) {
  20022. if (value === this._layerMask) {
  20023. return;
  20024. }
  20025. this._layerMask = value;
  20026. this._resyncLightSources();
  20027. },
  20028. enumerable: true,
  20029. configurable: true
  20030. });
  20031. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20032. /**
  20033. * Gets or sets a collision mask used to mask collisions (default is -1).
  20034. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20035. */
  20036. get: function () {
  20037. return this._collisionMask;
  20038. },
  20039. set: function (mask) {
  20040. this._collisionMask = !isNaN(mask) ? mask : -1;
  20041. },
  20042. enumerable: true,
  20043. configurable: true
  20044. });
  20045. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20046. /**
  20047. * Gets or sets the current collision group mask (-1 by default).
  20048. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20049. */
  20050. get: function () {
  20051. return this._collisionGroup;
  20052. },
  20053. set: function (mask) {
  20054. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20060. /** @hidden */
  20061. get: function () {
  20062. return null;
  20063. },
  20064. enumerable: true,
  20065. configurable: true
  20066. });
  20067. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20068. get: function () {
  20069. return this._skeleton;
  20070. },
  20071. /**
  20072. * Gets or sets a skeleton to apply skining transformations
  20073. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20074. */
  20075. set: function (value) {
  20076. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20077. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20078. }
  20079. if (value && value.needInitialSkinMatrix) {
  20080. value._registerMeshWithPoseMatrix(this);
  20081. }
  20082. this._skeleton = value;
  20083. if (!this._skeleton) {
  20084. this._bonesTransformMatrices = null;
  20085. }
  20086. this._markSubMeshesAsAttributesDirty();
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. /**
  20092. * Returns the string "AbstractMesh"
  20093. * @returns "AbstractMesh"
  20094. */
  20095. AbstractMesh.prototype.getClassName = function () {
  20096. return "AbstractMesh";
  20097. };
  20098. /**
  20099. * Gets a string representation of the current mesh
  20100. * @param fullDetails defines a boolean indicating if full details must be included
  20101. * @returns a string representation of the current mesh
  20102. */
  20103. AbstractMesh.prototype.toString = function (fullDetails) {
  20104. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20105. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20106. if (this._skeleton) {
  20107. ret += ", skeleton: " + this._skeleton.name;
  20108. }
  20109. if (fullDetails) {
  20110. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20111. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20112. }
  20113. return ret;
  20114. };
  20115. /** @hidden */
  20116. AbstractMesh.prototype._rebuild = function () {
  20117. if (this._occlusionQuery) {
  20118. this._occlusionQuery = null;
  20119. }
  20120. if (this._edgesRenderer) {
  20121. this._edgesRenderer._rebuild();
  20122. }
  20123. if (!this.subMeshes) {
  20124. return;
  20125. }
  20126. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20127. var subMesh = _a[_i];
  20128. subMesh._rebuild();
  20129. }
  20130. };
  20131. /** @hidden */
  20132. AbstractMesh.prototype._resyncLightSources = function () {
  20133. this._lightSources.length = 0;
  20134. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20135. var light = _a[_i];
  20136. if (!light.isEnabled()) {
  20137. continue;
  20138. }
  20139. if (light.canAffectMesh(this)) {
  20140. this._lightSources.push(light);
  20141. }
  20142. }
  20143. this._markSubMeshesAsLightDirty();
  20144. };
  20145. /** @hidden */
  20146. AbstractMesh.prototype._resyncLighSource = function (light) {
  20147. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20148. var index = this._lightSources.indexOf(light);
  20149. if (index === -1) {
  20150. if (!isIn) {
  20151. return;
  20152. }
  20153. this._lightSources.push(light);
  20154. }
  20155. else {
  20156. if (isIn) {
  20157. return;
  20158. }
  20159. this._lightSources.splice(index, 1);
  20160. }
  20161. this._markSubMeshesAsLightDirty();
  20162. };
  20163. /** @hidden */
  20164. AbstractMesh.prototype._unBindEffect = function () {
  20165. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20166. var subMesh = _a[_i];
  20167. subMesh.setEffect(null);
  20168. }
  20169. };
  20170. /** @hidden */
  20171. AbstractMesh.prototype._removeLightSource = function (light) {
  20172. var index = this._lightSources.indexOf(light);
  20173. if (index === -1) {
  20174. return;
  20175. }
  20176. this._lightSources.splice(index, 1);
  20177. this._markSubMeshesAsLightDirty();
  20178. };
  20179. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20180. if (!this.subMeshes) {
  20181. return;
  20182. }
  20183. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20184. var subMesh = _a[_i];
  20185. if (subMesh._materialDefines) {
  20186. func(subMesh._materialDefines);
  20187. }
  20188. }
  20189. };
  20190. /** @hidden */
  20191. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20192. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20193. };
  20194. /** @hidden */
  20195. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20196. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20197. };
  20198. /** @hidden */
  20199. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20200. if (!this.subMeshes) {
  20201. return;
  20202. }
  20203. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20204. var subMesh = _a[_i];
  20205. var material = subMesh.getMaterial();
  20206. if (material) {
  20207. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20208. }
  20209. }
  20210. };
  20211. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20212. /**
  20213. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20214. */
  20215. get: function () {
  20216. return this._scaling;
  20217. },
  20218. set: function (newScaling) {
  20219. this._scaling = newScaling;
  20220. if (this.physicsImpostor) {
  20221. this.physicsImpostor.forceUpdate();
  20222. }
  20223. },
  20224. enumerable: true,
  20225. configurable: true
  20226. });
  20227. // Methods
  20228. /**
  20229. * Disables the mesh edge rendering mode
  20230. * @returns the currentAbstractMesh
  20231. */
  20232. AbstractMesh.prototype.disableEdgesRendering = function () {
  20233. if (this._edgesRenderer) {
  20234. this._edgesRenderer.dispose();
  20235. this._edgesRenderer = null;
  20236. }
  20237. return this;
  20238. };
  20239. /**
  20240. * Enables the edge rendering mode on the mesh.
  20241. * This mode makes the mesh edges visible
  20242. * @param epsilon defines the maximal distance between two angles to detect a face
  20243. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20244. * @returns the currentAbstractMesh
  20245. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20246. */
  20247. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20248. if (epsilon === void 0) { epsilon = 0.95; }
  20249. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20250. this.disableEdgesRendering();
  20251. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20252. return this;
  20253. };
  20254. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20255. /**
  20256. * Gets the edgesRenderer associated with the mesh
  20257. */
  20258. get: function () {
  20259. return this._edgesRenderer;
  20260. },
  20261. enumerable: true,
  20262. configurable: true
  20263. });
  20264. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20265. /**
  20266. * Returns true if the mesh is blocked. Implemented by child classes
  20267. */
  20268. get: function () {
  20269. return false;
  20270. },
  20271. enumerable: true,
  20272. configurable: true
  20273. });
  20274. /**
  20275. * Returns the mesh itself by default. Implemented by child classes
  20276. * @param camera defines the camera to use to pick the right LOD level
  20277. * @returns the currentAbstractMesh
  20278. */
  20279. AbstractMesh.prototype.getLOD = function (camera) {
  20280. return this;
  20281. };
  20282. /**
  20283. * Returns 0 by default. Implemented by child classes
  20284. * @returns an integer
  20285. */
  20286. AbstractMesh.prototype.getTotalVertices = function () {
  20287. return 0;
  20288. };
  20289. /**
  20290. * Returns null by default. Implemented by child classes
  20291. * @returns null
  20292. */
  20293. AbstractMesh.prototype.getIndices = function () {
  20294. return null;
  20295. };
  20296. /**
  20297. * Returns the array of the requested vertex data kind. Implemented by child classes
  20298. * @param kind defines the vertex data kind to use
  20299. * @returns null
  20300. */
  20301. AbstractMesh.prototype.getVerticesData = function (kind) {
  20302. return null;
  20303. };
  20304. /**
  20305. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20306. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20307. * Note that a new underlying VertexBuffer object is created each call.
  20308. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20309. * @param kind defines vertex data kind:
  20310. * * BABYLON.VertexBuffer.PositionKind
  20311. * * BABYLON.VertexBuffer.UVKind
  20312. * * BABYLON.VertexBuffer.UV2Kind
  20313. * * BABYLON.VertexBuffer.UV3Kind
  20314. * * BABYLON.VertexBuffer.UV4Kind
  20315. * * BABYLON.VertexBuffer.UV5Kind
  20316. * * BABYLON.VertexBuffer.UV6Kind
  20317. * * BABYLON.VertexBuffer.ColorKind
  20318. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20319. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20320. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20321. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20322. * @param data defines the data source
  20323. * @param updatable defines if the data must be flagged as updatable (or static)
  20324. * @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
  20325. * @returns the current mesh
  20326. */
  20327. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20328. return this;
  20329. };
  20330. /**
  20331. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20332. * If the mesh has no geometry, it is simply returned as it is.
  20333. * @param kind defines vertex data kind:
  20334. * * BABYLON.VertexBuffer.PositionKind
  20335. * * BABYLON.VertexBuffer.UVKind
  20336. * * BABYLON.VertexBuffer.UV2Kind
  20337. * * BABYLON.VertexBuffer.UV3Kind
  20338. * * BABYLON.VertexBuffer.UV4Kind
  20339. * * BABYLON.VertexBuffer.UV5Kind
  20340. * * BABYLON.VertexBuffer.UV6Kind
  20341. * * BABYLON.VertexBuffer.ColorKind
  20342. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20343. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20344. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20345. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20346. * @param data defines the data source
  20347. * @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
  20348. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20349. * @returns the current mesh
  20350. */
  20351. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20352. return this;
  20353. };
  20354. /**
  20355. * Sets the mesh indices,
  20356. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20357. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20358. * @param totalVertices Defines the total number of vertices
  20359. * @returns the current mesh
  20360. */
  20361. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20362. return this;
  20363. };
  20364. /**
  20365. * Gets a boolean indicating if specific vertex data is present
  20366. * @param kind defines the vertex data kind to use
  20367. * @returns true is data kind is present
  20368. */
  20369. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20370. return false;
  20371. };
  20372. /**
  20373. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20374. * @returns a BoundingInfo
  20375. */
  20376. AbstractMesh.prototype.getBoundingInfo = function () {
  20377. if (this._masterMesh) {
  20378. return this._masterMesh.getBoundingInfo();
  20379. }
  20380. if (!this._boundingInfo) {
  20381. // this._boundingInfo is being created here
  20382. this._updateBoundingInfo();
  20383. }
  20384. // cannot be null.
  20385. return this._boundingInfo;
  20386. };
  20387. /**
  20388. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20389. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20390. * @returns the current mesh
  20391. */
  20392. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20393. if (includeDescendants === void 0) { includeDescendants = true; }
  20394. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20395. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20396. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20397. if (maxDimension === 0) {
  20398. return this;
  20399. }
  20400. var scale = 1 / maxDimension;
  20401. this.scaling.scaleInPlace(scale);
  20402. return this;
  20403. };
  20404. /**
  20405. * Overwrite the current bounding info
  20406. * @param boundingInfo defines the new bounding info
  20407. * @returns the current mesh
  20408. */
  20409. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20410. this._boundingInfo = boundingInfo;
  20411. return this;
  20412. };
  20413. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20414. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20415. get: function () {
  20416. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20417. },
  20418. enumerable: true,
  20419. configurable: true
  20420. });
  20421. /** @hidden */
  20422. AbstractMesh.prototype._preActivate = function () {
  20423. };
  20424. /** @hidden */
  20425. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20426. };
  20427. /** @hidden */
  20428. AbstractMesh.prototype._activate = function (renderId) {
  20429. this._renderId = renderId;
  20430. };
  20431. /**
  20432. * Gets the current world matrix
  20433. * @returns a Matrix
  20434. */
  20435. AbstractMesh.prototype.getWorldMatrix = function () {
  20436. if (this._masterMesh) {
  20437. return this._masterMesh.getWorldMatrix();
  20438. }
  20439. return _super.prototype.getWorldMatrix.call(this);
  20440. };
  20441. /** @hidden */
  20442. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20443. if (this._masterMesh) {
  20444. return this._masterMesh._getWorldMatrixDeterminant();
  20445. }
  20446. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20447. };
  20448. // ================================== Point of View Movement =================================
  20449. /**
  20450. * Perform relative position change from the point of view of behind the front of the mesh.
  20451. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20452. * Supports definition of mesh facing forward or backward
  20453. * @param amountRight defines the distance on the right axis
  20454. * @param amountUp defines the distance on the up axis
  20455. * @param amountForward defines the distance on the forward axis
  20456. * @returns the current mesh
  20457. */
  20458. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20459. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20460. return this;
  20461. };
  20462. /**
  20463. * Calculate relative position change from the point of view of behind the front of the mesh.
  20464. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20465. * Supports definition of mesh facing forward or backward
  20466. * @param amountRight defines the distance on the right axis
  20467. * @param amountUp defines the distance on the up axis
  20468. * @param amountForward defines the distance on the forward axis
  20469. * @returns the new displacement vector
  20470. */
  20471. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20472. var rotMatrix = new BABYLON.Matrix();
  20473. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20474. rotQuaternion.toRotationMatrix(rotMatrix);
  20475. var translationDelta = BABYLON.Vector3.Zero();
  20476. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20477. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20478. return translationDelta;
  20479. };
  20480. // ================================== Point of View Rotation =================================
  20481. /**
  20482. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20483. * Supports definition of mesh facing forward or backward
  20484. * @param flipBack defines the flip
  20485. * @param twirlClockwise defines the twirl
  20486. * @param tiltRight defines the tilt
  20487. * @returns the current mesh
  20488. */
  20489. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20490. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20491. return this;
  20492. };
  20493. /**
  20494. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20495. * Supports definition of mesh facing forward or backward.
  20496. * @param flipBack defines the flip
  20497. * @param twirlClockwise defines the twirl
  20498. * @param tiltRight defines the tilt
  20499. * @returns the new rotation vector
  20500. */
  20501. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20502. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20503. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20504. };
  20505. /**
  20506. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20507. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20508. * @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
  20509. * @returns the new bounding vectors
  20510. */
  20511. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20512. if (includeDescendants === void 0) { includeDescendants = true; }
  20513. if (predicate === void 0) { predicate = null; }
  20514. // Ensures that all world matrix will be recomputed.
  20515. this.getScene().incrementRenderId();
  20516. this.computeWorldMatrix(true);
  20517. var min;
  20518. var max;
  20519. var boundingInfo = this.getBoundingInfo();
  20520. if (!this.subMeshes) {
  20521. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20522. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20523. }
  20524. else {
  20525. min = boundingInfo.boundingBox.minimumWorld;
  20526. max = boundingInfo.boundingBox.maximumWorld;
  20527. }
  20528. if (includeDescendants) {
  20529. var descendants = this.getDescendants(false);
  20530. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20531. var descendant = descendants_1[_i];
  20532. var childMesh = descendant;
  20533. childMesh.computeWorldMatrix(true);
  20534. // Filters meshes based on custom predicate function.
  20535. if (predicate && !predicate(childMesh)) {
  20536. continue;
  20537. }
  20538. //make sure we have the needed params to get mix and max
  20539. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20540. continue;
  20541. }
  20542. var childBoundingInfo = childMesh.getBoundingInfo();
  20543. var boundingBox = childBoundingInfo.boundingBox;
  20544. var minBox = boundingBox.minimumWorld;
  20545. var maxBox = boundingBox.maximumWorld;
  20546. BABYLON.Tools.CheckExtends(minBox, min, max);
  20547. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20548. }
  20549. }
  20550. return {
  20551. min: min,
  20552. max: max
  20553. };
  20554. };
  20555. /** @hidden */
  20556. AbstractMesh.prototype._updateBoundingInfo = function () {
  20557. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20558. this._boundingInfo.update(this.worldMatrixFromCache);
  20559. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20560. return this;
  20561. };
  20562. /** @hidden */
  20563. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20564. if (!this.subMeshes) {
  20565. return this;
  20566. }
  20567. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20568. var subMesh = this.subMeshes[subIndex];
  20569. if (!subMesh.IsGlobal) {
  20570. subMesh.updateBoundingInfo(matrix);
  20571. }
  20572. }
  20573. return this;
  20574. };
  20575. /** @hidden */
  20576. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20577. // Bounding info
  20578. this._updateBoundingInfo();
  20579. };
  20580. /**
  20581. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20582. * A mesh is in the frustum if its bounding box intersects the frustum
  20583. * @param frustumPlanes defines the frustum to test
  20584. * @returns true if the mesh is in the frustum planes
  20585. */
  20586. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20587. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20588. };
  20589. /**
  20590. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20591. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20592. * @param frustumPlanes defines the frustum to test
  20593. * @returns true if the mesh is completely in the frustum planes
  20594. */
  20595. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20596. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20597. };
  20598. /**
  20599. * True if the mesh intersects another mesh or a SolidParticle object
  20600. * @param mesh defines a target mesh or SolidParticle to test
  20601. * @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)
  20602. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20603. * @returns true if there is an intersection
  20604. */
  20605. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20606. if (precise === void 0) { precise = false; }
  20607. if (!this._boundingInfo || !mesh._boundingInfo) {
  20608. return false;
  20609. }
  20610. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20611. return true;
  20612. }
  20613. if (includeDescendants) {
  20614. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20615. var child = _a[_i];
  20616. if (child.intersectsMesh(mesh, precise, true)) {
  20617. return true;
  20618. }
  20619. }
  20620. }
  20621. return false;
  20622. };
  20623. /**
  20624. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20625. * @param point defines the point to test
  20626. * @returns true if there is an intersection
  20627. */
  20628. AbstractMesh.prototype.intersectsPoint = function (point) {
  20629. if (!this._boundingInfo) {
  20630. return false;
  20631. }
  20632. return this._boundingInfo.intersectsPoint(point);
  20633. };
  20634. /**
  20635. * Gets the current physics impostor
  20636. * @see http://doc.babylonjs.com/features/physics_engine
  20637. * @returns a physics impostor or null
  20638. */
  20639. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20640. return this.physicsImpostor;
  20641. };
  20642. /**
  20643. * Gets the position of the current mesh in camera space
  20644. * @param camera defines the camera to use
  20645. * @returns a position
  20646. */
  20647. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20648. if (camera === void 0) { camera = null; }
  20649. if (!camera) {
  20650. camera = this.getScene().activeCamera;
  20651. }
  20652. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20653. };
  20654. /**
  20655. * Returns the distance from the mesh to the active camera
  20656. * @param camera defines the camera to use
  20657. * @returns the distance
  20658. */
  20659. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20660. if (camera === void 0) { camera = null; }
  20661. if (!camera) {
  20662. camera = this.getScene().activeCamera;
  20663. }
  20664. return this.absolutePosition.subtract(camera.position).length();
  20665. };
  20666. /**
  20667. * Apply a physic impulse to the mesh
  20668. * @param force defines the force to apply
  20669. * @param contactPoint defines where to apply the force
  20670. * @returns the current mesh
  20671. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20672. */
  20673. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20674. if (!this.physicsImpostor) {
  20675. return this;
  20676. }
  20677. this.physicsImpostor.applyImpulse(force, contactPoint);
  20678. return this;
  20679. };
  20680. /**
  20681. * Creates a physic joint between two meshes
  20682. * @param otherMesh defines the other mesh to use
  20683. * @param pivot1 defines the pivot to use on this mesh
  20684. * @param pivot2 defines the pivot to use on the other mesh
  20685. * @param options defines additional options (can be plugin dependent)
  20686. * @returns the current mesh
  20687. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20688. */
  20689. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20690. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20691. return this;
  20692. }
  20693. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20694. mainPivot: pivot1,
  20695. connectedPivot: pivot2,
  20696. nativeParams: options
  20697. });
  20698. return this;
  20699. };
  20700. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20701. // Collisions
  20702. /**
  20703. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20704. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20705. */
  20706. get: function () {
  20707. return this._checkCollisions;
  20708. },
  20709. set: function (collisionEnabled) {
  20710. this._checkCollisions = collisionEnabled;
  20711. if (this.getScene().workerCollisions) {
  20712. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20713. }
  20714. },
  20715. enumerable: true,
  20716. configurable: true
  20717. });
  20718. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20719. /**
  20720. * Gets Collider object used to compute collisions (not physics)
  20721. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20722. */
  20723. get: function () {
  20724. return this._collider;
  20725. },
  20726. enumerable: true,
  20727. configurable: true
  20728. });
  20729. /**
  20730. * Move the mesh using collision engine
  20731. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20732. * @param displacement defines the requested displacement vector
  20733. * @returns the current mesh
  20734. */
  20735. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20736. var globalPosition = this.getAbsolutePosition();
  20737. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20738. if (!this._collider) {
  20739. this._collider = new BABYLON.Collider();
  20740. }
  20741. this._collider._radius = this.ellipsoid;
  20742. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20743. return this;
  20744. };
  20745. // Submeshes octree
  20746. /**
  20747. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20748. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20749. * @param maxCapacity defines the maximum size of each block (64 by default)
  20750. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20751. * @returns the new octree
  20752. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20753. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20754. */
  20755. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20756. if (maxCapacity === void 0) { maxCapacity = 64; }
  20757. if (maxDepth === void 0) { maxDepth = 2; }
  20758. if (!this._submeshesOctree) {
  20759. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20760. }
  20761. this.computeWorldMatrix(true);
  20762. var boundingInfo = this.getBoundingInfo();
  20763. // Update octree
  20764. var bbox = boundingInfo.boundingBox;
  20765. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20766. return this._submeshesOctree;
  20767. };
  20768. // Collisions
  20769. /** @hidden */
  20770. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20771. this._generatePointsArray();
  20772. if (!this._positions) {
  20773. return this;
  20774. }
  20775. // Transformation
  20776. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20777. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20778. subMesh._lastColliderWorldVertices = [];
  20779. subMesh._trianglePlanes = [];
  20780. var start = subMesh.verticesStart;
  20781. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20782. for (var i = start; i < end; i++) {
  20783. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20784. }
  20785. }
  20786. // Collide
  20787. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20788. if (collider.collisionFound) {
  20789. collider.collidedMesh = this;
  20790. }
  20791. return this;
  20792. };
  20793. /** @hidden */
  20794. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20795. var subMeshes;
  20796. var len;
  20797. // Octrees
  20798. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20799. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20800. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20801. len = intersections.length;
  20802. subMeshes = intersections.data;
  20803. }
  20804. else {
  20805. subMeshes = this.subMeshes;
  20806. len = subMeshes.length;
  20807. }
  20808. for (var index = 0; index < len; index++) {
  20809. var subMesh = subMeshes[index];
  20810. // Bounding test
  20811. if (len > 1 && !subMesh._checkCollision(collider))
  20812. continue;
  20813. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20814. }
  20815. return this;
  20816. };
  20817. /** @hidden */
  20818. AbstractMesh.prototype._checkCollision = function (collider) {
  20819. // Bounding box test
  20820. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20821. return this;
  20822. // Transformation matrix
  20823. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20824. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20825. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20826. return this;
  20827. };
  20828. // Picking
  20829. /** @hidden */
  20830. AbstractMesh.prototype._generatePointsArray = function () {
  20831. return false;
  20832. };
  20833. /**
  20834. * Checks if the passed Ray intersects with the mesh
  20835. * @param ray defines the ray to use
  20836. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20837. * @returns the picking info
  20838. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20839. */
  20840. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20841. var pickingInfo = new BABYLON.PickingInfo();
  20842. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20843. return pickingInfo;
  20844. }
  20845. if (!this._generatePointsArray()) {
  20846. return pickingInfo;
  20847. }
  20848. var intersectInfo = null;
  20849. // Octrees
  20850. var subMeshes;
  20851. var len;
  20852. if (this._submeshesOctree && this.useOctreeForPicking) {
  20853. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20854. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20855. len = intersections.length;
  20856. subMeshes = intersections.data;
  20857. }
  20858. else {
  20859. subMeshes = this.subMeshes;
  20860. len = subMeshes.length;
  20861. }
  20862. for (var index = 0; index < len; index++) {
  20863. var subMesh = subMeshes[index];
  20864. // Bounding test
  20865. if (len > 1 && !subMesh.canIntersects(ray))
  20866. continue;
  20867. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20868. if (currentIntersectInfo) {
  20869. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20870. intersectInfo = currentIntersectInfo;
  20871. intersectInfo.subMeshId = index;
  20872. if (fastCheck) {
  20873. break;
  20874. }
  20875. }
  20876. }
  20877. }
  20878. if (intersectInfo) {
  20879. // Get picked point
  20880. var world = this.getWorldMatrix();
  20881. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20882. var direction = ray.direction.clone();
  20883. direction = direction.scale(intersectInfo.distance);
  20884. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20885. var pickedPoint = worldOrigin.add(worldDirection);
  20886. // Return result
  20887. pickingInfo.hit = true;
  20888. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20889. pickingInfo.pickedPoint = pickedPoint;
  20890. pickingInfo.pickedMesh = this;
  20891. pickingInfo.bu = intersectInfo.bu || 0;
  20892. pickingInfo.bv = intersectInfo.bv || 0;
  20893. pickingInfo.faceId = intersectInfo.faceId;
  20894. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20895. return pickingInfo;
  20896. }
  20897. return pickingInfo;
  20898. };
  20899. /**
  20900. * Clones the current mesh
  20901. * @param name defines the mesh name
  20902. * @param newParent defines the new mesh parent
  20903. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20904. * @returns the new mesh
  20905. */
  20906. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20907. return null;
  20908. };
  20909. /**
  20910. * Disposes all the submeshes of the current meshnp
  20911. * @returns the current mesh
  20912. */
  20913. AbstractMesh.prototype.releaseSubMeshes = function () {
  20914. if (this.subMeshes) {
  20915. while (this.subMeshes.length) {
  20916. this.subMeshes[0].dispose();
  20917. }
  20918. }
  20919. else {
  20920. this.subMeshes = new Array();
  20921. }
  20922. return this;
  20923. };
  20924. /**
  20925. * Releases resources associated with this abstract mesh.
  20926. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20927. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20928. */
  20929. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20930. var _this = this;
  20931. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20932. var index;
  20933. // Smart Array Retainers.
  20934. this.getScene().freeActiveMeshes();
  20935. this.getScene().freeRenderingGroups();
  20936. // Action manager
  20937. if (this.actionManager !== undefined && this.actionManager !== null) {
  20938. this.actionManager.dispose();
  20939. this.actionManager = null;
  20940. }
  20941. // Skeleton
  20942. this._skeleton = null;
  20943. // Physics
  20944. if (this.physicsImpostor) {
  20945. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20946. }
  20947. // Intersections in progress
  20948. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20949. var other = this._intersectionsInProgress[index];
  20950. var pos = other._intersectionsInProgress.indexOf(this);
  20951. other._intersectionsInProgress.splice(pos, 1);
  20952. }
  20953. this._intersectionsInProgress = [];
  20954. // Lights
  20955. var lights = this.getScene().lights;
  20956. lights.forEach(function (light) {
  20957. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20958. if (meshIndex !== -1) {
  20959. light.includedOnlyMeshes.splice(meshIndex, 1);
  20960. }
  20961. meshIndex = light.excludedMeshes.indexOf(_this);
  20962. if (meshIndex !== -1) {
  20963. light.excludedMeshes.splice(meshIndex, 1);
  20964. }
  20965. // Shadow generators
  20966. var generator = light.getShadowGenerator();
  20967. if (generator) {
  20968. var shadowMap = generator.getShadowMap();
  20969. if (shadowMap && shadowMap.renderList) {
  20970. meshIndex = shadowMap.renderList.indexOf(_this);
  20971. if (meshIndex !== -1) {
  20972. shadowMap.renderList.splice(meshIndex, 1);
  20973. }
  20974. }
  20975. }
  20976. });
  20977. // Edges
  20978. if (this._edgesRenderer) {
  20979. this._edgesRenderer.dispose();
  20980. this._edgesRenderer = null;
  20981. }
  20982. // SubMeshes
  20983. if (this.getClassName() !== "InstancedMesh") {
  20984. this.releaseSubMeshes();
  20985. }
  20986. // Octree
  20987. var sceneOctree = this.getScene().selectionOctree;
  20988. if (sceneOctree !== undefined && sceneOctree !== null) {
  20989. var index = sceneOctree.dynamicContent.indexOf(this);
  20990. if (index !== -1) {
  20991. sceneOctree.dynamicContent.splice(index, 1);
  20992. }
  20993. }
  20994. // Query
  20995. var engine = this.getScene().getEngine();
  20996. if (this._occlusionQuery) {
  20997. this._isOcclusionQueryInProgress = false;
  20998. engine.deleteQuery(this._occlusionQuery);
  20999. this._occlusionQuery = null;
  21000. }
  21001. // Engine
  21002. engine.wipeCaches();
  21003. // Remove from scene
  21004. this.getScene().removeMesh(this);
  21005. if (disposeMaterialAndTextures) {
  21006. if (this.material) {
  21007. this.material.dispose(false, true);
  21008. }
  21009. }
  21010. if (!doNotRecurse) {
  21011. // Particles
  21012. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21013. if (this.getScene().particleSystems[index].emitter === this) {
  21014. this.getScene().particleSystems[index].dispose();
  21015. index--;
  21016. }
  21017. }
  21018. }
  21019. // facet data
  21020. if (this._facetDataEnabled) {
  21021. this.disableFacetData();
  21022. }
  21023. this.onAfterWorldMatrixUpdateObservable.clear();
  21024. this.onCollideObservable.clear();
  21025. this.onCollisionPositionChangeObservable.clear();
  21026. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21027. };
  21028. /**
  21029. * Adds the passed mesh as a child to the current mesh
  21030. * @param mesh defines the child mesh
  21031. * @returns the current mesh
  21032. */
  21033. AbstractMesh.prototype.addChild = function (mesh) {
  21034. mesh.setParent(this);
  21035. return this;
  21036. };
  21037. /**
  21038. * Removes the passed mesh from the current mesh children list
  21039. * @param mesh defines the child mesh
  21040. * @returns the current mesh
  21041. */
  21042. AbstractMesh.prototype.removeChild = function (mesh) {
  21043. mesh.setParent(null);
  21044. return this;
  21045. };
  21046. // Facet data
  21047. /** @hidden */
  21048. AbstractMesh.prototype._initFacetData = function () {
  21049. if (!this._facetNormals) {
  21050. this._facetNormals = new Array();
  21051. }
  21052. if (!this._facetPositions) {
  21053. this._facetPositions = new Array();
  21054. }
  21055. if (!this._facetPartitioning) {
  21056. this._facetPartitioning = new Array();
  21057. }
  21058. this._facetNb = (this.getIndices().length / 3) | 0;
  21059. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21060. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21061. for (var f = 0; f < this._facetNb; f++) {
  21062. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21063. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21064. }
  21065. this._facetDataEnabled = true;
  21066. return this;
  21067. };
  21068. /**
  21069. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21070. * This method can be called within the render loop.
  21071. * 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
  21072. * @returns the current mesh
  21073. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21074. */
  21075. AbstractMesh.prototype.updateFacetData = function () {
  21076. if (!this._facetDataEnabled) {
  21077. this._initFacetData();
  21078. }
  21079. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21080. var indices = this.getIndices();
  21081. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21082. var bInfo = this.getBoundingInfo();
  21083. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21084. // init arrays, matrix and sort function on first call
  21085. this._facetDepthSortEnabled = true;
  21086. if (indices instanceof Uint16Array) {
  21087. this._depthSortedIndices = new Uint16Array(indices);
  21088. }
  21089. else if (indices instanceof Uint32Array) {
  21090. this._depthSortedIndices = new Uint32Array(indices);
  21091. }
  21092. else {
  21093. var needs32bits = false;
  21094. for (var i = 0; i < indices.length; i++) {
  21095. if (indices[i] > 65535) {
  21096. needs32bits = true;
  21097. break;
  21098. }
  21099. }
  21100. if (needs32bits) {
  21101. this._depthSortedIndices = new Uint32Array(indices);
  21102. }
  21103. else {
  21104. this._depthSortedIndices = new Uint16Array(indices);
  21105. }
  21106. }
  21107. this._facetDepthSortFunction = function (f1, f2) {
  21108. return (f2.sqDistance - f1.sqDistance);
  21109. };
  21110. if (!this._facetDepthSortFrom) {
  21111. var camera = this.getScene().activeCamera;
  21112. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21113. }
  21114. this._depthSortedFacets = [];
  21115. for (var f = 0; f < this._facetNb; f++) {
  21116. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21117. this._depthSortedFacets.push(depthSortedFacet);
  21118. }
  21119. this._invertedMatrix = BABYLON.Matrix.Identity();
  21120. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21121. }
  21122. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21123. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21124. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21125. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21126. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21127. this._subDiv.max = this._partitioningSubdivisions;
  21128. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21129. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21130. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21131. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21132. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21133. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21134. // set the parameters for ComputeNormals()
  21135. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21136. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21137. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21138. this._facetParameters.bInfo = bInfo;
  21139. this._facetParameters.bbSize = this._bbSize;
  21140. this._facetParameters.subDiv = this._subDiv;
  21141. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21142. this._facetParameters.depthSort = this._facetDepthSort;
  21143. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21144. this.computeWorldMatrix(true);
  21145. this._worldMatrix.invertToRef(this._invertedMatrix);
  21146. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21147. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21148. }
  21149. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21150. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21151. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21152. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21153. var l = (this._depthSortedIndices.length / 3) | 0;
  21154. for (var f = 0; f < l; f++) {
  21155. var sind = this._depthSortedFacets[f].ind;
  21156. this._depthSortedIndices[f * 3] = indices[sind];
  21157. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21158. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21159. }
  21160. this.updateIndices(this._depthSortedIndices);
  21161. }
  21162. return this;
  21163. };
  21164. /**
  21165. * Returns the facetLocalNormals array.
  21166. * The normals are expressed in the mesh local spac
  21167. * @returns an array of Vector3
  21168. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21169. */
  21170. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21171. if (!this._facetNormals) {
  21172. this.updateFacetData();
  21173. }
  21174. return this._facetNormals;
  21175. };
  21176. /**
  21177. * Returns the facetLocalPositions array.
  21178. * The facet positions are expressed in the mesh local space
  21179. * @returns an array of Vector3
  21180. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21181. */
  21182. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21183. if (!this._facetPositions) {
  21184. this.updateFacetData();
  21185. }
  21186. return this._facetPositions;
  21187. };
  21188. /**
  21189. * Returns the facetLocalPartioning array
  21190. * @returns an array of array of numbers
  21191. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21192. */
  21193. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21194. if (!this._facetPartitioning) {
  21195. this.updateFacetData();
  21196. }
  21197. return this._facetPartitioning;
  21198. };
  21199. /**
  21200. * Returns the i-th facet position in the world system.
  21201. * This method allocates a new Vector3 per call
  21202. * @param i defines the facet index
  21203. * @returns a new Vector3
  21204. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21205. */
  21206. AbstractMesh.prototype.getFacetPosition = function (i) {
  21207. var pos = BABYLON.Vector3.Zero();
  21208. this.getFacetPositionToRef(i, pos);
  21209. return pos;
  21210. };
  21211. /**
  21212. * Sets the reference Vector3 with the i-th facet position in the world system
  21213. * @param i defines the facet index
  21214. * @param ref defines the target vector
  21215. * @returns the current mesh
  21216. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21217. */
  21218. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21219. var localPos = (this.getFacetLocalPositions())[i];
  21220. var world = this.getWorldMatrix();
  21221. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21222. return this;
  21223. };
  21224. /**
  21225. * Returns the i-th facet normal in the world system.
  21226. * This method allocates a new Vector3 per call
  21227. * @param i defines the facet index
  21228. * @returns a new Vector3
  21229. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21230. */
  21231. AbstractMesh.prototype.getFacetNormal = function (i) {
  21232. var norm = BABYLON.Vector3.Zero();
  21233. this.getFacetNormalToRef(i, norm);
  21234. return norm;
  21235. };
  21236. /**
  21237. * Sets the reference Vector3 with the i-th facet normal in the world system
  21238. * @param i defines the facet index
  21239. * @param ref defines the target vector
  21240. * @returns the current mesh
  21241. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21242. */
  21243. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21244. var localNorm = (this.getFacetLocalNormals())[i];
  21245. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21246. return this;
  21247. };
  21248. /**
  21249. * 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)
  21250. * @param x defines x coordinate
  21251. * @param y defines y coordinate
  21252. * @param z defines z coordinate
  21253. * @returns the array of facet indexes
  21254. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21255. */
  21256. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21257. var bInfo = this.getBoundingInfo();
  21258. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21259. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21260. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21261. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21262. return null;
  21263. }
  21264. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21265. };
  21266. /**
  21267. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21268. * @param projected sets as the (x,y,z) world projection on the facet
  21269. * @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
  21270. * @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
  21271. * @param x defines x coordinate
  21272. * @param y defines y coordinate
  21273. * @param z defines z coordinate
  21274. * @returns the face index if found (or null instead)
  21275. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21276. */
  21277. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21278. if (checkFace === void 0) { checkFace = false; }
  21279. if (facing === void 0) { facing = true; }
  21280. var world = this.getWorldMatrix();
  21281. var invMat = BABYLON.Tmp.Matrix[5];
  21282. world.invertToRef(invMat);
  21283. var invVect = BABYLON.Tmp.Vector3[8];
  21284. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21285. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21286. if (projected) {
  21287. // tranform the local computed projected vector to world coordinates
  21288. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21289. }
  21290. return closest;
  21291. };
  21292. /**
  21293. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21294. * @param projected sets as the (x,y,z) local projection on the facet
  21295. * @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
  21296. * @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
  21297. * @param x defines x coordinate
  21298. * @param y defines y coordinate
  21299. * @param z defines z coordinate
  21300. * @returns the face index if found (or null instead)
  21301. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21302. */
  21303. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21304. if (checkFace === void 0) { checkFace = false; }
  21305. if (facing === void 0) { facing = true; }
  21306. var closest = null;
  21307. var tmpx = 0.0;
  21308. var tmpy = 0.0;
  21309. var tmpz = 0.0;
  21310. var d = 0.0; // tmp dot facet normal * facet position
  21311. var t0 = 0.0;
  21312. var projx = 0.0;
  21313. var projy = 0.0;
  21314. var projz = 0.0;
  21315. // Get all the facets in the same partitioning block than (x, y, z)
  21316. var facetPositions = this.getFacetLocalPositions();
  21317. var facetNormals = this.getFacetLocalNormals();
  21318. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21319. if (!facetsInBlock) {
  21320. return null;
  21321. }
  21322. // Get the closest facet to (x, y, z)
  21323. var shortest = Number.MAX_VALUE; // init distance vars
  21324. var tmpDistance = shortest;
  21325. var fib; // current facet in the block
  21326. var norm; // current facet normal
  21327. var p0; // current facet barycenter position
  21328. // loop on all the facets in the current partitioning block
  21329. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21330. fib = facetsInBlock[idx];
  21331. norm = facetNormals[fib];
  21332. p0 = facetPositions[fib];
  21333. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21334. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21335. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21336. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21337. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21338. projx = x + norm.x * t0;
  21339. projy = y + norm.y * t0;
  21340. projz = z + norm.z * t0;
  21341. tmpx = projx - x;
  21342. tmpy = projy - y;
  21343. tmpz = projz - z;
  21344. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21345. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21346. shortest = tmpDistance;
  21347. closest = fib;
  21348. if (projected) {
  21349. projected.x = projx;
  21350. projected.y = projy;
  21351. projected.z = projz;
  21352. }
  21353. }
  21354. }
  21355. }
  21356. return closest;
  21357. };
  21358. /**
  21359. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21360. * @returns the parameters
  21361. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21362. */
  21363. AbstractMesh.prototype.getFacetDataParameters = function () {
  21364. return this._facetParameters;
  21365. };
  21366. /**
  21367. * Disables the feature FacetData and frees the related memory
  21368. * @returns the current mesh
  21369. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21370. */
  21371. AbstractMesh.prototype.disableFacetData = function () {
  21372. if (this._facetDataEnabled) {
  21373. this._facetDataEnabled = false;
  21374. this._facetPositions = new Array();
  21375. this._facetNormals = new Array();
  21376. this._facetPartitioning = new Array();
  21377. this._facetParameters = null;
  21378. this._depthSortedIndices = new Uint32Array(0);
  21379. }
  21380. return this;
  21381. };
  21382. /**
  21383. * Updates the AbstractMesh indices array
  21384. * @param indices defines the data source
  21385. * @returns the current mesh
  21386. */
  21387. AbstractMesh.prototype.updateIndices = function (indices) {
  21388. return this;
  21389. };
  21390. /**
  21391. * Creates new normals data for the mesh
  21392. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21393. * @returns the current mesh
  21394. */
  21395. AbstractMesh.prototype.createNormals = function (updatable) {
  21396. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21397. var indices = this.getIndices();
  21398. var normals;
  21399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21400. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21401. }
  21402. else {
  21403. normals = [];
  21404. }
  21405. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21406. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21407. return this;
  21408. };
  21409. /**
  21410. * Align the mesh with a normal
  21411. * @param normal defines the normal to use
  21412. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21413. * @returns the current mesh
  21414. */
  21415. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21416. if (!upDirection) {
  21417. upDirection = BABYLON.Axis.Y;
  21418. }
  21419. var axisX = BABYLON.Tmp.Vector3[0];
  21420. var axisZ = BABYLON.Tmp.Vector3[1];
  21421. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21422. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21423. if (this.rotationQuaternion) {
  21424. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21425. }
  21426. else {
  21427. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21428. }
  21429. return this;
  21430. };
  21431. /** @hidden */
  21432. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21433. var engine = this.getEngine();
  21434. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21435. this._isOccluded = false;
  21436. return;
  21437. }
  21438. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21439. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21440. if (isOcclusionQueryAvailable) {
  21441. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21442. this._isOcclusionQueryInProgress = false;
  21443. this._occlusionInternalRetryCounter = 0;
  21444. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21445. }
  21446. else {
  21447. this._occlusionInternalRetryCounter++;
  21448. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21449. this._isOcclusionQueryInProgress = false;
  21450. this._occlusionInternalRetryCounter = 0;
  21451. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21452. // if strict continue the last state of the object.
  21453. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21454. }
  21455. else {
  21456. return;
  21457. }
  21458. }
  21459. }
  21460. // Todo. Move into an occlusion query component.
  21461. var scene = this.getScene();
  21462. if (scene.getBoundingBoxRenderer) {
  21463. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21464. if (!this._occlusionQuery) {
  21465. this._occlusionQuery = engine.createQuery();
  21466. }
  21467. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21468. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21469. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21470. this._isOcclusionQueryInProgress = true;
  21471. }
  21472. };
  21473. /** No occlusion */
  21474. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21475. /** Occlusion set to optimisitic */
  21476. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21477. /** Occlusion set to strict */
  21478. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21479. /** Use an accurante occlusion algorithm */
  21480. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21481. /** Use a conservative occlusion algorithm */
  21482. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21483. return AbstractMesh;
  21484. }(BABYLON.TransformNode));
  21485. BABYLON.AbstractMesh = AbstractMesh;
  21486. })(BABYLON || (BABYLON = {}));
  21487. //# sourceMappingURL=babylon.abstractMesh.js.map
  21488. var BABYLON;
  21489. (function (BABYLON) {
  21490. /**
  21491. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21492. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21493. * 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.
  21494. */
  21495. var Light = /** @class */ (function (_super) {
  21496. __extends(Light, _super);
  21497. /**
  21498. * Creates a Light object in the scene.
  21499. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21500. * @param name The firendly name of the light
  21501. * @param scene The scene the light belongs too
  21502. */
  21503. function Light(name, scene) {
  21504. var _this = _super.call(this, name, scene) || this;
  21505. /**
  21506. * Diffuse gives the basic color to an object.
  21507. */
  21508. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21509. /**
  21510. * Specular produces a highlight color on an object.
  21511. * Note: This is note affecting PBR materials.
  21512. */
  21513. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21514. /**
  21515. * Strength of the light.
  21516. * Note: By default it is define in the framework own unit.
  21517. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21518. */
  21519. _this.intensity = 1.0;
  21520. /**
  21521. * Defines how far from the source the light is impacting in scene units.
  21522. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21523. */
  21524. _this.range = Number.MAX_VALUE;
  21525. /**
  21526. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21527. * of light.
  21528. */
  21529. _this._photometricScale = 1.0;
  21530. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21531. _this._radius = 0.00001;
  21532. /**
  21533. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21534. * exceeding the number allowed of the materials.
  21535. */
  21536. _this.renderPriority = 0;
  21537. _this._shadowEnabled = true;
  21538. _this._excludeWithLayerMask = 0;
  21539. _this._includeOnlyWithLayerMask = 0;
  21540. _this._lightmapMode = 0;
  21541. /**
  21542. * @hidden Internal use only.
  21543. */
  21544. _this._excludedMeshesIds = new Array();
  21545. /**
  21546. * @hidden Internal use only.
  21547. */
  21548. _this._includedOnlyMeshesIds = new Array();
  21549. _this.getScene().addLight(_this);
  21550. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21551. _this._buildUniformLayout();
  21552. _this.includedOnlyMeshes = new Array();
  21553. _this.excludedMeshes = new Array();
  21554. _this._resyncMeshes();
  21555. return _this;
  21556. }
  21557. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21558. /**
  21559. * If every light affecting the material is in this lightmapMode,
  21560. * material.lightmapTexture adds or multiplies
  21561. * (depends on material.useLightmapAsShadowmap)
  21562. * after every other light calculations.
  21563. */
  21564. get: function () {
  21565. return Light._LIGHTMAP_DEFAULT;
  21566. },
  21567. enumerable: true,
  21568. configurable: true
  21569. });
  21570. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21571. /**
  21572. * material.lightmapTexture as only diffuse lighting from this light
  21573. * adds only specular lighting from this light
  21574. * adds dynamic shadows
  21575. */
  21576. get: function () {
  21577. return Light._LIGHTMAP_SPECULAR;
  21578. },
  21579. enumerable: true,
  21580. configurable: true
  21581. });
  21582. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21583. /**
  21584. * material.lightmapTexture as only lighting
  21585. * no light calculation from this light
  21586. * only adds dynamic shadows from this light
  21587. */
  21588. get: function () {
  21589. return Light._LIGHTMAP_SHADOWSONLY;
  21590. },
  21591. enumerable: true,
  21592. configurable: true
  21593. });
  21594. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21595. /**
  21596. * Each light type uses the default quantity according to its type:
  21597. * point/spot lights use luminous intensity
  21598. * directional lights use illuminance
  21599. */
  21600. get: function () {
  21601. return Light._INTENSITYMODE_AUTOMATIC;
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21607. /**
  21608. * lumen (lm)
  21609. */
  21610. get: function () {
  21611. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21617. /**
  21618. * candela (lm/sr)
  21619. */
  21620. get: function () {
  21621. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21627. /**
  21628. * lux (lm/m^2)
  21629. */
  21630. get: function () {
  21631. return Light._INTENSITYMODE_ILLUMINANCE;
  21632. },
  21633. enumerable: true,
  21634. configurable: true
  21635. });
  21636. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21637. /**
  21638. * nit (cd/m^2)
  21639. */
  21640. get: function () {
  21641. return Light._INTENSITYMODE_LUMINANCE;
  21642. },
  21643. enumerable: true,
  21644. configurable: true
  21645. });
  21646. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21647. /**
  21648. * Light type const id of the point light.
  21649. */
  21650. get: function () {
  21651. return Light._LIGHTTYPEID_POINTLIGHT;
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21657. /**
  21658. * Light type const id of the directional light.
  21659. */
  21660. get: function () {
  21661. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21667. /**
  21668. * Light type const id of the spot light.
  21669. */
  21670. get: function () {
  21671. return Light._LIGHTTYPEID_SPOTLIGHT;
  21672. },
  21673. enumerable: true,
  21674. configurable: true
  21675. });
  21676. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21677. /**
  21678. * Light type const id of the hemispheric light.
  21679. */
  21680. get: function () {
  21681. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21682. },
  21683. enumerable: true,
  21684. configurable: true
  21685. });
  21686. Object.defineProperty(Light.prototype, "intensityMode", {
  21687. /**
  21688. * Gets the photometric scale used to interpret the intensity.
  21689. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21690. */
  21691. get: function () {
  21692. return this._intensityMode;
  21693. },
  21694. /**
  21695. * Sets the photometric scale used to interpret the intensity.
  21696. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21697. */
  21698. set: function (value) {
  21699. this._intensityMode = value;
  21700. this._computePhotometricScale();
  21701. },
  21702. enumerable: true,
  21703. configurable: true
  21704. });
  21705. ;
  21706. ;
  21707. Object.defineProperty(Light.prototype, "radius", {
  21708. /**
  21709. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21710. */
  21711. get: function () {
  21712. return this._radius;
  21713. },
  21714. /**
  21715. * sets the light radius used by PBR Materials to simulate soft area lights.
  21716. */
  21717. set: function (value) {
  21718. this._radius = value;
  21719. this._computePhotometricScale();
  21720. },
  21721. enumerable: true,
  21722. configurable: true
  21723. });
  21724. ;
  21725. ;
  21726. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21727. /**
  21728. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21729. * the current shadow generator.
  21730. */
  21731. get: function () {
  21732. return this._shadowEnabled;
  21733. },
  21734. /**
  21735. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21736. * the current shadow generator.
  21737. */
  21738. set: function (value) {
  21739. if (this._shadowEnabled === value) {
  21740. return;
  21741. }
  21742. this._shadowEnabled = value;
  21743. this._markMeshesAsLightDirty();
  21744. },
  21745. enumerable: true,
  21746. configurable: true
  21747. });
  21748. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21749. /**
  21750. * Gets the only meshes impacted by this light.
  21751. */
  21752. get: function () {
  21753. return this._includedOnlyMeshes;
  21754. },
  21755. /**
  21756. * Sets the only meshes impacted by this light.
  21757. */
  21758. set: function (value) {
  21759. this._includedOnlyMeshes = value;
  21760. this._hookArrayForIncludedOnly(value);
  21761. },
  21762. enumerable: true,
  21763. configurable: true
  21764. });
  21765. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21766. /**
  21767. * Gets the meshes not impacted by this light.
  21768. */
  21769. get: function () {
  21770. return this._excludedMeshes;
  21771. },
  21772. /**
  21773. * Sets the meshes not impacted by this light.
  21774. */
  21775. set: function (value) {
  21776. this._excludedMeshes = value;
  21777. this._hookArrayForExcluded(value);
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21783. /**
  21784. * Gets the layer id use to find what meshes are not impacted by the light.
  21785. * Inactive if 0
  21786. */
  21787. get: function () {
  21788. return this._excludeWithLayerMask;
  21789. },
  21790. /**
  21791. * Sets the layer id use to find what meshes are not impacted by the light.
  21792. * Inactive if 0
  21793. */
  21794. set: function (value) {
  21795. this._excludeWithLayerMask = value;
  21796. this._resyncMeshes();
  21797. },
  21798. enumerable: true,
  21799. configurable: true
  21800. });
  21801. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21802. /**
  21803. * Gets the layer id use to find what meshes are impacted by the light.
  21804. * Inactive if 0
  21805. */
  21806. get: function () {
  21807. return this._includeOnlyWithLayerMask;
  21808. },
  21809. /**
  21810. * Sets the layer id use to find what meshes are impacted by the light.
  21811. * Inactive if 0
  21812. */
  21813. set: function (value) {
  21814. this._includeOnlyWithLayerMask = value;
  21815. this._resyncMeshes();
  21816. },
  21817. enumerable: true,
  21818. configurable: true
  21819. });
  21820. Object.defineProperty(Light.prototype, "lightmapMode", {
  21821. /**
  21822. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21823. */
  21824. get: function () {
  21825. return this._lightmapMode;
  21826. },
  21827. /**
  21828. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21829. */
  21830. set: function (value) {
  21831. if (this._lightmapMode === value) {
  21832. return;
  21833. }
  21834. this._lightmapMode = value;
  21835. this._markMeshesAsLightDirty();
  21836. },
  21837. enumerable: true,
  21838. configurable: true
  21839. });
  21840. /**
  21841. * Returns the string "Light".
  21842. * @returns the class name
  21843. */
  21844. Light.prototype.getClassName = function () {
  21845. return "Light";
  21846. };
  21847. /**
  21848. * Converts the light information to a readable string for debug purpose.
  21849. * @param fullDetails Supports for multiple levels of logging within scene loading
  21850. * @returns the human readable light info
  21851. */
  21852. Light.prototype.toString = function (fullDetails) {
  21853. var ret = "Name: " + this.name;
  21854. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21855. if (this.animations) {
  21856. for (var i = 0; i < this.animations.length; i++) {
  21857. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21858. }
  21859. }
  21860. if (fullDetails) {
  21861. }
  21862. return ret;
  21863. };
  21864. /**
  21865. * Set the enabled state of this node.
  21866. * @param value - the new enabled state
  21867. */
  21868. Light.prototype.setEnabled = function (value) {
  21869. _super.prototype.setEnabled.call(this, value);
  21870. this._resyncMeshes();
  21871. };
  21872. /**
  21873. * Returns the Light associated shadow generator if any.
  21874. * @return the associated shadow generator.
  21875. */
  21876. Light.prototype.getShadowGenerator = function () {
  21877. return this._shadowGenerator;
  21878. };
  21879. /**
  21880. * Returns a Vector3, the absolute light position in the World.
  21881. * @returns the world space position of the light
  21882. */
  21883. Light.prototype.getAbsolutePosition = function () {
  21884. return BABYLON.Vector3.Zero();
  21885. };
  21886. /**
  21887. * Specifies if the light will affect the passed mesh.
  21888. * @param mesh The mesh to test against the light
  21889. * @return true the mesh is affected otherwise, false.
  21890. */
  21891. Light.prototype.canAffectMesh = function (mesh) {
  21892. if (!mesh) {
  21893. return true;
  21894. }
  21895. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21896. return false;
  21897. }
  21898. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21899. return false;
  21900. }
  21901. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21902. return false;
  21903. }
  21904. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21905. return false;
  21906. }
  21907. return true;
  21908. };
  21909. /**
  21910. * Computes and Returns the light World matrix.
  21911. * @returns the world matrix
  21912. */
  21913. Light.prototype.getWorldMatrix = function () {
  21914. this._currentRenderId = this.getScene().getRenderId();
  21915. this._childRenderId = this._currentRenderId;
  21916. var worldMatrix = this._getWorldMatrix();
  21917. if (this.parent && this.parent.getWorldMatrix) {
  21918. if (!this._parentedWorldMatrix) {
  21919. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21920. }
  21921. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21922. this._markSyncedWithParent();
  21923. return this._parentedWorldMatrix;
  21924. }
  21925. return worldMatrix;
  21926. };
  21927. /**
  21928. * Sort function to order lights for rendering.
  21929. * @param a First Light object to compare to second.
  21930. * @param b Second Light object to compare first.
  21931. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21932. */
  21933. Light.CompareLightsPriority = function (a, b) {
  21934. //shadow-casting lights have priority over non-shadow-casting lights
  21935. //the renderPrioirty is a secondary sort criterion
  21936. if (a.shadowEnabled !== b.shadowEnabled) {
  21937. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21938. }
  21939. return b.renderPriority - a.renderPriority;
  21940. };
  21941. /**
  21942. * Releases resources associated with this node.
  21943. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21944. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21945. */
  21946. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21947. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21948. if (this._shadowGenerator) {
  21949. this._shadowGenerator.dispose();
  21950. this._shadowGenerator = null;
  21951. }
  21952. // Animations
  21953. this.getScene().stopAnimation(this);
  21954. // Remove from meshes
  21955. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21956. var mesh = _a[_i];
  21957. mesh._removeLightSource(this);
  21958. }
  21959. this._uniformBuffer.dispose();
  21960. // Remove from scene
  21961. this.getScene().removeLight(this);
  21962. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21963. };
  21964. /**
  21965. * Returns the light type ID (integer).
  21966. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21967. */
  21968. Light.prototype.getTypeID = function () {
  21969. return 0;
  21970. };
  21971. /**
  21972. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21973. * @returns the scaled intensity in intensity mode unit
  21974. */
  21975. Light.prototype.getScaledIntensity = function () {
  21976. return this._photometricScale * this.intensity;
  21977. };
  21978. /**
  21979. * Returns a new Light object, named "name", from the current one.
  21980. * @param name The name of the cloned light
  21981. * @returns the new created light
  21982. */
  21983. Light.prototype.clone = function (name) {
  21984. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21985. if (!constructor) {
  21986. return null;
  21987. }
  21988. return BABYLON.SerializationHelper.Clone(constructor, this);
  21989. };
  21990. /**
  21991. * Serializes the current light into a Serialization object.
  21992. * @returns the serialized object.
  21993. */
  21994. Light.prototype.serialize = function () {
  21995. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21996. // Type
  21997. serializationObject.type = this.getTypeID();
  21998. // Parent
  21999. if (this.parent) {
  22000. serializationObject.parentId = this.parent.id;
  22001. }
  22002. // Inclusion / exclusions
  22003. if (this.excludedMeshes.length > 0) {
  22004. serializationObject.excludedMeshesIds = [];
  22005. this.excludedMeshes.forEach(function (mesh) {
  22006. serializationObject.excludedMeshesIds.push(mesh.id);
  22007. });
  22008. }
  22009. if (this.includedOnlyMeshes.length > 0) {
  22010. serializationObject.includedOnlyMeshesIds = [];
  22011. this.includedOnlyMeshes.forEach(function (mesh) {
  22012. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22013. });
  22014. }
  22015. // Animations
  22016. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22017. serializationObject.ranges = this.serializeAnimationRanges();
  22018. return serializationObject;
  22019. };
  22020. /**
  22021. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22022. * This new light is named "name" and added to the passed scene.
  22023. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22024. * @param name The friendly name of the light
  22025. * @param scene The scene the new light will belong to
  22026. * @returns the constructor function
  22027. */
  22028. Light.GetConstructorFromName = function (type, name, scene) {
  22029. switch (type) {
  22030. case 0:
  22031. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22032. case 1:
  22033. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22034. case 2:
  22035. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22036. case 3:
  22037. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22038. }
  22039. return null;
  22040. };
  22041. /**
  22042. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22043. * @param parsedLight The JSON representation of the light
  22044. * @param scene The scene to create the parsed light in
  22045. * @returns the created light after parsing
  22046. */
  22047. Light.Parse = function (parsedLight, scene) {
  22048. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22049. if (!constructor) {
  22050. return null;
  22051. }
  22052. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22053. // Inclusion / exclusions
  22054. if (parsedLight.excludedMeshesIds) {
  22055. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22056. }
  22057. if (parsedLight.includedOnlyMeshesIds) {
  22058. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22059. }
  22060. // Parent
  22061. if (parsedLight.parentId) {
  22062. light._waitingParentId = parsedLight.parentId;
  22063. }
  22064. // Animations
  22065. if (parsedLight.animations) {
  22066. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22067. var parsedAnimation = parsedLight.animations[animationIndex];
  22068. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22069. }
  22070. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22071. }
  22072. if (parsedLight.autoAnimate) {
  22073. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22074. }
  22075. return light;
  22076. };
  22077. Light.prototype._hookArrayForExcluded = function (array) {
  22078. var _this = this;
  22079. var oldPush = array.push;
  22080. array.push = function () {
  22081. var items = [];
  22082. for (var _i = 0; _i < arguments.length; _i++) {
  22083. items[_i] = arguments[_i];
  22084. }
  22085. var result = oldPush.apply(array, items);
  22086. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22087. var item = items_1[_a];
  22088. item._resyncLighSource(_this);
  22089. }
  22090. return result;
  22091. };
  22092. var oldSplice = array.splice;
  22093. array.splice = function (index, deleteCount) {
  22094. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22095. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22096. var item = deleted_1[_i];
  22097. item._resyncLighSource(_this);
  22098. }
  22099. return deleted;
  22100. };
  22101. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22102. var item = array_1[_i];
  22103. item._resyncLighSource(this);
  22104. }
  22105. };
  22106. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22107. var _this = this;
  22108. var oldPush = array.push;
  22109. array.push = function () {
  22110. var items = [];
  22111. for (var _i = 0; _i < arguments.length; _i++) {
  22112. items[_i] = arguments[_i];
  22113. }
  22114. var result = oldPush.apply(array, items);
  22115. _this._resyncMeshes();
  22116. return result;
  22117. };
  22118. var oldSplice = array.splice;
  22119. array.splice = function (index, deleteCount) {
  22120. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22121. _this._resyncMeshes();
  22122. return deleted;
  22123. };
  22124. this._resyncMeshes();
  22125. };
  22126. Light.prototype._resyncMeshes = function () {
  22127. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22128. var mesh = _a[_i];
  22129. mesh._resyncLighSource(this);
  22130. }
  22131. };
  22132. /**
  22133. * Forces the meshes to update their light related information in their rendering used effects
  22134. * @hidden Internal Use Only
  22135. */
  22136. Light.prototype._markMeshesAsLightDirty = function () {
  22137. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22138. var mesh = _a[_i];
  22139. if (mesh._lightSources.indexOf(this) !== -1) {
  22140. mesh._markSubMeshesAsLightDirty();
  22141. }
  22142. }
  22143. };
  22144. /**
  22145. * Recomputes the cached photometric scale if needed.
  22146. */
  22147. Light.prototype._computePhotometricScale = function () {
  22148. this._photometricScale = this._getPhotometricScale();
  22149. this.getScene().resetCachedMaterial();
  22150. };
  22151. /**
  22152. * Returns the Photometric Scale according to the light type and intensity mode.
  22153. */
  22154. Light.prototype._getPhotometricScale = function () {
  22155. var photometricScale = 0.0;
  22156. var lightTypeID = this.getTypeID();
  22157. //get photometric mode
  22158. var photometricMode = this.intensityMode;
  22159. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22160. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22161. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22162. }
  22163. else {
  22164. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22165. }
  22166. }
  22167. //compute photometric scale
  22168. switch (lightTypeID) {
  22169. case Light.LIGHTTYPEID_POINTLIGHT:
  22170. case Light.LIGHTTYPEID_SPOTLIGHT:
  22171. switch (photometricMode) {
  22172. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22173. photometricScale = 1.0 / (4.0 * Math.PI);
  22174. break;
  22175. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22176. photometricScale = 1.0;
  22177. break;
  22178. case Light.INTENSITYMODE_LUMINANCE:
  22179. photometricScale = this.radius * this.radius;
  22180. break;
  22181. }
  22182. break;
  22183. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22184. switch (photometricMode) {
  22185. case Light.INTENSITYMODE_ILLUMINANCE:
  22186. photometricScale = 1.0;
  22187. break;
  22188. case Light.INTENSITYMODE_LUMINANCE:
  22189. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22190. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22191. var apexAngleRadians = this.radius;
  22192. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22193. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22194. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22195. photometricScale = solidAngle;
  22196. break;
  22197. }
  22198. break;
  22199. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22200. // No fall off in hemisperic light.
  22201. photometricScale = 1.0;
  22202. break;
  22203. }
  22204. return photometricScale;
  22205. };
  22206. /**
  22207. * Reorder the light in the scene according to their defined priority.
  22208. * @hidden Internal Use Only
  22209. */
  22210. Light.prototype._reorderLightsInScene = function () {
  22211. var scene = this.getScene();
  22212. if (this._renderPriority != 0) {
  22213. scene.requireLightSorting = true;
  22214. }
  22215. this.getScene().sortLightsByPriority();
  22216. };
  22217. //lightmapMode Consts
  22218. Light._LIGHTMAP_DEFAULT = 0;
  22219. Light._LIGHTMAP_SPECULAR = 1;
  22220. Light._LIGHTMAP_SHADOWSONLY = 2;
  22221. // Intensity Mode Consts
  22222. Light._INTENSITYMODE_AUTOMATIC = 0;
  22223. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22224. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22225. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22226. Light._INTENSITYMODE_LUMINANCE = 4;
  22227. // Light types ids const.
  22228. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22229. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22230. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22231. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22232. __decorate([
  22233. BABYLON.serializeAsColor3()
  22234. ], Light.prototype, "diffuse", void 0);
  22235. __decorate([
  22236. BABYLON.serializeAsColor3()
  22237. ], Light.prototype, "specular", void 0);
  22238. __decorate([
  22239. BABYLON.serialize()
  22240. ], Light.prototype, "intensity", void 0);
  22241. __decorate([
  22242. BABYLON.serialize()
  22243. ], Light.prototype, "range", void 0);
  22244. __decorate([
  22245. BABYLON.serialize()
  22246. ], Light.prototype, "intensityMode", null);
  22247. __decorate([
  22248. BABYLON.serialize()
  22249. ], Light.prototype, "radius", null);
  22250. __decorate([
  22251. BABYLON.serialize()
  22252. ], Light.prototype, "_renderPriority", void 0);
  22253. __decorate([
  22254. BABYLON.expandToProperty("_reorderLightsInScene")
  22255. ], Light.prototype, "renderPriority", void 0);
  22256. __decorate([
  22257. BABYLON.serialize("shadowEnabled")
  22258. ], Light.prototype, "_shadowEnabled", void 0);
  22259. __decorate([
  22260. BABYLON.serialize("excludeWithLayerMask")
  22261. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22262. __decorate([
  22263. BABYLON.serialize("includeOnlyWithLayerMask")
  22264. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22265. __decorate([
  22266. BABYLON.serialize("lightmapMode")
  22267. ], Light.prototype, "_lightmapMode", void 0);
  22268. return Light;
  22269. }(BABYLON.Node));
  22270. BABYLON.Light = Light;
  22271. })(BABYLON || (BABYLON = {}));
  22272. //# sourceMappingURL=babylon.light.js.map
  22273. var BABYLON;
  22274. (function (BABYLON) {
  22275. var Camera = /** @class */ (function (_super) {
  22276. __extends(Camera, _super);
  22277. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22278. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22279. var _this = _super.call(this, name, scene) || this;
  22280. /**
  22281. * The vector the camera should consider as up.
  22282. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22283. */
  22284. _this.upVector = BABYLON.Vector3.Up();
  22285. _this.orthoLeft = null;
  22286. _this.orthoRight = null;
  22287. _this.orthoBottom = null;
  22288. _this.orthoTop = null;
  22289. /**
  22290. * FOV is set in Radians. (default is 0.8)
  22291. */
  22292. _this.fov = 0.8;
  22293. _this.minZ = 1;
  22294. _this.maxZ = 10000.0;
  22295. _this.inertia = 0.9;
  22296. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22297. _this.isIntermediate = false;
  22298. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22299. /**
  22300. * Restricts the camera to viewing objects with the same layerMask.
  22301. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22302. */
  22303. _this.layerMask = 0x0FFFFFFF;
  22304. /**
  22305. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22306. */
  22307. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22308. // Camera rig members
  22309. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22310. _this._rigCameras = new Array();
  22311. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22312. _this._skipRendering = false;
  22313. _this.customRenderTargets = new Array();
  22314. // Observables
  22315. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22316. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22317. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22318. _this.onRestoreStateObservable = new BABYLON.Observable();
  22319. // Cache
  22320. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22321. _this._projectionMatrix = new BABYLON.Matrix();
  22322. _this._doNotComputeProjectionMatrix = false;
  22323. _this._worldMatrix = BABYLON.Matrix.Identity();
  22324. _this._postProcesses = new Array();
  22325. _this._transformMatrix = BABYLON.Matrix.Zero();
  22326. _this._activeMeshes = new BABYLON.SmartArray(256);
  22327. _this._globalPosition = BABYLON.Vector3.Zero();
  22328. _this._refreshFrustumPlanes = true;
  22329. _this.getScene().addCamera(_this);
  22330. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22331. _this.getScene().activeCamera = _this;
  22332. }
  22333. _this.position = position;
  22334. return _this;
  22335. }
  22336. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22337. get: function () {
  22338. return Camera._PERSPECTIVE_CAMERA;
  22339. },
  22340. enumerable: true,
  22341. configurable: true
  22342. });
  22343. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22344. get: function () {
  22345. return Camera._ORTHOGRAPHIC_CAMERA;
  22346. },
  22347. enumerable: true,
  22348. configurable: true
  22349. });
  22350. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22351. /**
  22352. * This is the default FOV mode for perspective cameras.
  22353. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22354. *
  22355. */
  22356. get: function () {
  22357. return Camera._FOVMODE_VERTICAL_FIXED;
  22358. },
  22359. enumerable: true,
  22360. configurable: true
  22361. });
  22362. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22363. /**
  22364. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22365. *
  22366. */
  22367. get: function () {
  22368. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22369. },
  22370. enumerable: true,
  22371. configurable: true
  22372. });
  22373. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22374. get: function () {
  22375. return Camera._RIG_MODE_NONE;
  22376. },
  22377. enumerable: true,
  22378. configurable: true
  22379. });
  22380. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22381. get: function () {
  22382. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22383. },
  22384. enumerable: true,
  22385. configurable: true
  22386. });
  22387. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22388. get: function () {
  22389. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22390. },
  22391. enumerable: true,
  22392. configurable: true
  22393. });
  22394. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22395. get: function () {
  22396. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22397. },
  22398. enumerable: true,
  22399. configurable: true
  22400. });
  22401. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22402. get: function () {
  22403. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22404. },
  22405. enumerable: true,
  22406. configurable: true
  22407. });
  22408. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22409. get: function () {
  22410. return Camera._RIG_MODE_VR;
  22411. },
  22412. enumerable: true,
  22413. configurable: true
  22414. });
  22415. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22416. get: function () {
  22417. return Camera._RIG_MODE_WEBVR;
  22418. },
  22419. enumerable: true,
  22420. configurable: true
  22421. });
  22422. /**
  22423. * Store current camera state (fov, position, etc..)
  22424. */
  22425. Camera.prototype.storeState = function () {
  22426. this._stateStored = true;
  22427. this._storedFov = this.fov;
  22428. return this;
  22429. };
  22430. /**
  22431. * Restores the camera state values if it has been stored. You must call storeState() first
  22432. */
  22433. Camera.prototype._restoreStateValues = function () {
  22434. if (!this._stateStored) {
  22435. return false;
  22436. }
  22437. this.fov = this._storedFov;
  22438. return true;
  22439. };
  22440. /**
  22441. * Restored camera state. You must call storeState() first
  22442. */
  22443. Camera.prototype.restoreState = function () {
  22444. if (this._restoreStateValues()) {
  22445. this.onRestoreStateObservable.notifyObservers(this);
  22446. return true;
  22447. }
  22448. return false;
  22449. };
  22450. Camera.prototype.getClassName = function () {
  22451. return "Camera";
  22452. };
  22453. /**
  22454. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22455. */
  22456. Camera.prototype.toString = function (fullDetails) {
  22457. var ret = "Name: " + this.name;
  22458. ret += ", type: " + this.getClassName();
  22459. if (this.animations) {
  22460. for (var i = 0; i < this.animations.length; i++) {
  22461. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22462. }
  22463. }
  22464. if (fullDetails) {
  22465. }
  22466. return ret;
  22467. };
  22468. Object.defineProperty(Camera.prototype, "globalPosition", {
  22469. get: function () {
  22470. return this._globalPosition;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Camera.prototype.getActiveMeshes = function () {
  22476. return this._activeMeshes;
  22477. };
  22478. Camera.prototype.isActiveMesh = function (mesh) {
  22479. return (this._activeMeshes.indexOf(mesh) !== -1);
  22480. };
  22481. /**
  22482. * Is this camera ready to be used/rendered
  22483. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22484. * @return true if the camera is ready
  22485. */
  22486. Camera.prototype.isReady = function (completeCheck) {
  22487. if (completeCheck === void 0) { completeCheck = false; }
  22488. if (completeCheck) {
  22489. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22490. var pp = _a[_i];
  22491. if (pp && !pp.isReady()) {
  22492. return false;
  22493. }
  22494. }
  22495. }
  22496. return _super.prototype.isReady.call(this, completeCheck);
  22497. };
  22498. //Cache
  22499. Camera.prototype._initCache = function () {
  22500. _super.prototype._initCache.call(this);
  22501. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22502. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22503. this._cache.mode = undefined;
  22504. this._cache.minZ = undefined;
  22505. this._cache.maxZ = undefined;
  22506. this._cache.fov = undefined;
  22507. this._cache.fovMode = undefined;
  22508. this._cache.aspectRatio = undefined;
  22509. this._cache.orthoLeft = undefined;
  22510. this._cache.orthoRight = undefined;
  22511. this._cache.orthoBottom = undefined;
  22512. this._cache.orthoTop = undefined;
  22513. this._cache.renderWidth = undefined;
  22514. this._cache.renderHeight = undefined;
  22515. };
  22516. Camera.prototype._updateCache = function (ignoreParentClass) {
  22517. if (!ignoreParentClass) {
  22518. _super.prototype._updateCache.call(this);
  22519. }
  22520. this._cache.position.copyFrom(this.position);
  22521. this._cache.upVector.copyFrom(this.upVector);
  22522. };
  22523. // Synchronized
  22524. Camera.prototype._isSynchronized = function () {
  22525. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22526. };
  22527. Camera.prototype._isSynchronizedViewMatrix = function () {
  22528. if (!_super.prototype._isSynchronized.call(this))
  22529. return false;
  22530. return this._cache.position.equals(this.position)
  22531. && this._cache.upVector.equals(this.upVector)
  22532. && this.isSynchronizedWithParent();
  22533. };
  22534. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22535. var check = this._cache.mode === this.mode
  22536. && this._cache.minZ === this.minZ
  22537. && this._cache.maxZ === this.maxZ;
  22538. if (!check) {
  22539. return false;
  22540. }
  22541. var engine = this.getEngine();
  22542. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22543. check = this._cache.fov === this.fov
  22544. && this._cache.fovMode === this.fovMode
  22545. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22546. }
  22547. else {
  22548. check = this._cache.orthoLeft === this.orthoLeft
  22549. && this._cache.orthoRight === this.orthoRight
  22550. && this._cache.orthoBottom === this.orthoBottom
  22551. && this._cache.orthoTop === this.orthoTop
  22552. && this._cache.renderWidth === engine.getRenderWidth()
  22553. && this._cache.renderHeight === engine.getRenderHeight();
  22554. }
  22555. return check;
  22556. };
  22557. // Controls
  22558. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22559. };
  22560. Camera.prototype.detachControl = function (element) {
  22561. };
  22562. Camera.prototype.update = function () {
  22563. this._checkInputs();
  22564. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22565. this._updateRigCameras();
  22566. }
  22567. };
  22568. Camera.prototype._checkInputs = function () {
  22569. this.onAfterCheckInputsObservable.notifyObservers(this);
  22570. };
  22571. Object.defineProperty(Camera.prototype, "rigCameras", {
  22572. get: function () {
  22573. return this._rigCameras;
  22574. },
  22575. enumerable: true,
  22576. configurable: true
  22577. });
  22578. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22579. get: function () {
  22580. return this._rigPostProcess;
  22581. },
  22582. enumerable: true,
  22583. configurable: true
  22584. });
  22585. /**
  22586. * Internal, gets the first post proces.
  22587. * @returns the first post process to be run on this camera.
  22588. */
  22589. Camera.prototype._getFirstPostProcess = function () {
  22590. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22591. if (this._postProcesses[ppIndex] !== null) {
  22592. return this._postProcesses[ppIndex];
  22593. }
  22594. }
  22595. return null;
  22596. };
  22597. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22598. // invalidate framebuffer
  22599. var firstPostProcess = this._getFirstPostProcess();
  22600. if (firstPostProcess) {
  22601. firstPostProcess.markTextureDirty();
  22602. }
  22603. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22604. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22605. var cam = this._rigCameras[i];
  22606. var rigPostProcess = cam._rigPostProcess;
  22607. // for VR rig, there does not have to be a post process
  22608. if (rigPostProcess) {
  22609. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22610. if (isPass) {
  22611. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22612. cam.isIntermediate = this._postProcesses.length === 0;
  22613. }
  22614. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22615. rigPostProcess.markTextureDirty();
  22616. }
  22617. else {
  22618. cam._postProcesses = this._postProcesses.slice(0);
  22619. }
  22620. }
  22621. };
  22622. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22623. if (insertAt === void 0) { insertAt = null; }
  22624. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22625. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22626. return 0;
  22627. }
  22628. if (insertAt == null || insertAt < 0) {
  22629. this._postProcesses.push(postProcess);
  22630. }
  22631. else if (this._postProcesses[insertAt] === null) {
  22632. this._postProcesses[insertAt] = postProcess;
  22633. }
  22634. else {
  22635. this._postProcesses.splice(insertAt, 0, postProcess);
  22636. }
  22637. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22638. return this._postProcesses.indexOf(postProcess);
  22639. };
  22640. Camera.prototype.detachPostProcess = function (postProcess) {
  22641. var idx = this._postProcesses.indexOf(postProcess);
  22642. if (idx !== -1) {
  22643. this._postProcesses[idx] = null;
  22644. }
  22645. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22646. };
  22647. Camera.prototype.getWorldMatrix = function () {
  22648. if (this._isSynchronizedViewMatrix()) {
  22649. return this._worldMatrix;
  22650. }
  22651. // Getting the the view matrix will also compute the world matrix.
  22652. this.getViewMatrix();
  22653. return this._worldMatrix;
  22654. };
  22655. Camera.prototype._getViewMatrix = function () {
  22656. return BABYLON.Matrix.Identity();
  22657. };
  22658. Camera.prototype.getViewMatrix = function (force) {
  22659. if (!force && this._isSynchronizedViewMatrix()) {
  22660. return this._computedViewMatrix;
  22661. }
  22662. this.updateCache();
  22663. this._computedViewMatrix = this._getViewMatrix();
  22664. this._currentRenderId = this.getScene().getRenderId();
  22665. this._childRenderId = this._currentRenderId;
  22666. this._refreshFrustumPlanes = true;
  22667. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22668. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22669. }
  22670. this.onViewMatrixChangedObservable.notifyObservers(this);
  22671. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22672. return this._computedViewMatrix;
  22673. };
  22674. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22675. this._doNotComputeProjectionMatrix = true;
  22676. if (projection !== undefined) {
  22677. this._projectionMatrix = projection;
  22678. }
  22679. };
  22680. ;
  22681. Camera.prototype.unfreezeProjectionMatrix = function () {
  22682. this._doNotComputeProjectionMatrix = false;
  22683. };
  22684. ;
  22685. Camera.prototype.getProjectionMatrix = function (force) {
  22686. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22687. return this._projectionMatrix;
  22688. }
  22689. // Cache
  22690. this._cache.mode = this.mode;
  22691. this._cache.minZ = this.minZ;
  22692. this._cache.maxZ = this.maxZ;
  22693. // Matrix
  22694. this._refreshFrustumPlanes = true;
  22695. var engine = this.getEngine();
  22696. var scene = this.getScene();
  22697. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22698. this._cache.fov = this.fov;
  22699. this._cache.fovMode = this.fovMode;
  22700. this._cache.aspectRatio = engine.getAspectRatio(this);
  22701. if (this.minZ <= 0) {
  22702. this.minZ = 0.1;
  22703. }
  22704. if (scene.useRightHandedSystem) {
  22705. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22706. }
  22707. else {
  22708. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22709. }
  22710. }
  22711. else {
  22712. var halfWidth = engine.getRenderWidth() / 2.0;
  22713. var halfHeight = engine.getRenderHeight() / 2.0;
  22714. if (scene.useRightHandedSystem) {
  22715. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22716. }
  22717. else {
  22718. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22719. }
  22720. this._cache.orthoLeft = this.orthoLeft;
  22721. this._cache.orthoRight = this.orthoRight;
  22722. this._cache.orthoBottom = this.orthoBottom;
  22723. this._cache.orthoTop = this.orthoTop;
  22724. this._cache.renderWidth = engine.getRenderWidth();
  22725. this._cache.renderHeight = engine.getRenderHeight();
  22726. }
  22727. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22728. return this._projectionMatrix;
  22729. };
  22730. Camera.prototype.getTranformationMatrix = function () {
  22731. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22732. return this._transformMatrix;
  22733. };
  22734. Camera.prototype.updateFrustumPlanes = function () {
  22735. if (!this._refreshFrustumPlanes) {
  22736. return;
  22737. }
  22738. this.getTranformationMatrix();
  22739. if (!this._frustumPlanes) {
  22740. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22741. }
  22742. else {
  22743. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22744. }
  22745. this._refreshFrustumPlanes = false;
  22746. };
  22747. Camera.prototype.isInFrustum = function (target) {
  22748. this.updateFrustumPlanes();
  22749. return target.isInFrustum(this._frustumPlanes);
  22750. };
  22751. Camera.prototype.isCompletelyInFrustum = function (target) {
  22752. this.updateFrustumPlanes();
  22753. return target.isCompletelyInFrustum(this._frustumPlanes);
  22754. };
  22755. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22756. if (length === void 0) { length = 100; }
  22757. if (!transform) {
  22758. transform = this.getWorldMatrix();
  22759. }
  22760. if (!origin) {
  22761. origin = this.position;
  22762. }
  22763. var forward = new BABYLON.Vector3(0, 0, 1);
  22764. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22765. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22766. return new BABYLON.Ray(origin, direction, length);
  22767. };
  22768. /**
  22769. * Releases resources associated with this node.
  22770. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22771. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22772. */
  22773. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22774. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22775. // Observables
  22776. this.onViewMatrixChangedObservable.clear();
  22777. this.onProjectionMatrixChangedObservable.clear();
  22778. this.onAfterCheckInputsObservable.clear();
  22779. this.onRestoreStateObservable.clear();
  22780. // Inputs
  22781. if (this.inputs) {
  22782. this.inputs.clear();
  22783. }
  22784. // Animations
  22785. this.getScene().stopAnimation(this);
  22786. // Remove from scene
  22787. this.getScene().removeCamera(this);
  22788. while (this._rigCameras.length > 0) {
  22789. var camera = this._rigCameras.pop();
  22790. if (camera) {
  22791. camera.dispose();
  22792. }
  22793. }
  22794. // Postprocesses
  22795. if (this._rigPostProcess) {
  22796. this._rigPostProcess.dispose(this);
  22797. this._rigPostProcess = null;
  22798. this._postProcesses = [];
  22799. }
  22800. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22801. this._rigPostProcess = null;
  22802. this._postProcesses = [];
  22803. }
  22804. else {
  22805. var i = this._postProcesses.length;
  22806. while (--i >= 0) {
  22807. var postProcess = this._postProcesses[i];
  22808. if (postProcess) {
  22809. postProcess.dispose(this);
  22810. }
  22811. }
  22812. }
  22813. // Render targets
  22814. var i = this.customRenderTargets.length;
  22815. while (--i >= 0) {
  22816. this.customRenderTargets[i].dispose();
  22817. }
  22818. this.customRenderTargets = [];
  22819. // Active Meshes
  22820. this._activeMeshes.dispose();
  22821. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22822. };
  22823. Object.defineProperty(Camera.prototype, "leftCamera", {
  22824. // ---- Camera rigs section ----
  22825. get: function () {
  22826. if (this._rigCameras.length < 1) {
  22827. return null;
  22828. }
  22829. return this._rigCameras[0];
  22830. },
  22831. enumerable: true,
  22832. configurable: true
  22833. });
  22834. Object.defineProperty(Camera.prototype, "rightCamera", {
  22835. get: function () {
  22836. if (this._rigCameras.length < 2) {
  22837. return null;
  22838. }
  22839. return this._rigCameras[1];
  22840. },
  22841. enumerable: true,
  22842. configurable: true
  22843. });
  22844. Camera.prototype.getLeftTarget = function () {
  22845. if (this._rigCameras.length < 1) {
  22846. return null;
  22847. }
  22848. return this._rigCameras[0].getTarget();
  22849. };
  22850. Camera.prototype.getRightTarget = function () {
  22851. if (this._rigCameras.length < 2) {
  22852. return null;
  22853. }
  22854. return this._rigCameras[1].getTarget();
  22855. };
  22856. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22857. if (this.cameraRigMode === mode) {
  22858. return;
  22859. }
  22860. while (this._rigCameras.length > 0) {
  22861. var camera = this._rigCameras.pop();
  22862. if (camera) {
  22863. camera.dispose();
  22864. }
  22865. }
  22866. this.cameraRigMode = mode;
  22867. this._cameraRigParams = {};
  22868. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22869. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22870. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22871. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22872. // create the rig cameras, unless none
  22873. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22874. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22875. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22876. if (leftCamera && rightCamera) {
  22877. this._rigCameras.push(leftCamera);
  22878. this._rigCameras.push(rightCamera);
  22879. }
  22880. }
  22881. switch (this.cameraRigMode) {
  22882. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22883. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22884. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22885. break;
  22886. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22887. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22888. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22889. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22890. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22891. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22892. break;
  22893. case Camera.RIG_MODE_VR:
  22894. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22895. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22896. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22897. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22898. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22899. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22900. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22901. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22902. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22903. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22904. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22905. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22906. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22907. if (metrics.compensateDistortion) {
  22908. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22909. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22910. }
  22911. break;
  22912. case Camera.RIG_MODE_WEBVR:
  22913. if (rigParams.vrDisplay) {
  22914. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22915. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22916. //Left eye
  22917. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22918. this._rigCameras[0].setCameraRigParameter("left", true);
  22919. //leaving this for future reference
  22920. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22921. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22922. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22923. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22924. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22925. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22926. this._rigCameras[0].parent = this;
  22927. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22928. //Right eye
  22929. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22930. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22931. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22932. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22933. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22934. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22935. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22936. this._rigCameras[1].parent = this;
  22937. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22938. if (Camera.UseAlternateWebVRRendering) {
  22939. this._rigCameras[1]._skipRendering = true;
  22940. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22941. }
  22942. }
  22943. break;
  22944. }
  22945. this._cascadePostProcessesToRigCams();
  22946. this.update();
  22947. };
  22948. Camera.prototype._getVRProjectionMatrix = function () {
  22949. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22950. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22951. return this._projectionMatrix;
  22952. };
  22953. Camera.prototype._updateCameraRotationMatrix = function () {
  22954. //Here for WebVR
  22955. };
  22956. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22957. //Here for WebVR
  22958. };
  22959. /**
  22960. * This function MUST be overwritten by the different WebVR cameras available.
  22961. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22962. */
  22963. Camera.prototype._getWebVRProjectionMatrix = function () {
  22964. return BABYLON.Matrix.Identity();
  22965. };
  22966. /**
  22967. * This function MUST be overwritten by the different WebVR cameras available.
  22968. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22969. */
  22970. Camera.prototype._getWebVRViewMatrix = function () {
  22971. return BABYLON.Matrix.Identity();
  22972. };
  22973. Camera.prototype.setCameraRigParameter = function (name, value) {
  22974. if (!this._cameraRigParams) {
  22975. this._cameraRigParams = {};
  22976. }
  22977. this._cameraRigParams[name] = value;
  22978. //provisionnally:
  22979. if (name === "interaxialDistance") {
  22980. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22981. }
  22982. };
  22983. /**
  22984. * needs to be overridden by children so sub has required properties to be copied
  22985. */
  22986. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22987. return null;
  22988. };
  22989. /**
  22990. * May need to be overridden by children
  22991. */
  22992. Camera.prototype._updateRigCameras = function () {
  22993. for (var i = 0; i < this._rigCameras.length; i++) {
  22994. this._rigCameras[i].minZ = this.minZ;
  22995. this._rigCameras[i].maxZ = this.maxZ;
  22996. this._rigCameras[i].fov = this.fov;
  22997. }
  22998. // only update viewport when ANAGLYPH
  22999. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23000. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23001. }
  23002. };
  23003. Camera.prototype._setupInputs = function () {
  23004. };
  23005. Camera.prototype.serialize = function () {
  23006. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23007. // Type
  23008. serializationObject.type = this.getClassName();
  23009. // Parent
  23010. if (this.parent) {
  23011. serializationObject.parentId = this.parent.id;
  23012. }
  23013. if (this.inputs) {
  23014. this.inputs.serialize(serializationObject);
  23015. }
  23016. // Animations
  23017. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23018. serializationObject.ranges = this.serializeAnimationRanges();
  23019. return serializationObject;
  23020. };
  23021. Camera.prototype.clone = function (name) {
  23022. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23023. };
  23024. Camera.prototype.getDirection = function (localAxis) {
  23025. var result = BABYLON.Vector3.Zero();
  23026. this.getDirectionToRef(localAxis, result);
  23027. return result;
  23028. };
  23029. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23030. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23031. };
  23032. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23033. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23034. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23035. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23036. interaxial_distance: interaxial_distance,
  23037. isStereoscopicSideBySide: isStereoscopicSideBySide
  23038. });
  23039. if (constructorFunc) {
  23040. return constructorFunc;
  23041. }
  23042. // Default to universal camera
  23043. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23044. };
  23045. Camera.prototype.computeWorldMatrix = function () {
  23046. return this.getWorldMatrix();
  23047. };
  23048. Camera.Parse = function (parsedCamera, scene) {
  23049. var type = parsedCamera.type;
  23050. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23051. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23052. // Parent
  23053. if (parsedCamera.parentId) {
  23054. camera._waitingParentId = parsedCamera.parentId;
  23055. }
  23056. //If camera has an input manager, let it parse inputs settings
  23057. if (camera.inputs) {
  23058. camera.inputs.parse(parsedCamera);
  23059. camera._setupInputs();
  23060. }
  23061. if (camera.setPosition) { // need to force position
  23062. camera.position.copyFromFloats(0, 0, 0);
  23063. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23064. }
  23065. // Target
  23066. if (parsedCamera.target) {
  23067. if (camera.setTarget) {
  23068. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23069. }
  23070. }
  23071. // Apply 3d rig, when found
  23072. if (parsedCamera.cameraRigMode) {
  23073. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23074. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23075. }
  23076. // Animations
  23077. if (parsedCamera.animations) {
  23078. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23079. var parsedAnimation = parsedCamera.animations[animationIndex];
  23080. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23081. }
  23082. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23083. }
  23084. if (parsedCamera.autoAnimate) {
  23085. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23086. }
  23087. return camera;
  23088. };
  23089. // Statics
  23090. Camera._PERSPECTIVE_CAMERA = 0;
  23091. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23092. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23093. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23094. Camera._RIG_MODE_NONE = 0;
  23095. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23096. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23097. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23098. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23099. Camera._RIG_MODE_VR = 20;
  23100. Camera._RIG_MODE_WEBVR = 21;
  23101. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23102. Camera.UseAlternateWebVRRendering = false;
  23103. __decorate([
  23104. BABYLON.serializeAsVector3()
  23105. ], Camera.prototype, "position", void 0);
  23106. __decorate([
  23107. BABYLON.serializeAsVector3()
  23108. ], Camera.prototype, "upVector", void 0);
  23109. __decorate([
  23110. BABYLON.serialize()
  23111. ], Camera.prototype, "orthoLeft", void 0);
  23112. __decorate([
  23113. BABYLON.serialize()
  23114. ], Camera.prototype, "orthoRight", void 0);
  23115. __decorate([
  23116. BABYLON.serialize()
  23117. ], Camera.prototype, "orthoBottom", void 0);
  23118. __decorate([
  23119. BABYLON.serialize()
  23120. ], Camera.prototype, "orthoTop", void 0);
  23121. __decorate([
  23122. BABYLON.serialize()
  23123. ], Camera.prototype, "fov", void 0);
  23124. __decorate([
  23125. BABYLON.serialize()
  23126. ], Camera.prototype, "minZ", void 0);
  23127. __decorate([
  23128. BABYLON.serialize()
  23129. ], Camera.prototype, "maxZ", void 0);
  23130. __decorate([
  23131. BABYLON.serialize()
  23132. ], Camera.prototype, "inertia", void 0);
  23133. __decorate([
  23134. BABYLON.serialize()
  23135. ], Camera.prototype, "mode", void 0);
  23136. __decorate([
  23137. BABYLON.serialize()
  23138. ], Camera.prototype, "layerMask", void 0);
  23139. __decorate([
  23140. BABYLON.serialize()
  23141. ], Camera.prototype, "fovMode", void 0);
  23142. __decorate([
  23143. BABYLON.serialize()
  23144. ], Camera.prototype, "cameraRigMode", void 0);
  23145. __decorate([
  23146. BABYLON.serialize()
  23147. ], Camera.prototype, "interaxialDistance", void 0);
  23148. __decorate([
  23149. BABYLON.serialize()
  23150. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23151. return Camera;
  23152. }(BABYLON.Node));
  23153. BABYLON.Camera = Camera;
  23154. })(BABYLON || (BABYLON = {}));
  23155. //# sourceMappingURL=babylon.camera.js.map
  23156. var BABYLON;
  23157. (function (BABYLON) {
  23158. var RenderingManager = /** @class */ (function () {
  23159. function RenderingManager(scene) {
  23160. this._renderingGroups = new Array();
  23161. this._autoClearDepthStencil = {};
  23162. this._customOpaqueSortCompareFn = {};
  23163. this._customAlphaTestSortCompareFn = {};
  23164. this._customTransparentSortCompareFn = {};
  23165. this._renderinGroupInfo = null;
  23166. this._scene = scene;
  23167. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23168. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23169. }
  23170. }
  23171. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23172. if (depth === void 0) { depth = true; }
  23173. if (stencil === void 0) { stencil = true; }
  23174. if (this._depthStencilBufferAlreadyCleaned) {
  23175. return;
  23176. }
  23177. this._scene.getEngine().clear(null, false, depth, stencil);
  23178. this._depthStencilBufferAlreadyCleaned = true;
  23179. };
  23180. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23181. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23182. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23183. var info = null;
  23184. if (observable) {
  23185. if (!this._renderinGroupInfo) {
  23186. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23187. }
  23188. info = this._renderinGroupInfo;
  23189. info.scene = this._scene;
  23190. info.camera = this._scene.activeCamera;
  23191. }
  23192. // Dispatch sprites
  23193. if (renderSprites) {
  23194. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23195. var manager = this._scene.spriteManagers[index];
  23196. this.dispatchSprites(manager);
  23197. }
  23198. }
  23199. // Render
  23200. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23201. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23202. var renderingGroup = this._renderingGroups[index];
  23203. if (!renderingGroup && !observable)
  23204. continue;
  23205. var renderingGroupMask = 0;
  23206. // Fire PRECLEAR stage
  23207. if (observable && info) {
  23208. renderingGroupMask = Math.pow(2, index);
  23209. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23210. info.renderingGroupId = index;
  23211. observable.notifyObservers(info, renderingGroupMask);
  23212. }
  23213. // Clear depth/stencil if needed
  23214. if (RenderingManager.AUTOCLEAR) {
  23215. var autoClear = this._autoClearDepthStencil[index];
  23216. if (autoClear && autoClear.autoClear) {
  23217. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23218. }
  23219. }
  23220. if (observable && info) {
  23221. // Fire PREOPAQUE stage
  23222. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23223. observable.notifyObservers(info, renderingGroupMask);
  23224. // Fire PRETRANSPARENT stage
  23225. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23226. observable.notifyObservers(info, renderingGroupMask);
  23227. }
  23228. if (renderingGroup) {
  23229. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23230. var step = _a[_i];
  23231. step.action(index);
  23232. }
  23233. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23234. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23235. var step = _c[_b];
  23236. step.action(index);
  23237. }
  23238. }
  23239. // Fire POSTTRANSPARENT stage
  23240. if (observable && info) {
  23241. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23242. observable.notifyObservers(info, renderingGroupMask);
  23243. }
  23244. }
  23245. };
  23246. RenderingManager.prototype.reset = function () {
  23247. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23248. var renderingGroup = this._renderingGroups[index];
  23249. if (renderingGroup) {
  23250. renderingGroup.prepare();
  23251. }
  23252. }
  23253. };
  23254. RenderingManager.prototype.dispose = function () {
  23255. this.freeRenderingGroups();
  23256. this._renderingGroups.length = 0;
  23257. };
  23258. /**
  23259. * Clear the info related to rendering groups preventing retention points during dispose.
  23260. */
  23261. RenderingManager.prototype.freeRenderingGroups = function () {
  23262. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23263. var renderingGroup = this._renderingGroups[index];
  23264. if (renderingGroup) {
  23265. renderingGroup.dispose();
  23266. }
  23267. }
  23268. };
  23269. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23270. if (this._renderingGroups[renderingGroupId] === undefined) {
  23271. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23272. }
  23273. };
  23274. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23275. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23276. this._prepareRenderingGroup(renderingGroupId);
  23277. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23278. };
  23279. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23280. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23281. this._prepareRenderingGroup(renderingGroupId);
  23282. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23283. };
  23284. /**
  23285. * @param subMesh The submesh to dispatch
  23286. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23287. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23288. */
  23289. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23290. if (mesh === undefined) {
  23291. mesh = subMesh.getMesh();
  23292. }
  23293. var renderingGroupId = mesh.renderingGroupId || 0;
  23294. this._prepareRenderingGroup(renderingGroupId);
  23295. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23296. };
  23297. /**
  23298. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23299. * This allowed control for front to back rendering or reversly depending of the special needs.
  23300. *
  23301. * @param renderingGroupId The rendering group id corresponding to its index
  23302. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23303. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23304. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23305. */
  23306. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23307. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23308. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23309. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23310. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23311. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23312. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23313. if (this._renderingGroups[renderingGroupId]) {
  23314. var group = this._renderingGroups[renderingGroupId];
  23315. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23316. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23317. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23318. }
  23319. };
  23320. /**
  23321. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23322. *
  23323. * @param renderingGroupId The rendering group id corresponding to its index
  23324. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23325. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23326. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23327. */
  23328. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23329. if (depth === void 0) { depth = true; }
  23330. if (stencil === void 0) { stencil = true; }
  23331. this._autoClearDepthStencil[renderingGroupId] = {
  23332. autoClear: autoClearDepthStencil,
  23333. depth: depth,
  23334. stencil: stencil
  23335. };
  23336. };
  23337. /**
  23338. * The max id used for rendering groups (not included)
  23339. */
  23340. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23341. /**
  23342. * The min id used for rendering groups (included)
  23343. */
  23344. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23345. /**
  23346. * Used to globally prevent autoclearing scenes.
  23347. */
  23348. RenderingManager.AUTOCLEAR = true;
  23349. return RenderingManager;
  23350. }());
  23351. BABYLON.RenderingManager = RenderingManager;
  23352. })(BABYLON || (BABYLON = {}));
  23353. //# sourceMappingURL=babylon.renderingManager.js.map
  23354. var BABYLON;
  23355. (function (BABYLON) {
  23356. var RenderingGroup = /** @class */ (function () {
  23357. /**
  23358. * Creates a new rendering group.
  23359. * @param index The rendering group index
  23360. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23361. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23362. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23363. */
  23364. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23365. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23366. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23367. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23368. this.index = index;
  23369. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23370. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23371. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23372. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23373. this._particleSystems = new BABYLON.SmartArray(256);
  23374. this._spriteManagers = new BABYLON.SmartArray(256);
  23375. this._edgesRenderers = new BABYLON.SmartArray(16);
  23376. this._scene = scene;
  23377. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23378. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23379. this.transparentSortCompareFn = transparentSortCompareFn;
  23380. }
  23381. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23382. /**
  23383. * Set the opaque sort comparison function.
  23384. * If null the sub meshes will be render in the order they were created
  23385. */
  23386. set: function (value) {
  23387. this._opaqueSortCompareFn = value;
  23388. if (value) {
  23389. this._renderOpaque = this.renderOpaqueSorted;
  23390. }
  23391. else {
  23392. this._renderOpaque = RenderingGroup.renderUnsorted;
  23393. }
  23394. },
  23395. enumerable: true,
  23396. configurable: true
  23397. });
  23398. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23399. /**
  23400. * Set the alpha test sort comparison function.
  23401. * If null the sub meshes will be render in the order they were created
  23402. */
  23403. set: function (value) {
  23404. this._alphaTestSortCompareFn = value;
  23405. if (value) {
  23406. this._renderAlphaTest = this.renderAlphaTestSorted;
  23407. }
  23408. else {
  23409. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23410. }
  23411. },
  23412. enumerable: true,
  23413. configurable: true
  23414. });
  23415. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23416. /**
  23417. * Set the transparent sort comparison function.
  23418. * If null the sub meshes will be render in the order they were created
  23419. */
  23420. set: function (value) {
  23421. if (value) {
  23422. this._transparentSortCompareFn = value;
  23423. }
  23424. else {
  23425. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23426. }
  23427. this._renderTransparent = this.renderTransparentSorted;
  23428. },
  23429. enumerable: true,
  23430. configurable: true
  23431. });
  23432. /**
  23433. * Render all the sub meshes contained in the group.
  23434. * @param customRenderFunction Used to override the default render behaviour of the group.
  23435. * @returns true if rendered some submeshes.
  23436. */
  23437. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23438. if (customRenderFunction) {
  23439. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23440. return;
  23441. }
  23442. var engine = this._scene.getEngine();
  23443. // Depth only
  23444. if (this._depthOnlySubMeshes.length !== 0) {
  23445. engine.setColorWrite(false);
  23446. this._renderAlphaTest(this._depthOnlySubMeshes);
  23447. engine.setColorWrite(true);
  23448. }
  23449. // Opaque
  23450. if (this._opaqueSubMeshes.length !== 0) {
  23451. this._renderOpaque(this._opaqueSubMeshes);
  23452. }
  23453. // Alpha test
  23454. if (this._alphaTestSubMeshes.length !== 0) {
  23455. this._renderAlphaTest(this._alphaTestSubMeshes);
  23456. }
  23457. var stencilState = engine.getStencilBuffer();
  23458. engine.setStencilBuffer(false);
  23459. // Sprites
  23460. if (renderSprites) {
  23461. this._renderSprites();
  23462. }
  23463. // Particles
  23464. if (renderParticles) {
  23465. this._renderParticles(activeMeshes);
  23466. }
  23467. if (this.onBeforeTransparentRendering) {
  23468. this.onBeforeTransparentRendering();
  23469. }
  23470. // Transparent
  23471. if (this._transparentSubMeshes.length !== 0) {
  23472. this._renderTransparent(this._transparentSubMeshes);
  23473. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23474. }
  23475. // Set back stencil to false in case it changes before the edge renderer.
  23476. engine.setStencilBuffer(false);
  23477. // Edges
  23478. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23479. this._edgesRenderers.data[edgesRendererIndex].render();
  23480. }
  23481. // Restore Stencil state.
  23482. engine.setStencilBuffer(stencilState);
  23483. };
  23484. /**
  23485. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23486. * @param subMeshes The submeshes to render
  23487. */
  23488. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23489. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23490. };
  23491. /**
  23492. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23493. * @param subMeshes The submeshes to render
  23494. */
  23495. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23496. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23497. };
  23498. /**
  23499. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23500. * @param subMeshes The submeshes to render
  23501. */
  23502. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23503. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23504. };
  23505. /**
  23506. * Renders the submeshes in a specified order.
  23507. * @param subMeshes The submeshes to sort before render
  23508. * @param sortCompareFn The comparison function use to sort
  23509. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23510. * @param transparent Specifies to activate blending if true
  23511. */
  23512. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23513. var subIndex = 0;
  23514. var subMesh;
  23515. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23516. for (; subIndex < subMeshes.length; subIndex++) {
  23517. subMesh = subMeshes.data[subIndex];
  23518. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23519. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23520. }
  23521. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23522. if (sortCompareFn) {
  23523. sortedArray.sort(sortCompareFn);
  23524. }
  23525. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23526. subMesh = sortedArray[subIndex];
  23527. if (transparent) {
  23528. var material = subMesh.getMaterial();
  23529. if (material && material.needDepthPrePass) {
  23530. var engine = material.getScene().getEngine();
  23531. engine.setColorWrite(false);
  23532. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23533. subMesh.render(false);
  23534. engine.setColorWrite(true);
  23535. }
  23536. }
  23537. subMesh.render(transparent);
  23538. }
  23539. };
  23540. /**
  23541. * Renders the submeshes in the order they were dispatched (no sort applied).
  23542. * @param subMeshes The submeshes to render
  23543. */
  23544. RenderingGroup.renderUnsorted = function (subMeshes) {
  23545. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23546. var submesh = subMeshes.data[subIndex];
  23547. submesh.render(false);
  23548. }
  23549. };
  23550. /**
  23551. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23552. * are rendered back to front if in the same alpha index.
  23553. *
  23554. * @param a The first submesh
  23555. * @param b The second submesh
  23556. * @returns The result of the comparison
  23557. */
  23558. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23559. // Alpha index first
  23560. if (a._alphaIndex > b._alphaIndex) {
  23561. return 1;
  23562. }
  23563. if (a._alphaIndex < b._alphaIndex) {
  23564. return -1;
  23565. }
  23566. // Then distance to camera
  23567. return RenderingGroup.backToFrontSortCompare(a, b);
  23568. };
  23569. /**
  23570. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23571. * are rendered back to front.
  23572. *
  23573. * @param a The first submesh
  23574. * @param b The second submesh
  23575. * @returns The result of the comparison
  23576. */
  23577. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23578. // Then distance to camera
  23579. if (a._distanceToCamera < b._distanceToCamera) {
  23580. return 1;
  23581. }
  23582. if (a._distanceToCamera > b._distanceToCamera) {
  23583. return -1;
  23584. }
  23585. return 0;
  23586. };
  23587. /**
  23588. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23589. * are rendered front to back (prevent overdraw).
  23590. *
  23591. * @param a The first submesh
  23592. * @param b The second submesh
  23593. * @returns The result of the comparison
  23594. */
  23595. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23596. // Then distance to camera
  23597. if (a._distanceToCamera < b._distanceToCamera) {
  23598. return -1;
  23599. }
  23600. if (a._distanceToCamera > b._distanceToCamera) {
  23601. return 1;
  23602. }
  23603. return 0;
  23604. };
  23605. /**
  23606. * Resets the different lists of submeshes to prepare a new frame.
  23607. */
  23608. RenderingGroup.prototype.prepare = function () {
  23609. this._opaqueSubMeshes.reset();
  23610. this._transparentSubMeshes.reset();
  23611. this._alphaTestSubMeshes.reset();
  23612. this._depthOnlySubMeshes.reset();
  23613. this._particleSystems.reset();
  23614. this._spriteManagers.reset();
  23615. this._edgesRenderers.reset();
  23616. };
  23617. RenderingGroup.prototype.dispose = function () {
  23618. this._opaqueSubMeshes.dispose();
  23619. this._transparentSubMeshes.dispose();
  23620. this._alphaTestSubMeshes.dispose();
  23621. this._depthOnlySubMeshes.dispose();
  23622. this._particleSystems.dispose();
  23623. this._spriteManagers.dispose();
  23624. this._edgesRenderers.dispose();
  23625. };
  23626. /**
  23627. * Inserts the submesh in its correct queue depending on its material.
  23628. * @param subMesh The submesh to dispatch
  23629. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23630. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23631. */
  23632. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23633. // Get mesh and materials if not provided
  23634. if (mesh === undefined) {
  23635. mesh = subMesh.getMesh();
  23636. }
  23637. if (material === undefined) {
  23638. material = subMesh.getMaterial();
  23639. }
  23640. if (material === null || material === undefined) {
  23641. return;
  23642. }
  23643. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23644. this._transparentSubMeshes.push(subMesh);
  23645. }
  23646. else if (material.needAlphaTesting()) { // Alpha test
  23647. if (material.needDepthPrePass) {
  23648. this._depthOnlySubMeshes.push(subMesh);
  23649. }
  23650. this._alphaTestSubMeshes.push(subMesh);
  23651. }
  23652. else {
  23653. if (material.needDepthPrePass) {
  23654. this._depthOnlySubMeshes.push(subMesh);
  23655. }
  23656. this._opaqueSubMeshes.push(subMesh); // Opaque
  23657. }
  23658. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23659. this._edgesRenderers.push(mesh._edgesRenderer);
  23660. }
  23661. };
  23662. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23663. this._spriteManagers.push(spriteManager);
  23664. };
  23665. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23666. this._particleSystems.push(particleSystem);
  23667. };
  23668. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23669. if (this._particleSystems.length === 0) {
  23670. return;
  23671. }
  23672. // Particles
  23673. var activeCamera = this._scene.activeCamera;
  23674. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23675. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23676. var particleSystem = this._particleSystems.data[particleIndex];
  23677. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23678. continue;
  23679. }
  23680. var emitter = particleSystem.emitter;
  23681. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23682. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23683. }
  23684. }
  23685. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23686. };
  23687. RenderingGroup.prototype._renderSprites = function () {
  23688. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23689. return;
  23690. }
  23691. // Sprites
  23692. var activeCamera = this._scene.activeCamera;
  23693. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23694. for (var id = 0; id < this._spriteManagers.length; id++) {
  23695. var spriteManager = this._spriteManagers.data[id];
  23696. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23697. spriteManager.render();
  23698. }
  23699. }
  23700. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23701. };
  23702. return RenderingGroup;
  23703. }());
  23704. BABYLON.RenderingGroup = RenderingGroup;
  23705. })(BABYLON || (BABYLON = {}));
  23706. //# sourceMappingURL=babylon.renderingGroup.js.map
  23707. var BABYLON;
  23708. (function (BABYLON) {
  23709. /**
  23710. * Groups all the scene component constants in one place to ease maintenance.
  23711. * @hidden
  23712. */
  23713. var SceneComponentConstants = /** @class */ (function () {
  23714. function SceneComponentConstants() {
  23715. }
  23716. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23717. SceneComponentConstants.NAME_LAYER = "Layer";
  23718. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23719. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23720. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23721. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23722. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23723. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23724. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23725. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23726. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23727. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23728. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23729. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23730. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23731. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23732. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23733. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23734. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23735. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23736. return SceneComponentConstants;
  23737. }());
  23738. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23739. /**
  23740. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23741. * @hidden
  23742. */
  23743. var Stage = /** @class */ (function (_super) {
  23744. __extends(Stage, _super);
  23745. /**
  23746. * Hide ctor from the rest of the world.
  23747. * @param items The items to add.
  23748. */
  23749. function Stage(items) {
  23750. return _super.apply(this, items) || this;
  23751. }
  23752. /**
  23753. * Creates a new Stage.
  23754. * @returns A new instance of a Stage
  23755. */
  23756. Stage.Create = function () {
  23757. return Object.create(Stage.prototype);
  23758. };
  23759. /**
  23760. * Registers a step in an ordered way in the targeted stage.
  23761. * @param index Defines the position to register the step in
  23762. * @param component Defines the component attached to the step
  23763. * @param action Defines the action to launch during the step
  23764. */
  23765. Stage.prototype.registerStep = function (index, component, action) {
  23766. var i = 0;
  23767. var maxIndex = Number.MAX_VALUE;
  23768. for (; i < this.length && i < maxIndex; i++) {
  23769. var step = this[i];
  23770. maxIndex = step.index;
  23771. }
  23772. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23773. };
  23774. /**
  23775. * Clears all the steps from the stage.
  23776. */
  23777. Stage.prototype.clear = function () {
  23778. this.length = 0;
  23779. };
  23780. return Stage;
  23781. }(Array));
  23782. BABYLON.Stage = Stage;
  23783. })(BABYLON || (BABYLON = {}));
  23784. //# sourceMappingURL=babylon.sceneComponent.js.map
  23785. var BABYLON;
  23786. (function (BABYLON) {
  23787. /**
  23788. * Base class of the scene acting as a container for the different elements composing a scene.
  23789. * This class is dynamically extended by the different components of the scene increasing
  23790. * flexibility and reducing coupling
  23791. */
  23792. var AbstractScene = /** @class */ (function () {
  23793. function AbstractScene() {
  23794. /** All of the cameras added to this scene
  23795. * @see http://doc.babylonjs.com/babylon101/cameras
  23796. */
  23797. this.cameras = new Array();
  23798. /**
  23799. * All of the lights added to this scene
  23800. * @see http://doc.babylonjs.com/babylon101/lights
  23801. */
  23802. this.lights = new Array();
  23803. /**
  23804. * All of the (abstract) meshes added to this scene
  23805. */
  23806. this.meshes = new Array();
  23807. /**
  23808. * The list of skeletons added to the scene
  23809. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23810. */
  23811. this.skeletons = new Array();
  23812. /**
  23813. * All of the particle systems added to this scene
  23814. * @see http://doc.babylonjs.com/babylon101/particles
  23815. */
  23816. this.particleSystems = new Array();
  23817. /**
  23818. * Gets a list of Animations associated with the scene
  23819. */
  23820. this.animations = [];
  23821. /**
  23822. * All of the animation groups added to this scene
  23823. * @see http://doc.babylonjs.com/how_to/group
  23824. */
  23825. this.animationGroups = new Array();
  23826. /**
  23827. * All of the multi-materials added to this scene
  23828. * @see http://doc.babylonjs.com/how_to/multi_materials
  23829. */
  23830. this.multiMaterials = new Array();
  23831. /**
  23832. * All of the materials added to this scene
  23833. * @see http://doc.babylonjs.com/babylon101/materials
  23834. */
  23835. this.materials = new Array();
  23836. /**
  23837. * The list of morph target managers added to the scene
  23838. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23839. */
  23840. this.morphTargetManagers = new Array();
  23841. /**
  23842. * The list of geometries used in the scene.
  23843. */
  23844. this.geometries = new Array();
  23845. /**
  23846. * All of the tranform nodes added to this scene
  23847. * @see http://doc.babylonjs.com/how_to/transformnode
  23848. */
  23849. this.transformNodes = new Array();
  23850. /**
  23851. * ActionManagers available on the scene.
  23852. */
  23853. this.actionManagers = new Array();
  23854. /**
  23855. * Sounds to keep.
  23856. */
  23857. this.sounds = new Array();
  23858. /**
  23859. * Textures to keep.
  23860. */
  23861. this.textures = new Array();
  23862. }
  23863. /**
  23864. * Adds a parser in the list of available ones
  23865. * @param name Defines the name of the parser
  23866. * @param parser Defines the parser to add
  23867. */
  23868. AbstractScene.AddParser = function (name, parser) {
  23869. this._BabylonFileParsers[name] = parser;
  23870. };
  23871. /**
  23872. * Gets a general parser from the list of avaialble ones
  23873. * @param name Defines the name of the parser
  23874. * @returns the requested parser or null
  23875. */
  23876. AbstractScene.GetParser = function (name) {
  23877. if (this._BabylonFileParsers[name]) {
  23878. return this._BabylonFileParsers[name];
  23879. }
  23880. return null;
  23881. };
  23882. /**
  23883. * Adds n individual parser in the list of available ones
  23884. * @param name Defines the name of the parser
  23885. * @param parser Defines the parser to add
  23886. */
  23887. AbstractScene.AddIndividualParser = function (name, parser) {
  23888. this._IndividualBabylonFileParsers[name] = parser;
  23889. };
  23890. /**
  23891. * Gets an individual parser from the list of avaialble ones
  23892. * @param name Defines the name of the parser
  23893. * @returns the requested parser or null
  23894. */
  23895. AbstractScene.GetIndividualParser = function (name) {
  23896. if (this._IndividualBabylonFileParsers[name]) {
  23897. return this._IndividualBabylonFileParsers[name];
  23898. }
  23899. return null;
  23900. };
  23901. /**
  23902. * Parser json data and populate both a scene and its associated container object
  23903. * @param jsonData Defines the data to parse
  23904. * @param scene Defines the scene to parse the data for
  23905. * @param container Defines the container attached to the parsing sequence
  23906. * @param rootUrl Defines the root url of the data
  23907. */
  23908. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23909. for (var parserName in this._BabylonFileParsers) {
  23910. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23911. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23912. }
  23913. }
  23914. };
  23915. /**
  23916. * Stores the list of available parsers in the application.
  23917. */
  23918. AbstractScene._BabylonFileParsers = {};
  23919. /**
  23920. * Stores the list of available individual parsers in the application.
  23921. */
  23922. AbstractScene._IndividualBabylonFileParsers = {};
  23923. return AbstractScene;
  23924. }());
  23925. BABYLON.AbstractScene = AbstractScene;
  23926. })(BABYLON || (BABYLON = {}));
  23927. //# sourceMappingURL=babylon.abstractScene.js.map
  23928. var BABYLON;
  23929. (function (BABYLON) {
  23930. /** @hidden */
  23931. var ClickInfo = /** @class */ (function () {
  23932. function ClickInfo() {
  23933. this._singleClick = false;
  23934. this._doubleClick = false;
  23935. this._hasSwiped = false;
  23936. this._ignore = false;
  23937. }
  23938. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23939. get: function () {
  23940. return this._singleClick;
  23941. },
  23942. set: function (b) {
  23943. this._singleClick = b;
  23944. },
  23945. enumerable: true,
  23946. configurable: true
  23947. });
  23948. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23949. get: function () {
  23950. return this._doubleClick;
  23951. },
  23952. set: function (b) {
  23953. this._doubleClick = b;
  23954. },
  23955. enumerable: true,
  23956. configurable: true
  23957. });
  23958. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23959. get: function () {
  23960. return this._hasSwiped;
  23961. },
  23962. set: function (b) {
  23963. this._hasSwiped = b;
  23964. },
  23965. enumerable: true,
  23966. configurable: true
  23967. });
  23968. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23969. get: function () {
  23970. return this._ignore;
  23971. },
  23972. set: function (b) {
  23973. this._ignore = b;
  23974. },
  23975. enumerable: true,
  23976. configurable: true
  23977. });
  23978. return ClickInfo;
  23979. }());
  23980. /**
  23981. * This class is used by the onRenderingGroupObservable
  23982. */
  23983. var RenderingGroupInfo = /** @class */ (function () {
  23984. function RenderingGroupInfo() {
  23985. }
  23986. /**
  23987. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23988. * This stage will be fired no matter what
  23989. */
  23990. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23991. /**
  23992. * Called before opaque object are rendered.
  23993. * This stage will be fired only if there's 3D Opaque content to render
  23994. */
  23995. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23996. /**
  23997. * Called after the opaque objects are rendered and before the transparent ones
  23998. * This stage will be fired only if there's 3D transparent content to render
  23999. */
  24000. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  24001. /**
  24002. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  24003. * This stage will be fired no matter what
  24004. */
  24005. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  24006. return RenderingGroupInfo;
  24007. }());
  24008. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24009. /**
  24010. * Represents a scene to be rendered by the engine.
  24011. * @see http://doc.babylonjs.com/features/scene
  24012. */
  24013. var Scene = /** @class */ (function (_super) {
  24014. __extends(Scene, _super);
  24015. /**
  24016. * Creates a new Scene
  24017. * @param engine defines the engine to use to render this scene
  24018. */
  24019. function Scene(engine) {
  24020. var _this = _super.call(this) || this;
  24021. // Members
  24022. /**
  24023. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24024. */
  24025. _this.autoClear = true;
  24026. /**
  24027. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24028. */
  24029. _this.autoClearDepthAndStencil = true;
  24030. /**
  24031. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24032. */
  24033. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24034. /**
  24035. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24036. */
  24037. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24038. _this._forceWireframe = false;
  24039. _this._forcePointsCloud = false;
  24040. /**
  24041. * Gets or sets a boolean indicating if animations are enabled
  24042. */
  24043. _this.animationsEnabled = true;
  24044. _this._animationPropertiesOverride = null;
  24045. /**
  24046. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24047. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24048. */
  24049. _this.useConstantAnimationDeltaTime = false;
  24050. /**
  24051. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24052. * Please note that it requires to run a ray cast through the scene on every frame
  24053. */
  24054. _this.constantlyUpdateMeshUnderPointer = false;
  24055. /**
  24056. * Defines the HTML cursor to use when hovering over interactive elements
  24057. */
  24058. _this.hoverCursor = "pointer";
  24059. /**
  24060. * Defines the HTML default cursor to use (empty by default)
  24061. */
  24062. _this.defaultCursor = "";
  24063. /**
  24064. * This is used to call preventDefault() on pointer down
  24065. * in order to block unwanted artifacts like system double clicks
  24066. */
  24067. _this.preventDefaultOnPointerDown = true;
  24068. // Metadata
  24069. /**
  24070. * Gets or sets user defined metadata
  24071. */
  24072. _this.metadata = null;
  24073. /**
  24074. * Use this array to add regular expressions used to disable offline support for specific urls
  24075. */
  24076. _this.disableOfflineSupportExceptionRules = new Array();
  24077. /**
  24078. * An event triggered when the scene is disposed.
  24079. */
  24080. _this.onDisposeObservable = new BABYLON.Observable();
  24081. _this._onDisposeObserver = null;
  24082. /**
  24083. * An event triggered before rendering the scene (right after animations and physics)
  24084. */
  24085. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24086. _this._onBeforeRenderObserver = null;
  24087. /**
  24088. * An event triggered after rendering the scene
  24089. */
  24090. _this.onAfterRenderObservable = new BABYLON.Observable();
  24091. _this._onAfterRenderObserver = null;
  24092. /**
  24093. * An event triggered before animating the scene
  24094. */
  24095. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24096. /**
  24097. * An event triggered after animations processing
  24098. */
  24099. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24100. /**
  24101. * An event triggered before draw calls are ready to be sent
  24102. */
  24103. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24104. /**
  24105. * An event triggered after draw calls have been sent
  24106. */
  24107. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24108. /**
  24109. * An event triggered when physic simulation is about to be run
  24110. */
  24111. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24112. /**
  24113. * An event triggered when physic simulation has been done
  24114. */
  24115. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24116. /**
  24117. * An event triggered when the scene is ready
  24118. */
  24119. _this.onReadyObservable = new BABYLON.Observable();
  24120. /**
  24121. * An event triggered before rendering a camera
  24122. */
  24123. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24124. _this._onBeforeCameraRenderObserver = null;
  24125. /**
  24126. * An event triggered after rendering a camera
  24127. */
  24128. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24129. _this._onAfterCameraRenderObserver = null;
  24130. /**
  24131. * An event triggered when active meshes evaluation is about to start
  24132. */
  24133. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24134. /**
  24135. * An event triggered when active meshes evaluation is done
  24136. */
  24137. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24138. /**
  24139. * An event triggered when particles rendering is about to start
  24140. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24141. */
  24142. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24143. /**
  24144. * An event triggered when particles rendering is done
  24145. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24146. */
  24147. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24148. /**
  24149. * An event triggered when sprites rendering is about to start
  24150. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24151. */
  24152. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24153. /**
  24154. * An event triggered when sprites rendering is done
  24155. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24156. */
  24157. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24158. /**
  24159. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24160. */
  24161. _this.onDataLoadedObservable = new BABYLON.Observable();
  24162. /**
  24163. * An event triggered when a camera is created
  24164. */
  24165. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24166. /**
  24167. * An event triggered when a camera is removed
  24168. */
  24169. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24170. /**
  24171. * An event triggered when a light is created
  24172. */
  24173. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24174. /**
  24175. * An event triggered when a light is removed
  24176. */
  24177. _this.onLightRemovedObservable = new BABYLON.Observable();
  24178. /**
  24179. * An event triggered when a geometry is created
  24180. */
  24181. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24182. /**
  24183. * An event triggered when a geometry is removed
  24184. */
  24185. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24186. /**
  24187. * An event triggered when a transform node is created
  24188. */
  24189. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24190. /**
  24191. * An event triggered when a transform node is removed
  24192. */
  24193. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24194. /**
  24195. * An event triggered when a mesh is created
  24196. */
  24197. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24198. /**
  24199. * An event triggered when a mesh is removed
  24200. */
  24201. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24202. /**
  24203. * An event triggered when render targets are about to be rendered
  24204. * Can happen multiple times per frame.
  24205. */
  24206. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24207. /**
  24208. * An event triggered when render targets were rendered.
  24209. * Can happen multiple times per frame.
  24210. */
  24211. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24212. /**
  24213. * An event triggered before calculating deterministic simulation step
  24214. */
  24215. _this.onBeforeStepObservable = new BABYLON.Observable();
  24216. /**
  24217. * An event triggered after calculating deterministic simulation step
  24218. */
  24219. _this.onAfterStepObservable = new BABYLON.Observable();
  24220. /**
  24221. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24222. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24223. * 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)
  24224. */
  24225. _this.onRenderingGroupObservable = new BABYLON.Observable();
  24226. // Animations
  24227. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24228. /**
  24229. * 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).
  24230. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24231. */
  24232. _this.onPrePointerObservable = new BABYLON.Observable();
  24233. /**
  24234. * Observable event triggered each time an input event is received from the rendering canvas
  24235. */
  24236. _this.onPointerObservable = new BABYLON.Observable();
  24237. _this._meshPickProceed = false;
  24238. _this._currentPickResult = null;
  24239. _this._previousPickResult = null;
  24240. _this._totalPointersPressed = 0;
  24241. _this._doubleClickOccured = false;
  24242. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24243. _this.cameraToUseForPointers = null;
  24244. _this._pointerX = 0;
  24245. _this._pointerY = 0;
  24246. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24247. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24248. _this._startingPointerTime = 0;
  24249. _this._previousStartingPointerTime = 0;
  24250. _this._pointerCaptures = {};
  24251. // Deterministic lockstep
  24252. _this._timeAccumulator = 0;
  24253. _this._currentStepId = 0;
  24254. _this._currentInternalStep = 0;
  24255. // Keyboard
  24256. /**
  24257. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24258. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24259. */
  24260. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24261. /**
  24262. * Observable event triggered each time an keyboard event is received from the hosting window
  24263. */
  24264. _this.onKeyboardObservable = new BABYLON.Observable();
  24265. // Coordinates system
  24266. _this._useRightHandedSystem = false;
  24267. // Fog
  24268. _this._fogEnabled = true;
  24269. _this._fogMode = Scene.FOGMODE_NONE;
  24270. /**
  24271. * Gets or sets the fog color to use
  24272. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24273. */
  24274. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24275. /**
  24276. * Gets or sets the fog density to use
  24277. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24278. */
  24279. _this.fogDensity = 0.1;
  24280. /**
  24281. * Gets or sets the fog start distance to use
  24282. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24283. */
  24284. _this.fogStart = 0;
  24285. /**
  24286. * Gets or sets the fog end distance to use
  24287. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24288. */
  24289. _this.fogEnd = 1000.0;
  24290. // Lights
  24291. _this._shadowsEnabled = true;
  24292. _this._lightsEnabled = true;
  24293. /** All of the active cameras added to this scene. */
  24294. _this.activeCameras = new Array();
  24295. // Textures
  24296. _this._texturesEnabled = true;
  24297. // Particles
  24298. /**
  24299. * Gets or sets a boolean indicating if particles are enabled on this scene
  24300. */
  24301. _this.particlesEnabled = true;
  24302. // Sprites
  24303. /**
  24304. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24305. */
  24306. _this.spritesEnabled = true;
  24307. /**
  24308. * All of the sprite managers added to this scene
  24309. * @see http://doc.babylonjs.com/babylon101/sprites
  24310. */
  24311. _this.spriteManagers = new Array();
  24312. // Skeletons
  24313. _this._skeletonsEnabled = true;
  24314. // Lens flares
  24315. /**
  24316. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24317. */
  24318. _this.lensFlaresEnabled = true;
  24319. // Collisions
  24320. /**
  24321. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24322. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24323. */
  24324. _this.collisionsEnabled = true;
  24325. /**
  24326. * Defines the gravity applied to this scene (used only for collisions)
  24327. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24328. */
  24329. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24330. // Postprocesses
  24331. /**
  24332. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24333. */
  24334. _this.postProcessesEnabled = true;
  24335. /**
  24336. * The list of postprocesses added to the scene
  24337. */
  24338. _this.postProcesses = new Array();
  24339. // Customs render targets
  24340. /**
  24341. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24342. */
  24343. _this.renderTargetsEnabled = true;
  24344. /**
  24345. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24346. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24347. */
  24348. _this.dumpNextRenderTargets = false;
  24349. /**
  24350. * The list of user defined render targets added to the scene
  24351. */
  24352. _this.customRenderTargets = new Array();
  24353. /**
  24354. * Gets the list of meshes imported to the scene through SceneLoader
  24355. */
  24356. _this.importedMeshesFiles = new Array();
  24357. // Probes
  24358. /**
  24359. * Gets or sets a boolean indicating if probes are enabled on this scene
  24360. */
  24361. _this.probesEnabled = true;
  24362. /**
  24363. * The list of reflection probes added to the scene
  24364. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24365. */
  24366. _this.reflectionProbes = new Array();
  24367. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24368. // Procedural textures
  24369. /**
  24370. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24371. */
  24372. _this.proceduralTexturesEnabled = true;
  24373. /**
  24374. * The list of procedural textures added to the scene
  24375. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24376. */
  24377. _this.proceduralTextures = new Array();
  24378. /**
  24379. * The list of sound tracks added to the scene
  24380. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24381. */
  24382. _this.soundTracks = new Array();
  24383. _this._audioEnabled = true;
  24384. _this._headphone = false;
  24385. // Performance counters
  24386. _this._totalVertices = new BABYLON.PerfCounter();
  24387. /** @hidden */
  24388. _this._activeIndices = new BABYLON.PerfCounter();
  24389. /** @hidden */
  24390. _this._activeParticles = new BABYLON.PerfCounter();
  24391. /** @hidden */
  24392. _this._activeBones = new BABYLON.PerfCounter();
  24393. _this._animationTime = 0;
  24394. /**
  24395. * Gets or sets a general scale for animation speed
  24396. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24397. */
  24398. _this.animationTimeScale = 1;
  24399. _this._renderId = 0;
  24400. _this._executeWhenReadyTimeoutId = -1;
  24401. _this._intermediateRendering = false;
  24402. _this._viewUpdateFlag = -1;
  24403. _this._projectionUpdateFlag = -1;
  24404. _this._alternateViewUpdateFlag = -1;
  24405. _this._alternateProjectionUpdateFlag = -1;
  24406. /** @hidden */
  24407. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24408. _this._activeRequests = new Array();
  24409. _this._pendingData = new Array();
  24410. _this._isDisposed = false;
  24411. /**
  24412. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24413. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24414. */
  24415. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24416. _this._activeMeshes = new BABYLON.SmartArray(256);
  24417. _this._processedMaterials = new BABYLON.SmartArray(256);
  24418. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24419. /** @hidden */
  24420. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24421. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24422. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24423. /** @hidden */
  24424. _this._activeAnimatables = new Array();
  24425. _this._transformMatrix = BABYLON.Matrix.Zero();
  24426. _this._useAlternateCameraConfiguration = false;
  24427. _this._alternateRendering = false;
  24428. /**
  24429. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24430. * This is useful if there are more lights that the maximum simulteanous authorized
  24431. */
  24432. _this.requireLightSorting = false;
  24433. _this._depthRenderer = {};
  24434. /**
  24435. * Backing store of defined scene components.
  24436. */
  24437. _this._components = [];
  24438. /**
  24439. * Backing store of defined scene components.
  24440. */
  24441. _this._serializableComponents = [];
  24442. /**
  24443. * List of components to register on the next registration step.
  24444. */
  24445. _this._transientComponents = [];
  24446. /**
  24447. * Defines the actions happening before camera updates.
  24448. */
  24449. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24450. /**
  24451. * Defines the actions happening during the per mesh ready checks.
  24452. */
  24453. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24454. /**
  24455. * Defines the actions happening before evaluate active mesh checks.
  24456. */
  24457. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24458. /**
  24459. * Defines the actions happening during the evaluate sub mesh checks.
  24460. */
  24461. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24462. /**
  24463. * Defines the actions happening during the active mesh stage.
  24464. */
  24465. _this._activeMeshStage = BABYLON.Stage.Create();
  24466. /**
  24467. * Defines the actions happening during the per camera render target step.
  24468. */
  24469. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24470. /**
  24471. * Defines the actions happening just before the active camera is drawing.
  24472. */
  24473. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24474. /**
  24475. * Defines the actions happening just before a rendering group is drawing.
  24476. */
  24477. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24478. /**
  24479. * Defines the actions happening just after a rendering group has been drawn.
  24480. */
  24481. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24482. /**
  24483. * Defines the actions happening just after the active camera has been drawn.
  24484. */
  24485. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24486. _this._activeMeshesFrozen = false;
  24487. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24488. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24489. _this._engine.scenes.push(_this);
  24490. _this._uid = null;
  24491. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24492. if (BABYLON.PostProcessManager) {
  24493. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24494. }
  24495. if (BABYLON.OutlineRenderer) {
  24496. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24497. }
  24498. if (BABYLON.Tools.IsWindowObjectExist()) {
  24499. _this.attachControl();
  24500. }
  24501. //simplification queue
  24502. if (BABYLON.SimplificationQueue) {
  24503. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24504. }
  24505. //collision coordinator initialization. For now legacy per default.
  24506. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24507. // Uniform Buffer
  24508. _this._createUbo();
  24509. // Default Image processing definition
  24510. if (BABYLON.ImageProcessingConfiguration) {
  24511. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24512. }
  24513. return _this;
  24514. }
  24515. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24516. /** The fog is deactivated */
  24517. get: function () {
  24518. return Scene._FOGMODE_NONE;
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24524. /** The fog density is following an exponential function */
  24525. get: function () {
  24526. return Scene._FOGMODE_EXP;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24532. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24533. get: function () {
  24534. return Scene._FOGMODE_EXP2;
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24540. /** The fog density is following a linear function. */
  24541. get: function () {
  24542. return Scene._FOGMODE_LINEAR;
  24543. },
  24544. enumerable: true,
  24545. configurable: true
  24546. });
  24547. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24548. /**
  24549. * Texture used in all pbr material as the reflection texture.
  24550. * As in the majority of the scene they are the same (exception for multi room and so on),
  24551. * this is easier to reference from here than from all the materials.
  24552. */
  24553. get: function () {
  24554. return this._environmentTexture;
  24555. },
  24556. /**
  24557. * Texture used in all pbr material as the reflection texture.
  24558. * As in the majority of the scene they are the same (exception for multi room and so on),
  24559. * this is easier to set here than in all the materials.
  24560. */
  24561. set: function (value) {
  24562. if (this._environmentTexture === value) {
  24563. return;
  24564. }
  24565. this._environmentTexture = value;
  24566. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24567. },
  24568. enumerable: true,
  24569. configurable: true
  24570. });
  24571. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24572. /**
  24573. * Default image processing configuration used either in the rendering
  24574. * Forward main pass or through the imageProcessingPostProcess if present.
  24575. * As in the majority of the scene they are the same (exception for multi camera),
  24576. * this is easier to reference from here than from all the materials and post process.
  24577. *
  24578. * No setter as we it is a shared configuration, you can set the values instead.
  24579. */
  24580. get: function () {
  24581. return this._imageProcessingConfiguration;
  24582. },
  24583. enumerable: true,
  24584. configurable: true
  24585. });
  24586. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24587. get: function () {
  24588. return this._forceWireframe;
  24589. },
  24590. /**
  24591. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24592. */
  24593. set: function (value) {
  24594. if (this._forceWireframe === value) {
  24595. return;
  24596. }
  24597. this._forceWireframe = value;
  24598. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24599. },
  24600. enumerable: true,
  24601. configurable: true
  24602. });
  24603. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24604. get: function () {
  24605. return this._forcePointsCloud;
  24606. },
  24607. /**
  24608. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24609. */
  24610. set: function (value) {
  24611. if (this._forcePointsCloud === value) {
  24612. return;
  24613. }
  24614. this._forcePointsCloud = value;
  24615. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24616. },
  24617. enumerable: true,
  24618. configurable: true
  24619. });
  24620. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24621. /**
  24622. * Gets or sets the animation properties override
  24623. */
  24624. get: function () {
  24625. return this._animationPropertiesOverride;
  24626. },
  24627. set: function (value) {
  24628. this._animationPropertiesOverride = value;
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. Object.defineProperty(Scene.prototype, "onDispose", {
  24634. /** Sets a function to be executed when this scene is disposed. */
  24635. set: function (callback) {
  24636. if (this._onDisposeObserver) {
  24637. this.onDisposeObservable.remove(this._onDisposeObserver);
  24638. }
  24639. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24640. },
  24641. enumerable: true,
  24642. configurable: true
  24643. });
  24644. Object.defineProperty(Scene.prototype, "beforeRender", {
  24645. /** Sets a function to be executed before rendering this scene */
  24646. set: function (callback) {
  24647. if (this._onBeforeRenderObserver) {
  24648. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24649. }
  24650. if (callback) {
  24651. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24652. }
  24653. },
  24654. enumerable: true,
  24655. configurable: true
  24656. });
  24657. Object.defineProperty(Scene.prototype, "afterRender", {
  24658. /** Sets a function to be executed after rendering this scene */
  24659. set: function (callback) {
  24660. if (this._onAfterRenderObserver) {
  24661. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24662. }
  24663. if (callback) {
  24664. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24665. }
  24666. },
  24667. enumerable: true,
  24668. configurable: true
  24669. });
  24670. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24671. /** Sets a function to be executed before rendering a camera*/
  24672. set: function (callback) {
  24673. if (this._onBeforeCameraRenderObserver) {
  24674. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24675. }
  24676. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24677. },
  24678. enumerable: true,
  24679. configurable: true
  24680. });
  24681. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24682. /** Sets a function to be executed after rendering a camera*/
  24683. set: function (callback) {
  24684. if (this._onAfterCameraRenderObserver) {
  24685. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24686. }
  24687. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24693. /**
  24694. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24695. */
  24696. get: function () {
  24697. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24698. },
  24699. enumerable: true,
  24700. configurable: true
  24701. });
  24702. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24703. get: function () {
  24704. return this._useRightHandedSystem;
  24705. },
  24706. /**
  24707. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24708. */
  24709. set: function (value) {
  24710. if (this._useRightHandedSystem === value) {
  24711. return;
  24712. }
  24713. this._useRightHandedSystem = value;
  24714. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24715. },
  24716. enumerable: true,
  24717. configurable: true
  24718. });
  24719. /**
  24720. * Sets the step Id used by deterministic lock step
  24721. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24722. * @param newStepId defines the step Id
  24723. */
  24724. Scene.prototype.setStepId = function (newStepId) {
  24725. this._currentStepId = newStepId;
  24726. };
  24727. ;
  24728. /**
  24729. * Gets the step Id used by deterministic lock step
  24730. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24731. * @returns the step Id
  24732. */
  24733. Scene.prototype.getStepId = function () {
  24734. return this._currentStepId;
  24735. };
  24736. ;
  24737. /**
  24738. * Gets the internal step used by deterministic lock step
  24739. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24740. * @returns the internal step
  24741. */
  24742. Scene.prototype.getInternalStep = function () {
  24743. return this._currentInternalStep;
  24744. };
  24745. ;
  24746. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24747. get: function () {
  24748. return this._fogEnabled;
  24749. },
  24750. /**
  24751. * Gets or sets a boolean indicating if fog is enabled on this scene
  24752. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24753. */
  24754. set: function (value) {
  24755. if (this._fogEnabled === value) {
  24756. return;
  24757. }
  24758. this._fogEnabled = value;
  24759. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24760. },
  24761. enumerable: true,
  24762. configurable: true
  24763. });
  24764. Object.defineProperty(Scene.prototype, "fogMode", {
  24765. get: function () {
  24766. return this._fogMode;
  24767. },
  24768. /**
  24769. * Gets or sets the fog mode to use
  24770. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24771. */
  24772. set: function (value) {
  24773. if (this._fogMode === value) {
  24774. return;
  24775. }
  24776. this._fogMode = value;
  24777. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24783. get: function () {
  24784. return this._shadowsEnabled;
  24785. },
  24786. /**
  24787. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24788. */
  24789. set: function (value) {
  24790. if (this._shadowsEnabled === value) {
  24791. return;
  24792. }
  24793. this._shadowsEnabled = value;
  24794. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24800. get: function () {
  24801. return this._lightsEnabled;
  24802. },
  24803. /**
  24804. * Gets or sets a boolean indicating if lights are enabled on this scene
  24805. */
  24806. set: function (value) {
  24807. if (this._lightsEnabled === value) {
  24808. return;
  24809. }
  24810. this._lightsEnabled = value;
  24811. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24812. },
  24813. enumerable: true,
  24814. configurable: true
  24815. });
  24816. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24817. /** The default material used on meshes when no material is affected */
  24818. get: function () {
  24819. if (!this._defaultMaterial) {
  24820. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24821. }
  24822. return this._defaultMaterial;
  24823. },
  24824. /** The default material used on meshes when no material is affected */
  24825. set: function (value) {
  24826. this._defaultMaterial = value;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24832. get: function () {
  24833. return this._texturesEnabled;
  24834. },
  24835. /**
  24836. * Gets or sets a boolean indicating if textures are enabled on this scene
  24837. */
  24838. set: function (value) {
  24839. if (this._texturesEnabled === value) {
  24840. return;
  24841. }
  24842. this._texturesEnabled = value;
  24843. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24844. },
  24845. enumerable: true,
  24846. configurable: true
  24847. });
  24848. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24849. get: function () {
  24850. return this._skeletonsEnabled;
  24851. },
  24852. /**
  24853. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24854. */
  24855. set: function (value) {
  24856. if (this._skeletonsEnabled === value) {
  24857. return;
  24858. }
  24859. this._skeletonsEnabled = value;
  24860. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24861. },
  24862. enumerable: true,
  24863. configurable: true
  24864. });
  24865. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24866. /**
  24867. * Gets the postprocess render pipeline manager
  24868. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24869. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24870. */
  24871. get: function () {
  24872. if (!this._postProcessRenderPipelineManager) {
  24873. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24874. }
  24875. return this._postProcessRenderPipelineManager;
  24876. },
  24877. enumerable: true,
  24878. configurable: true
  24879. });
  24880. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24881. /**
  24882. * Gets the main soundtrack associated with the scene
  24883. */
  24884. get: function () {
  24885. if (!this._mainSoundTrack) {
  24886. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24887. }
  24888. return this._mainSoundTrack;
  24889. },
  24890. enumerable: true,
  24891. configurable: true
  24892. });
  24893. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24894. /** @hidden */
  24895. get: function () {
  24896. return this._alternateRendering;
  24897. },
  24898. enumerable: true,
  24899. configurable: true
  24900. });
  24901. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24902. /**
  24903. * Gets the list of frustum planes (built from the active camera)
  24904. */
  24905. get: function () {
  24906. return this._frustumPlanes;
  24907. },
  24908. enumerable: true,
  24909. configurable: true
  24910. });
  24911. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24912. /**
  24913. * Gets the current geometry buffer associated to the scene.
  24914. */
  24915. get: function () {
  24916. return this._geometryBufferRenderer;
  24917. },
  24918. /**
  24919. * Sets the current geometry buffer for the scene.
  24920. */
  24921. set: function (geometryBufferRenderer) {
  24922. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24923. this._geometryBufferRenderer = geometryBufferRenderer;
  24924. }
  24925. },
  24926. enumerable: true,
  24927. configurable: true
  24928. });
  24929. /**
  24930. * Registers the transient components if needed.
  24931. */
  24932. Scene.prototype._registerTransientComponents = function () {
  24933. // Register components that have been associated lately to the scene.
  24934. if (this._transientComponents.length > 0) {
  24935. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24936. var component = _a[_i];
  24937. component.register();
  24938. }
  24939. this._transientComponents = [];
  24940. }
  24941. };
  24942. /**
  24943. * Add a component to the scene.
  24944. * Note that the ccomponent could be registered on th next frame if this is called after
  24945. * the register component stage.
  24946. * @param component Defines the component to add to the scene
  24947. */
  24948. Scene.prototype._addComponent = function (component) {
  24949. this._components.push(component);
  24950. this._transientComponents.push(component);
  24951. var serializableComponent = component;
  24952. if (serializableComponent.addFromContainer) {
  24953. this._serializableComponents.push(serializableComponent);
  24954. }
  24955. };
  24956. /**
  24957. * Gets a component from the scene.
  24958. * @param name defines the name of the component to retrieve
  24959. * @returns the component or null if not present
  24960. */
  24961. Scene.prototype._getComponent = function (name) {
  24962. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24963. var component = _a[_i];
  24964. if (component.name === name) {
  24965. return component;
  24966. }
  24967. }
  24968. return null;
  24969. };
  24970. Object.defineProperty(Scene.prototype, "debugLayer", {
  24971. /**
  24972. * Gets the debug layer (aka Inspector) associated with the scene
  24973. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24974. */
  24975. get: function () {
  24976. if (!this._debugLayer) {
  24977. this._debugLayer = new BABYLON.DebugLayer(this);
  24978. }
  24979. return this._debugLayer;
  24980. },
  24981. enumerable: true,
  24982. configurable: true
  24983. });
  24984. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24985. /**
  24986. * Gets a boolean indicating if collisions are processed on a web worker
  24987. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24988. */
  24989. get: function () {
  24990. return this._workerCollisions;
  24991. },
  24992. set: function (enabled) {
  24993. if (!BABYLON.CollisionCoordinatorLegacy) {
  24994. return;
  24995. }
  24996. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24997. this._workerCollisions = enabled;
  24998. if (this.collisionCoordinator) {
  24999. this.collisionCoordinator.destroy();
  25000. }
  25001. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25002. this.collisionCoordinator.init(this);
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. Object.defineProperty(Scene.prototype, "selectionOctree", {
  25008. /**
  25009. * Gets the octree used to boost mesh selection (picking)
  25010. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25011. */
  25012. get: function () {
  25013. return this._selectionOctree;
  25014. },
  25015. enumerable: true,
  25016. configurable: true
  25017. });
  25018. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25019. /**
  25020. * Gets the mesh that is currently under the pointer
  25021. */
  25022. get: function () {
  25023. return this._pointerOverMesh;
  25024. },
  25025. enumerable: true,
  25026. configurable: true
  25027. });
  25028. Object.defineProperty(Scene.prototype, "pointerX", {
  25029. /**
  25030. * Gets the current on-screen X position of the pointer
  25031. */
  25032. get: function () {
  25033. return this._pointerX;
  25034. },
  25035. enumerable: true,
  25036. configurable: true
  25037. });
  25038. Object.defineProperty(Scene.prototype, "pointerY", {
  25039. /**
  25040. * Gets the current on-screen Y position of the pointer
  25041. */
  25042. get: function () {
  25043. return this._pointerY;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. /**
  25049. * Gets the cached material (ie. the latest rendered one)
  25050. * @returns the cached material
  25051. */
  25052. Scene.prototype.getCachedMaterial = function () {
  25053. return this._cachedMaterial;
  25054. };
  25055. /**
  25056. * Gets the cached effect (ie. the latest rendered one)
  25057. * @returns the cached effect
  25058. */
  25059. Scene.prototype.getCachedEffect = function () {
  25060. return this._cachedEffect;
  25061. };
  25062. /**
  25063. * Gets the cached visibility state (ie. the latest rendered one)
  25064. * @returns the cached visibility state
  25065. */
  25066. Scene.prototype.getCachedVisibility = function () {
  25067. return this._cachedVisibility;
  25068. };
  25069. /**
  25070. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25071. * @param material defines the current material
  25072. * @param effect defines the current effect
  25073. * @param visibility defines the current visibility state
  25074. * @returns true if one parameter is not cached
  25075. */
  25076. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25077. if (visibility === void 0) { visibility = 1; }
  25078. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25079. };
  25080. /**
  25081. * Gets the outline renderer associated with the scene
  25082. * @returns a OutlineRenderer
  25083. */
  25084. Scene.prototype.getOutlineRenderer = function () {
  25085. return this._outlineRenderer;
  25086. };
  25087. /**
  25088. * Gets the engine associated with the scene
  25089. * @returns an Engine
  25090. */
  25091. Scene.prototype.getEngine = function () {
  25092. return this._engine;
  25093. };
  25094. /**
  25095. * Gets the total number of vertices rendered per frame
  25096. * @returns the total number of vertices rendered per frame
  25097. */
  25098. Scene.prototype.getTotalVertices = function () {
  25099. return this._totalVertices.current;
  25100. };
  25101. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25102. /**
  25103. * Gets the performance counter for total vertices
  25104. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25105. */
  25106. get: function () {
  25107. return this._totalVertices;
  25108. },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. /**
  25113. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25114. * @returns the total number of active indices rendered per frame
  25115. */
  25116. Scene.prototype.getActiveIndices = function () {
  25117. return this._activeIndices.current;
  25118. };
  25119. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25120. /**
  25121. * Gets the performance counter for active indices
  25122. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25123. */
  25124. get: function () {
  25125. return this._activeIndices;
  25126. },
  25127. enumerable: true,
  25128. configurable: true
  25129. });
  25130. /**
  25131. * Gets the total number of active particles rendered per frame
  25132. * @returns the total number of active particles rendered per frame
  25133. */
  25134. Scene.prototype.getActiveParticles = function () {
  25135. return this._activeParticles.current;
  25136. };
  25137. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25138. /**
  25139. * Gets the performance counter for active particles
  25140. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25141. */
  25142. get: function () {
  25143. return this._activeParticles;
  25144. },
  25145. enumerable: true,
  25146. configurable: true
  25147. });
  25148. /**
  25149. * Gets the total number of active bones rendered per frame
  25150. * @returns the total number of active bones rendered per frame
  25151. */
  25152. Scene.prototype.getActiveBones = function () {
  25153. return this._activeBones.current;
  25154. };
  25155. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25156. /**
  25157. * Gets the performance counter for active bones
  25158. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25159. */
  25160. get: function () {
  25161. return this._activeBones;
  25162. },
  25163. enumerable: true,
  25164. configurable: true
  25165. });
  25166. /** @hidden */
  25167. Scene.prototype.getInterFramePerfCounter = function () {
  25168. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25169. return 0;
  25170. };
  25171. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25172. /** @hidden */
  25173. get: function () {
  25174. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25175. return null;
  25176. },
  25177. enumerable: true,
  25178. configurable: true
  25179. });
  25180. /** @hidden */
  25181. Scene.prototype.getLastFrameDuration = function () {
  25182. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25183. return 0;
  25184. };
  25185. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25186. /** @hidden */
  25187. get: function () {
  25188. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25189. return null;
  25190. },
  25191. enumerable: true,
  25192. configurable: true
  25193. });
  25194. /** @hidden */
  25195. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25196. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25197. return 0;
  25198. };
  25199. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25200. /** @hidden */
  25201. get: function () {
  25202. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25203. return null;
  25204. },
  25205. enumerable: true,
  25206. configurable: true
  25207. });
  25208. /**
  25209. * Gets the array of active meshes
  25210. * @returns an array of AbstractMesh
  25211. */
  25212. Scene.prototype.getActiveMeshes = function () {
  25213. return this._activeMeshes;
  25214. };
  25215. /** @hidden */
  25216. Scene.prototype.getRenderTargetsDuration = function () {
  25217. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25218. return 0;
  25219. };
  25220. /** @hidden */
  25221. Scene.prototype.getRenderDuration = function () {
  25222. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25223. return 0;
  25224. };
  25225. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25226. /** @hidden */
  25227. get: function () {
  25228. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25229. return null;
  25230. },
  25231. enumerable: true,
  25232. configurable: true
  25233. });
  25234. /** @hidden */
  25235. Scene.prototype.getParticlesDuration = function () {
  25236. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25237. return 0;
  25238. };
  25239. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25240. /** @hidden */
  25241. get: function () {
  25242. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25243. return null;
  25244. },
  25245. enumerable: true,
  25246. configurable: true
  25247. });
  25248. /** @hidden */
  25249. Scene.prototype.getSpritesDuration = function () {
  25250. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25251. return 0;
  25252. };
  25253. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25254. /** @hidden */
  25255. get: function () {
  25256. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25257. return null;
  25258. },
  25259. enumerable: true,
  25260. configurable: true
  25261. });
  25262. /**
  25263. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25264. * @returns a number
  25265. */
  25266. Scene.prototype.getAnimationRatio = function () {
  25267. return this._animationRatio;
  25268. };
  25269. /**
  25270. * Gets an unique Id for the current frame
  25271. * @returns a number
  25272. */
  25273. Scene.prototype.getRenderId = function () {
  25274. return this._renderId;
  25275. };
  25276. /** Call this function if you want to manually increment the render Id*/
  25277. Scene.prototype.incrementRenderId = function () {
  25278. this._renderId++;
  25279. };
  25280. Scene.prototype._updatePointerPosition = function (evt) {
  25281. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25282. if (!canvasRect) {
  25283. return;
  25284. }
  25285. this._pointerX = evt.clientX - canvasRect.left;
  25286. this._pointerY = evt.clientY - canvasRect.top;
  25287. this._unTranslatedPointerX = this._pointerX;
  25288. this._unTranslatedPointerY = this._pointerY;
  25289. };
  25290. Scene.prototype._createUbo = function () {
  25291. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25292. this._sceneUbo.addUniform("viewProjection", 16);
  25293. this._sceneUbo.addUniform("view", 16);
  25294. };
  25295. Scene.prototype._createAlternateUbo = function () {
  25296. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25297. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25298. this._alternateSceneUbo.addUniform("view", 16);
  25299. };
  25300. // Pointers handling
  25301. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25302. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25303. if (result) {
  25304. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25305. }
  25306. return result;
  25307. };
  25308. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25309. if (pointerInfo.pickInfo) {
  25310. if (!pointerInfo.pickInfo.ray) {
  25311. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25312. }
  25313. }
  25314. };
  25315. /**
  25316. * Use this method to simulate a pointer move on a mesh
  25317. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25318. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25319. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25320. * @returns the current scene
  25321. */
  25322. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25323. var evt = new PointerEvent("pointermove", pointerEventInit);
  25324. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25325. return this;
  25326. }
  25327. return this._processPointerMove(pickResult, evt);
  25328. };
  25329. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25330. var canvas = this._engine.getRenderingCanvas();
  25331. if (!canvas) {
  25332. return this;
  25333. }
  25334. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25335. this.setPointerOverSprite(null);
  25336. this.setPointerOverMesh(pickResult.pickedMesh);
  25337. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25338. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25339. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25340. }
  25341. else {
  25342. canvas.style.cursor = this.hoverCursor;
  25343. }
  25344. }
  25345. else {
  25346. canvas.style.cursor = this.defaultCursor;
  25347. }
  25348. }
  25349. else {
  25350. this.setPointerOverMesh(null);
  25351. // Sprites
  25352. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25353. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25354. this.setPointerOverSprite(pickResult.pickedSprite);
  25355. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25356. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25357. }
  25358. else {
  25359. canvas.style.cursor = this.hoverCursor;
  25360. }
  25361. }
  25362. else {
  25363. this.setPointerOverSprite(null);
  25364. // Restore pointer
  25365. canvas.style.cursor = this.defaultCursor;
  25366. }
  25367. }
  25368. if (pickResult) {
  25369. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25370. if (this.onPointerMove) {
  25371. this.onPointerMove(evt, pickResult, type);
  25372. }
  25373. if (this.onPointerObservable.hasObservers()) {
  25374. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25375. this._setRayOnPointerInfo(pi);
  25376. this.onPointerObservable.notifyObservers(pi, type);
  25377. }
  25378. }
  25379. return this;
  25380. };
  25381. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25382. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25383. if (pickResult) {
  25384. pi.ray = pickResult.ray;
  25385. }
  25386. this.onPrePointerObservable.notifyObservers(pi, type);
  25387. if (pi.skipOnPointerObservable) {
  25388. return true;
  25389. }
  25390. else {
  25391. return false;
  25392. }
  25393. };
  25394. /**
  25395. * Use this method to simulate a pointer down on a mesh
  25396. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25397. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25398. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25399. * @returns the current scene
  25400. */
  25401. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25402. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25403. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25404. return this;
  25405. }
  25406. return this._processPointerDown(pickResult, evt);
  25407. };
  25408. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25409. var _this = this;
  25410. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25411. this._pickedDownMesh = pickResult.pickedMesh;
  25412. var actionManager = pickResult.pickedMesh.actionManager;
  25413. if (actionManager) {
  25414. if (actionManager.hasPickTriggers) {
  25415. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25416. switch (evt.button) {
  25417. case 0:
  25418. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25419. break;
  25420. case 1:
  25421. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25422. break;
  25423. case 2:
  25424. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25425. break;
  25426. }
  25427. }
  25428. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25429. window.setTimeout(function () {
  25430. 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);
  25431. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25432. if (_this._totalPointersPressed !== 0 &&
  25433. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25434. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25435. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25436. _this._startingPointerTime = 0;
  25437. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25438. }
  25439. }
  25440. }, Scene.LongPressDelay);
  25441. }
  25442. }
  25443. }
  25444. if (pickResult) {
  25445. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25446. if (this.onPointerDown) {
  25447. this.onPointerDown(evt, pickResult, type);
  25448. }
  25449. if (this.onPointerObservable.hasObservers()) {
  25450. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25451. this._setRayOnPointerInfo(pi);
  25452. this.onPointerObservable.notifyObservers(pi, type);
  25453. }
  25454. }
  25455. return this;
  25456. };
  25457. /**
  25458. * Use this method to simulate a pointer up on a mesh
  25459. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25460. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25461. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25462. * @returns the current scene
  25463. */
  25464. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25465. var evt = new PointerEvent("pointerup", pointerEventInit);
  25466. var clickInfo = new ClickInfo();
  25467. clickInfo.singleClick = true;
  25468. clickInfo.ignore = true;
  25469. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25470. return this;
  25471. }
  25472. return this._processPointerUp(pickResult, evt, clickInfo);
  25473. };
  25474. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25475. if (pickResult && pickResult && pickResult.pickedMesh) {
  25476. this._pickedUpMesh = pickResult.pickedMesh;
  25477. if (this._pickedDownMesh === this._pickedUpMesh) {
  25478. if (this.onPointerPick) {
  25479. this.onPointerPick(evt, pickResult);
  25480. }
  25481. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25482. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25483. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25484. this._setRayOnPointerInfo(pi);
  25485. this.onPointerObservable.notifyObservers(pi, type_1);
  25486. }
  25487. }
  25488. if (pickResult.pickedMesh.actionManager) {
  25489. if (clickInfo.ignore) {
  25490. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25491. }
  25492. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25493. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25494. }
  25495. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25497. }
  25498. }
  25499. }
  25500. if (this._pickedDownMesh &&
  25501. this._pickedDownMesh.actionManager &&
  25502. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25503. this._pickedDownMesh !== this._pickedUpMesh) {
  25504. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25505. }
  25506. var type = BABYLON.PointerEventTypes.POINTERUP;
  25507. if (this.onPointerObservable.hasObservers()) {
  25508. if (!clickInfo.ignore) {
  25509. if (!clickInfo.hasSwiped) {
  25510. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25511. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25512. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25513. this._setRayOnPointerInfo(pi);
  25514. this.onPointerObservable.notifyObservers(pi, type_2);
  25515. }
  25516. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25517. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25518. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25519. this._setRayOnPointerInfo(pi);
  25520. this.onPointerObservable.notifyObservers(pi, type_3);
  25521. }
  25522. }
  25523. }
  25524. else {
  25525. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25526. this._setRayOnPointerInfo(pi);
  25527. this.onPointerObservable.notifyObservers(pi, type);
  25528. }
  25529. }
  25530. if (this.onPointerUp) {
  25531. this.onPointerUp(evt, pickResult, type);
  25532. }
  25533. return this;
  25534. };
  25535. /**
  25536. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25537. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25538. * @returns true if the pointer was captured
  25539. */
  25540. Scene.prototype.isPointerCaptured = function (pointerId) {
  25541. if (pointerId === void 0) { pointerId = 0; }
  25542. return this._pointerCaptures[pointerId];
  25543. };
  25544. /**
  25545. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25546. * @param attachUp defines if you want to attach events to pointerup
  25547. * @param attachDown defines if you want to attach events to pointerdown
  25548. * @param attachMove defines if you want to attach events to pointermove
  25549. */
  25550. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25551. var _this = this;
  25552. if (attachUp === void 0) { attachUp = true; }
  25553. if (attachDown === void 0) { attachDown = true; }
  25554. if (attachMove === void 0) { attachMove = true; }
  25555. this._initActionManager = function (act, clickInfo) {
  25556. if (!_this._meshPickProceed) {
  25557. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25558. _this._currentPickResult = pickResult;
  25559. if (pickResult) {
  25560. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25561. }
  25562. _this._meshPickProceed = true;
  25563. }
  25564. return act;
  25565. };
  25566. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25567. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25568. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25569. btn !== _this._previousButtonPressed) {
  25570. _this._doubleClickOccured = false;
  25571. clickInfo.singleClick = true;
  25572. clickInfo.ignore = false;
  25573. cb(clickInfo, _this._currentPickResult);
  25574. }
  25575. };
  25576. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25577. var clickInfo = new ClickInfo();
  25578. _this._currentPickResult = null;
  25579. var act = null;
  25580. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25581. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25582. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25583. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25584. act = _this._initActionManager(act, clickInfo);
  25585. if (act)
  25586. checkPicking = act.hasPickTriggers;
  25587. }
  25588. if (checkPicking) {
  25589. var btn = evt.button;
  25590. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25591. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25592. if (!clickInfo.hasSwiped) {
  25593. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25594. if (!checkSingleClickImmediately) {
  25595. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25596. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25597. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25598. act = _this._initActionManager(act, clickInfo);
  25599. if (act)
  25600. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25601. }
  25602. }
  25603. if (checkSingleClickImmediately) {
  25604. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25605. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25606. btn !== _this._previousButtonPressed) {
  25607. clickInfo.singleClick = true;
  25608. cb(clickInfo, _this._currentPickResult);
  25609. }
  25610. }
  25611. // at least one double click is required to be check and exclusive double click is enabled
  25612. else {
  25613. // wait that no double click has been raised during the double click delay
  25614. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25615. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25616. }
  25617. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25618. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25619. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25620. act = _this._initActionManager(act, clickInfo);
  25621. if (act)
  25622. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25623. }
  25624. if (checkDoubleClick) {
  25625. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25626. if (btn === _this._previousButtonPressed &&
  25627. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25628. !_this._doubleClickOccured) {
  25629. // pointer has not moved for 2 clicks, it's a double click
  25630. if (!clickInfo.hasSwiped &&
  25631. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25632. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25633. _this._previousStartingPointerTime = 0;
  25634. _this._doubleClickOccured = true;
  25635. clickInfo.doubleClick = true;
  25636. clickInfo.ignore = false;
  25637. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25638. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25639. }
  25640. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25641. cb(clickInfo, _this._currentPickResult);
  25642. }
  25643. // if the two successive clicks are too far, it's just two simple clicks
  25644. else {
  25645. _this._doubleClickOccured = false;
  25646. _this._previousStartingPointerTime = _this._startingPointerTime;
  25647. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25648. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25649. _this._previousButtonPressed = btn;
  25650. if (Scene.ExclusiveDoubleClickMode) {
  25651. if (_this._previousDelayedSimpleClickTimeout) {
  25652. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25653. }
  25654. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25655. cb(clickInfo, _this._previousPickResult);
  25656. }
  25657. else {
  25658. cb(clickInfo, _this._currentPickResult);
  25659. }
  25660. }
  25661. }
  25662. // just the first click of the double has been raised
  25663. else {
  25664. _this._doubleClickOccured = false;
  25665. _this._previousStartingPointerTime = _this._startingPointerTime;
  25666. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25667. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25668. _this._previousButtonPressed = btn;
  25669. }
  25670. }
  25671. }
  25672. }
  25673. clickInfo.ignore = true;
  25674. cb(clickInfo, _this._currentPickResult);
  25675. };
  25676. this._spritePredicate = function (sprite) {
  25677. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25678. };
  25679. this._onPointerMove = function (evt) {
  25680. _this._updatePointerPosition(evt);
  25681. // PreObservable support
  25682. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25683. return;
  25684. }
  25685. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25686. return;
  25687. }
  25688. if (!_this.pointerMovePredicate) {
  25689. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25690. }
  25691. // Meshes
  25692. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25693. _this._processPointerMove(pickResult, evt);
  25694. };
  25695. this._onPointerDown = function (evt) {
  25696. _this._totalPointersPressed++;
  25697. _this._pickedDownMesh = null;
  25698. _this._meshPickProceed = false;
  25699. _this._updatePointerPosition(evt);
  25700. if (_this.preventDefaultOnPointerDown && canvas) {
  25701. evt.preventDefault();
  25702. canvas.focus();
  25703. }
  25704. // PreObservable support
  25705. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25706. return;
  25707. }
  25708. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25709. return;
  25710. }
  25711. _this._pointerCaptures[evt.pointerId] = true;
  25712. _this._startingPointerPosition.x = _this._pointerX;
  25713. _this._startingPointerPosition.y = _this._pointerY;
  25714. _this._startingPointerTime = Date.now();
  25715. if (!_this.pointerDownPredicate) {
  25716. _this.pointerDownPredicate = function (mesh) {
  25717. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25718. };
  25719. }
  25720. // Meshes
  25721. _this._pickedDownMesh = null;
  25722. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25723. _this._processPointerDown(pickResult, evt);
  25724. // Sprites
  25725. _this._pickedDownSprite = null;
  25726. if (_this.spriteManagers.length > 0) {
  25727. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25728. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25729. if (pickResult.pickedSprite.actionManager) {
  25730. _this._pickedDownSprite = pickResult.pickedSprite;
  25731. switch (evt.button) {
  25732. case 0:
  25733. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25734. break;
  25735. case 1:
  25736. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25737. break;
  25738. case 2:
  25739. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25740. break;
  25741. }
  25742. if (pickResult.pickedSprite.actionManager) {
  25743. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25744. }
  25745. }
  25746. }
  25747. }
  25748. };
  25749. this._onPointerUp = function (evt) {
  25750. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25751. return; // So we need to test it the pointer down was pressed before.
  25752. }
  25753. _this._totalPointersPressed--;
  25754. _this._pickedUpMesh = null;
  25755. _this._meshPickProceed = false;
  25756. _this._updatePointerPosition(evt);
  25757. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25758. // PreObservable support
  25759. if (_this.onPrePointerObservable.hasObservers()) {
  25760. if (!clickInfo.ignore) {
  25761. if (!clickInfo.hasSwiped) {
  25762. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25763. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25764. return;
  25765. }
  25766. }
  25767. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25768. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25769. return;
  25770. }
  25771. }
  25772. }
  25773. }
  25774. else {
  25775. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25776. return;
  25777. }
  25778. }
  25779. }
  25780. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25781. return;
  25782. }
  25783. _this._pointerCaptures[evt.pointerId] = false;
  25784. if (!_this.pointerUpPredicate) {
  25785. _this.pointerUpPredicate = function (mesh) {
  25786. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25787. };
  25788. }
  25789. // Meshes
  25790. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25791. _this._initActionManager(null, clickInfo);
  25792. }
  25793. if (!pickResult) {
  25794. pickResult = _this._currentPickResult;
  25795. }
  25796. _this._processPointerUp(pickResult, evt, clickInfo);
  25797. // Sprites
  25798. if (!clickInfo.ignore) {
  25799. if (_this.spriteManagers.length > 0) {
  25800. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25801. if (spritePickResult) {
  25802. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25803. if (spritePickResult.pickedSprite.actionManager) {
  25804. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25805. if (spritePickResult.pickedSprite.actionManager) {
  25806. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25807. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25808. }
  25809. }
  25810. }
  25811. }
  25812. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25813. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25814. }
  25815. }
  25816. }
  25817. }
  25818. _this._previousPickResult = _this._currentPickResult;
  25819. });
  25820. };
  25821. this._onKeyDown = function (evt) {
  25822. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25823. if (_this.onPreKeyboardObservable.hasObservers()) {
  25824. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25825. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25826. if (pi.skipOnPointerObservable) {
  25827. return;
  25828. }
  25829. }
  25830. if (_this.onKeyboardObservable.hasObservers()) {
  25831. var pi = new BABYLON.KeyboardInfo(type, evt);
  25832. _this.onKeyboardObservable.notifyObservers(pi, type);
  25833. }
  25834. if (_this.actionManager) {
  25835. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25836. }
  25837. };
  25838. this._onKeyUp = function (evt) {
  25839. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25840. if (_this.onPreKeyboardObservable.hasObservers()) {
  25841. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25842. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25843. if (pi.skipOnPointerObservable) {
  25844. return;
  25845. }
  25846. }
  25847. if (_this.onKeyboardObservable.hasObservers()) {
  25848. var pi = new BABYLON.KeyboardInfo(type, evt);
  25849. _this.onKeyboardObservable.notifyObservers(pi, type);
  25850. }
  25851. if (_this.actionManager) {
  25852. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25853. }
  25854. };
  25855. var engine = this.getEngine();
  25856. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25857. if (!canvas) {
  25858. return;
  25859. }
  25860. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25861. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25862. });
  25863. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25864. if (!canvas) {
  25865. return;
  25866. }
  25867. canvas.removeEventListener("keydown", _this._onKeyDown);
  25868. canvas.removeEventListener("keyup", _this._onKeyUp);
  25869. });
  25870. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25871. var canvas = this._engine.getRenderingCanvas();
  25872. if (!canvas) {
  25873. return;
  25874. }
  25875. if (attachMove) {
  25876. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25877. // Wheel
  25878. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25879. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25880. }
  25881. if (attachDown) {
  25882. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25883. }
  25884. if (attachUp) {
  25885. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25886. }
  25887. canvas.tabIndex = 1;
  25888. };
  25889. /** Detaches all event handlers*/
  25890. Scene.prototype.detachControl = function () {
  25891. var engine = this.getEngine();
  25892. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25893. var canvas = engine.getRenderingCanvas();
  25894. if (!canvas) {
  25895. return;
  25896. }
  25897. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25898. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25899. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25900. if (this._onCanvasBlurObserver) {
  25901. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25902. }
  25903. if (this._onCanvasFocusObserver) {
  25904. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25905. }
  25906. // Wheel
  25907. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25908. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25909. // Keyboard
  25910. canvas.removeEventListener("keydown", this._onKeyDown);
  25911. canvas.removeEventListener("keyup", this._onKeyUp);
  25912. // Observables
  25913. this.onKeyboardObservable.clear();
  25914. this.onPreKeyboardObservable.clear();
  25915. this.onPointerObservable.clear();
  25916. this.onPrePointerObservable.clear();
  25917. };
  25918. /**
  25919. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25920. * Delay loaded resources are not taking in account
  25921. * @return true if all required resources are ready
  25922. */
  25923. Scene.prototype.isReady = function () {
  25924. if (this._isDisposed) {
  25925. return false;
  25926. }
  25927. if (this._pendingData.length > 0) {
  25928. return false;
  25929. }
  25930. var index;
  25931. var engine = this.getEngine();
  25932. // Geometries
  25933. for (index = 0; index < this.geometries.length; index++) {
  25934. var geometry = this.geometries[index];
  25935. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25936. return false;
  25937. }
  25938. }
  25939. // Meshes
  25940. for (index = 0; index < this.meshes.length; index++) {
  25941. var mesh = this.meshes[index];
  25942. if (!mesh.isEnabled()) {
  25943. continue;
  25944. }
  25945. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25946. continue;
  25947. }
  25948. if (!mesh.isReady(true)) {
  25949. return false;
  25950. }
  25951. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25952. // Is Ready For Mesh
  25953. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25954. var step = _a[_i];
  25955. if (!step.action(mesh, hardwareInstancedRendering)) {
  25956. return false;
  25957. }
  25958. }
  25959. }
  25960. // Post-processes
  25961. if (this.activeCameras && this.activeCameras.length > 0) {
  25962. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25963. var camera = _c[_b];
  25964. if (!camera.isReady(true)) {
  25965. return false;
  25966. }
  25967. }
  25968. }
  25969. else if (this.activeCamera) {
  25970. if (!this.activeCamera.isReady(true)) {
  25971. return false;
  25972. }
  25973. }
  25974. // Particles
  25975. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25976. var particleSystem = _e[_d];
  25977. if (!particleSystem.isReady()) {
  25978. return false;
  25979. }
  25980. }
  25981. return true;
  25982. };
  25983. /** Resets all cached information relative to material (including effect and visibility) */
  25984. Scene.prototype.resetCachedMaterial = function () {
  25985. this._cachedMaterial = null;
  25986. this._cachedEffect = null;
  25987. this._cachedVisibility = null;
  25988. };
  25989. /**
  25990. * Registers a function to be called before every frame render
  25991. * @param func defines the function to register
  25992. */
  25993. Scene.prototype.registerBeforeRender = function (func) {
  25994. this.onBeforeRenderObservable.add(func);
  25995. };
  25996. /**
  25997. * Unregisters a function called before every frame render
  25998. * @param func defines the function to unregister
  25999. */
  26000. Scene.prototype.unregisterBeforeRender = function (func) {
  26001. this.onBeforeRenderObservable.removeCallback(func);
  26002. };
  26003. /**
  26004. * Registers a function to be called after every frame render
  26005. * @param func defines the function to register
  26006. */
  26007. Scene.prototype.registerAfterRender = function (func) {
  26008. this.onAfterRenderObservable.add(func);
  26009. };
  26010. /**
  26011. * Unregisters a function called after every frame render
  26012. * @param func defines the function to unregister
  26013. */
  26014. Scene.prototype.unregisterAfterRender = function (func) {
  26015. this.onAfterRenderObservable.removeCallback(func);
  26016. };
  26017. Scene.prototype._executeOnceBeforeRender = function (func) {
  26018. var _this = this;
  26019. var execFunc = function () {
  26020. func();
  26021. setTimeout(function () {
  26022. _this.unregisterBeforeRender(execFunc);
  26023. });
  26024. };
  26025. this.registerBeforeRender(execFunc);
  26026. };
  26027. /**
  26028. * The provided function will run before render once and will be disposed afterwards.
  26029. * A timeout delay can be provided so that the function will be executed in N ms.
  26030. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26031. * @param func The function to be executed.
  26032. * @param timeout optional delay in ms
  26033. */
  26034. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26035. var _this = this;
  26036. if (timeout !== undefined) {
  26037. setTimeout(function () {
  26038. _this._executeOnceBeforeRender(func);
  26039. }, timeout);
  26040. }
  26041. else {
  26042. this._executeOnceBeforeRender(func);
  26043. }
  26044. };
  26045. /** @hidden */
  26046. Scene.prototype._addPendingData = function (data) {
  26047. this._pendingData.push(data);
  26048. };
  26049. /** @hidden */
  26050. Scene.prototype._removePendingData = function (data) {
  26051. var wasLoading = this.isLoading;
  26052. var index = this._pendingData.indexOf(data);
  26053. if (index !== -1) {
  26054. this._pendingData.splice(index, 1);
  26055. }
  26056. if (wasLoading && !this.isLoading) {
  26057. this.onDataLoadedObservable.notifyObservers(this);
  26058. }
  26059. };
  26060. /**
  26061. * Returns the number of items waiting to be loaded
  26062. * @returns the number of items waiting to be loaded
  26063. */
  26064. Scene.prototype.getWaitingItemsCount = function () {
  26065. return this._pendingData.length;
  26066. };
  26067. Object.defineProperty(Scene.prototype, "isLoading", {
  26068. /**
  26069. * Returns a boolean indicating if the scene is still loading data
  26070. */
  26071. get: function () {
  26072. return this._pendingData.length > 0;
  26073. },
  26074. enumerable: true,
  26075. configurable: true
  26076. });
  26077. /**
  26078. * Registers a function to be executed when the scene is ready
  26079. * @param {Function} func - the function to be executed
  26080. */
  26081. Scene.prototype.executeWhenReady = function (func) {
  26082. var _this = this;
  26083. this.onReadyObservable.add(func);
  26084. if (this._executeWhenReadyTimeoutId !== -1) {
  26085. return;
  26086. }
  26087. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26088. _this._checkIsReady();
  26089. }, 150);
  26090. };
  26091. /**
  26092. * Returns a promise that resolves when the scene is ready
  26093. * @returns A promise that resolves when the scene is ready
  26094. */
  26095. Scene.prototype.whenReadyAsync = function () {
  26096. var _this = this;
  26097. return new Promise(function (resolve) {
  26098. _this.executeWhenReady(function () {
  26099. resolve();
  26100. });
  26101. });
  26102. };
  26103. /** @hidden */
  26104. Scene.prototype._checkIsReady = function () {
  26105. var _this = this;
  26106. this._registerTransientComponents();
  26107. if (this.isReady()) {
  26108. this.onReadyObservable.notifyObservers(this);
  26109. this.onReadyObservable.clear();
  26110. this._executeWhenReadyTimeoutId = -1;
  26111. return;
  26112. }
  26113. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26114. _this._checkIsReady();
  26115. }, 150);
  26116. };
  26117. // Animations
  26118. /**
  26119. * Will start the animation sequence of a given target
  26120. * @param target defines the target
  26121. * @param from defines from which frame should animation start
  26122. * @param to defines until which frame should animation run.
  26123. * @param weight defines the weight to apply to the animation (1.0 by default)
  26124. * @param loop defines if the animation loops
  26125. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26126. * @param onAnimationEnd defines the function to be executed when the animation ends
  26127. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26128. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26129. * @returns the animatable object created for this animation
  26130. */
  26131. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26132. if (weight === void 0) { weight = 1.0; }
  26133. if (speedRatio === void 0) { speedRatio = 1.0; }
  26134. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26135. returnedAnimatable.weight = weight;
  26136. return returnedAnimatable;
  26137. };
  26138. /**
  26139. * Will start the animation sequence of a given target
  26140. * @param target defines the target
  26141. * @param from defines from which frame should animation start
  26142. * @param to defines until which frame should animation run.
  26143. * @param loop defines if the animation loops
  26144. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26145. * @param onAnimationEnd defines the function to be executed when the animation ends
  26146. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26147. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26148. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26149. * @returns the animatable object created for this animation
  26150. */
  26151. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26152. if (speedRatio === void 0) { speedRatio = 1.0; }
  26153. if (stopCurrent === void 0) { stopCurrent = true; }
  26154. if (from > to && speedRatio > 0) {
  26155. speedRatio *= -1;
  26156. }
  26157. if (stopCurrent) {
  26158. this.stopAnimation(target, undefined, targetMask);
  26159. }
  26160. if (!animatable) {
  26161. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26162. }
  26163. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26164. // Local animations
  26165. if (target.animations && shouldRunTargetAnimations) {
  26166. animatable.appendAnimations(target, target.animations);
  26167. }
  26168. // Children animations
  26169. if (target.getAnimatables) {
  26170. var animatables = target.getAnimatables();
  26171. for (var index = 0; index < animatables.length; index++) {
  26172. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26173. }
  26174. }
  26175. animatable.reset();
  26176. return animatable;
  26177. };
  26178. /**
  26179. * Begin a new animation on a given node
  26180. * @param target defines the target where the animation will take place
  26181. * @param animations defines the list of animations to start
  26182. * @param from defines the initial value
  26183. * @param to defines the final value
  26184. * @param loop defines if you want animation to loop (off by default)
  26185. * @param speedRatio defines the speed ratio to apply to all animations
  26186. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26187. * @returns the list of created animatables
  26188. */
  26189. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26190. if (speedRatio === undefined) {
  26191. speedRatio = 1.0;
  26192. }
  26193. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26194. return animatable;
  26195. };
  26196. /**
  26197. * Begin a new animation on a given node and its hierarchy
  26198. * @param target defines the root node where the animation will take place
  26199. * @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.
  26200. * @param animations defines the list of animations to start
  26201. * @param from defines the initial value
  26202. * @param to defines the final value
  26203. * @param loop defines if you want animation to loop (off by default)
  26204. * @param speedRatio defines the speed ratio to apply to all animations
  26205. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26206. * @returns the list of animatables created for all nodes
  26207. */
  26208. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26209. var children = target.getDescendants(directDescendantsOnly);
  26210. var result = [];
  26211. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26212. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26213. var child = children_1[_i];
  26214. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26215. }
  26216. return result;
  26217. };
  26218. /**
  26219. * Gets the animatable associated with a specific target
  26220. * @param target defines the target of the animatable
  26221. * @returns the required animatable if found
  26222. */
  26223. Scene.prototype.getAnimatableByTarget = function (target) {
  26224. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26225. if (this._activeAnimatables[index].target === target) {
  26226. return this._activeAnimatables[index];
  26227. }
  26228. }
  26229. return null;
  26230. };
  26231. /**
  26232. * Gets all animatables associated with a given target
  26233. * @param target defines the target to look animatables for
  26234. * @returns an array of Animatables
  26235. */
  26236. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26237. var result = [];
  26238. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26239. if (this._activeAnimatables[index].target === target) {
  26240. result.push(this._activeAnimatables[index]);
  26241. }
  26242. }
  26243. return result;
  26244. };
  26245. Object.defineProperty(Scene.prototype, "animatables", {
  26246. /**
  26247. * Gets all animatable attached to the scene
  26248. */
  26249. get: function () {
  26250. return this._activeAnimatables;
  26251. },
  26252. enumerable: true,
  26253. configurable: true
  26254. });
  26255. /**
  26256. * Will stop the animation of the given target
  26257. * @param target - the target
  26258. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26259. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26260. */
  26261. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26262. var animatables = this.getAllAnimatablesByTarget(target);
  26263. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26264. var animatable = animatables_1[_i];
  26265. animatable.stop(animationName, targetMask);
  26266. }
  26267. };
  26268. /**
  26269. * Stops and removes all animations that have been applied to the scene
  26270. */
  26271. Scene.prototype.stopAllAnimations = function () {
  26272. if (this._activeAnimatables) {
  26273. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26274. this._activeAnimatables[i].stop();
  26275. }
  26276. this._activeAnimatables = [];
  26277. }
  26278. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26279. var group = _a[_i];
  26280. group.stop();
  26281. }
  26282. };
  26283. Scene.prototype._animate = function () {
  26284. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26285. return;
  26286. }
  26287. // Getting time
  26288. var now = BABYLON.Tools.Now;
  26289. if (!this._animationTimeLast) {
  26290. if (this._pendingData.length > 0) {
  26291. return;
  26292. }
  26293. this._animationTimeLast = now;
  26294. }
  26295. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26296. this._animationTime += deltaTime;
  26297. this._animationTimeLast = now;
  26298. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26299. this._activeAnimatables[index]._animate(this._animationTime);
  26300. }
  26301. // Late animation bindings
  26302. this._processLateAnimationBindings();
  26303. };
  26304. /** @hidden */
  26305. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26306. var target = runtimeAnimation.target;
  26307. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26308. if (!target._lateAnimationHolders) {
  26309. target._lateAnimationHolders = {};
  26310. }
  26311. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26312. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26313. totalWeight: 0,
  26314. animations: [],
  26315. originalValue: originalValue
  26316. };
  26317. }
  26318. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26319. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26320. };
  26321. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26322. var normalizer = 1.0;
  26323. var finalPosition = BABYLON.Tmp.Vector3[0];
  26324. var finalScaling = BABYLON.Tmp.Vector3[1];
  26325. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26326. var startIndex = 0;
  26327. var originalAnimation = holder.animations[0];
  26328. var originalValue = holder.originalValue;
  26329. var scale = 1;
  26330. if (holder.totalWeight < 1.0) {
  26331. // We need to mix the original value in
  26332. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26333. scale = 1.0 - holder.totalWeight;
  26334. }
  26335. else {
  26336. startIndex = 1;
  26337. // We need to normalize the weights
  26338. normalizer = holder.totalWeight;
  26339. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26340. scale = originalAnimation.weight / normalizer;
  26341. if (scale == 1) {
  26342. return originalAnimation.currentValue;
  26343. }
  26344. }
  26345. finalScaling.scaleInPlace(scale);
  26346. finalPosition.scaleInPlace(scale);
  26347. finalQuaternion.scaleInPlace(scale);
  26348. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26349. var runtimeAnimation = holder.animations[animIndex];
  26350. var scale = runtimeAnimation.weight / normalizer;
  26351. var currentPosition = BABYLON.Tmp.Vector3[2];
  26352. var currentScaling = BABYLON.Tmp.Vector3[3];
  26353. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26354. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26355. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26356. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26357. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26358. }
  26359. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26360. return originalAnimation._workValue;
  26361. };
  26362. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26363. var originalAnimation = holder.animations[0];
  26364. var originalValue = holder.originalValue;
  26365. if (holder.animations.length === 1) {
  26366. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26367. }
  26368. var normalizer = 1.0;
  26369. var quaternions;
  26370. var weights;
  26371. if (holder.totalWeight < 1.0) {
  26372. var scale = 1.0 - holder.totalWeight;
  26373. quaternions = [];
  26374. weights = [];
  26375. quaternions.push(originalValue);
  26376. weights.push(scale);
  26377. }
  26378. else {
  26379. if (holder.animations.length === 2) { // Slerp as soon as we can
  26380. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26381. }
  26382. quaternions = [];
  26383. weights = [];
  26384. normalizer = holder.totalWeight;
  26385. }
  26386. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26387. var runtimeAnimation = holder.animations[animIndex];
  26388. quaternions.push(runtimeAnimation.currentValue);
  26389. weights.push(runtimeAnimation.weight / normalizer);
  26390. }
  26391. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26392. var cumulativeAmount = 0;
  26393. var cumulativeQuaternion = null;
  26394. for (var index = 0; index < quaternions.length;) {
  26395. if (!cumulativeQuaternion) {
  26396. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26397. cumulativeAmount = weights[index] + weights[index + 1];
  26398. index += 2;
  26399. continue;
  26400. }
  26401. cumulativeAmount += weights[index];
  26402. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26403. index++;
  26404. }
  26405. return cumulativeQuaternion;
  26406. };
  26407. Scene.prototype._processLateAnimationBindings = function () {
  26408. if (!this._registeredForLateAnimationBindings.length) {
  26409. return;
  26410. }
  26411. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26412. var target = this._registeredForLateAnimationBindings.data[index];
  26413. for (var path in target._lateAnimationHolders) {
  26414. var holder = target._lateAnimationHolders[path];
  26415. var originalAnimation = holder.animations[0];
  26416. var originalValue = holder.originalValue;
  26417. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26418. var finalValue = void 0;
  26419. if (matrixDecomposeMode) {
  26420. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26421. }
  26422. else {
  26423. var quaternionMode = originalValue.w !== undefined;
  26424. if (quaternionMode) {
  26425. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26426. }
  26427. else {
  26428. var startIndex = 0;
  26429. var normalizer = 1.0;
  26430. if (holder.totalWeight < 1.0) {
  26431. // We need to mix the original value in
  26432. if (originalValue.scale) {
  26433. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26434. }
  26435. else {
  26436. finalValue = originalValue * (1.0 - holder.totalWeight);
  26437. }
  26438. }
  26439. else {
  26440. // We need to normalize the weights
  26441. normalizer = holder.totalWeight;
  26442. var scale_1 = originalAnimation.weight / normalizer;
  26443. if (scale_1 !== 1) {
  26444. if (originalAnimation.currentValue.scale) {
  26445. finalValue = originalAnimation.currentValue.scale(scale_1);
  26446. }
  26447. else {
  26448. finalValue = originalAnimation.currentValue * scale_1;
  26449. }
  26450. }
  26451. else {
  26452. finalValue = originalAnimation.currentValue;
  26453. }
  26454. startIndex = 1;
  26455. }
  26456. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26457. var runtimeAnimation = holder.animations[animIndex];
  26458. var scale = runtimeAnimation.weight / normalizer;
  26459. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26460. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26461. }
  26462. else {
  26463. finalValue += runtimeAnimation.currentValue * scale;
  26464. }
  26465. }
  26466. }
  26467. }
  26468. target[path] = finalValue;
  26469. }
  26470. target._lateAnimationHolders = {};
  26471. }
  26472. this._registeredForLateAnimationBindings.reset();
  26473. };
  26474. // Matrix
  26475. /** @hidden */
  26476. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26477. this._useAlternateCameraConfiguration = active;
  26478. };
  26479. /**
  26480. * Gets the current view matrix
  26481. * @returns a Matrix
  26482. */
  26483. Scene.prototype.getViewMatrix = function () {
  26484. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26485. };
  26486. /**
  26487. * Gets the current projection matrix
  26488. * @returns a Matrix
  26489. */
  26490. Scene.prototype.getProjectionMatrix = function () {
  26491. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26492. };
  26493. /**
  26494. * Gets the current transform matrix
  26495. * @returns a Matrix made of View * Projection
  26496. */
  26497. Scene.prototype.getTransformMatrix = function () {
  26498. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26499. };
  26500. /**
  26501. * Sets the current transform matrix
  26502. * @param view defines the View matrix to use
  26503. * @param projection defines the Projection matrix to use
  26504. */
  26505. Scene.prototype.setTransformMatrix = function (view, projection) {
  26506. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26507. return;
  26508. }
  26509. this._viewUpdateFlag = view.updateFlag;
  26510. this._projectionUpdateFlag = projection.updateFlag;
  26511. this._viewMatrix = view;
  26512. this._projectionMatrix = projection;
  26513. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26514. // Update frustum
  26515. if (!this._frustumPlanes) {
  26516. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26517. }
  26518. else {
  26519. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26520. }
  26521. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26522. var otherCamera = this.activeCamera._alternateCamera;
  26523. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26524. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26525. }
  26526. if (this._sceneUbo.useUbo) {
  26527. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26528. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26529. this._sceneUbo.update();
  26530. }
  26531. };
  26532. /** @hidden */
  26533. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26534. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26535. return;
  26536. }
  26537. this._alternateViewUpdateFlag = view.updateFlag;
  26538. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26539. this._alternateViewMatrix = view;
  26540. this._alternateProjectionMatrix = projection;
  26541. if (!this._alternateTransformMatrix) {
  26542. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26543. }
  26544. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26545. if (!this._alternateSceneUbo) {
  26546. this._createAlternateUbo();
  26547. }
  26548. if (this._alternateSceneUbo.useUbo) {
  26549. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26550. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26551. this._alternateSceneUbo.update();
  26552. }
  26553. };
  26554. /**
  26555. * Gets the uniform buffer used to store scene data
  26556. * @returns a UniformBuffer
  26557. */
  26558. Scene.prototype.getSceneUniformBuffer = function () {
  26559. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26560. };
  26561. /**
  26562. * Gets an unique (relatively to the current scene) Id
  26563. * @returns an unique number for the scene
  26564. */
  26565. Scene.prototype.getUniqueId = function () {
  26566. var result = Scene._uniqueIdCounter;
  26567. Scene._uniqueIdCounter++;
  26568. return result;
  26569. };
  26570. /**
  26571. * Add a mesh to the list of scene's meshes
  26572. * @param newMesh defines the mesh to add
  26573. * @param recursive if all child meshes should also be added to the scene
  26574. */
  26575. Scene.prototype.addMesh = function (newMesh, recursive) {
  26576. var _this = this;
  26577. if (recursive === void 0) { recursive = false; }
  26578. this.meshes.push(newMesh);
  26579. //notify the collision coordinator
  26580. if (this.collisionCoordinator) {
  26581. this.collisionCoordinator.onMeshAdded(newMesh);
  26582. }
  26583. newMesh._resyncLightSources();
  26584. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26585. if (recursive) {
  26586. newMesh.getChildMeshes().forEach(function (m) {
  26587. _this.addMesh(m);
  26588. });
  26589. }
  26590. };
  26591. /**
  26592. * Remove a mesh for the list of scene's meshes
  26593. * @param toRemove defines the mesh to remove
  26594. * @param recursive if all child meshes should also be removed from the scene
  26595. * @returns the index where the mesh was in the mesh list
  26596. */
  26597. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26598. var _this = this;
  26599. if (recursive === void 0) { recursive = false; }
  26600. var index = this.meshes.indexOf(toRemove);
  26601. if (index !== -1) {
  26602. // Remove from the scene if mesh found
  26603. this.meshes.splice(index, 1);
  26604. }
  26605. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26606. if (recursive) {
  26607. toRemove.getChildMeshes().forEach(function (m) {
  26608. _this.removeMesh(m);
  26609. });
  26610. }
  26611. return index;
  26612. };
  26613. /**
  26614. * Add a transform node to the list of scene's transform nodes
  26615. * @param newTransformNode defines the transform node to add
  26616. */
  26617. Scene.prototype.addTransformNode = function (newTransformNode) {
  26618. this.transformNodes.push(newTransformNode);
  26619. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26620. };
  26621. /**
  26622. * Remove a transform node for the list of scene's transform nodes
  26623. * @param toRemove defines the transform node to remove
  26624. * @returns the index where the transform node was in the transform node list
  26625. */
  26626. Scene.prototype.removeTransformNode = function (toRemove) {
  26627. var index = this.transformNodes.indexOf(toRemove);
  26628. if (index !== -1) {
  26629. // Remove from the scene if found
  26630. this.transformNodes.splice(index, 1);
  26631. }
  26632. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26633. return index;
  26634. };
  26635. /**
  26636. * Remove a skeleton for the list of scene's skeletons
  26637. * @param toRemove defines the skeleton to remove
  26638. * @returns the index where the skeleton was in the skeleton list
  26639. */
  26640. Scene.prototype.removeSkeleton = function (toRemove) {
  26641. var index = this.skeletons.indexOf(toRemove);
  26642. if (index !== -1) {
  26643. // Remove from the scene if found
  26644. this.skeletons.splice(index, 1);
  26645. }
  26646. return index;
  26647. };
  26648. /**
  26649. * Remove a morph target for the list of scene's morph targets
  26650. * @param toRemove defines the morph target to remove
  26651. * @returns the index where the morph target was in the morph target list
  26652. */
  26653. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26654. var index = this.morphTargetManagers.indexOf(toRemove);
  26655. if (index !== -1) {
  26656. // Remove from the scene if found
  26657. this.morphTargetManagers.splice(index, 1);
  26658. }
  26659. return index;
  26660. };
  26661. /**
  26662. * Remove a light for the list of scene's lights
  26663. * @param toRemove defines the light to remove
  26664. * @returns the index where the light was in the light list
  26665. */
  26666. Scene.prototype.removeLight = function (toRemove) {
  26667. var index = this.lights.indexOf(toRemove);
  26668. if (index !== -1) {
  26669. // Remove from meshes
  26670. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26671. var mesh = _a[_i];
  26672. mesh._removeLightSource(toRemove);
  26673. }
  26674. // Remove from the scene if mesh found
  26675. this.lights.splice(index, 1);
  26676. this.sortLightsByPriority();
  26677. }
  26678. this.onLightRemovedObservable.notifyObservers(toRemove);
  26679. return index;
  26680. };
  26681. /**
  26682. * Remove a camera for the list of scene's cameras
  26683. * @param toRemove defines the camera to remove
  26684. * @returns the index where the camera was in the camera list
  26685. */
  26686. Scene.prototype.removeCamera = function (toRemove) {
  26687. var index = this.cameras.indexOf(toRemove);
  26688. if (index !== -1) {
  26689. // Remove from the scene if mesh found
  26690. this.cameras.splice(index, 1);
  26691. }
  26692. // Remove from activeCameras
  26693. var index2 = this.activeCameras.indexOf(toRemove);
  26694. if (index2 !== -1) {
  26695. // Remove from the scene if mesh found
  26696. this.activeCameras.splice(index2, 1);
  26697. }
  26698. // Reset the activeCamera
  26699. if (this.activeCamera === toRemove) {
  26700. if (this.cameras.length > 0) {
  26701. this.activeCamera = this.cameras[0];
  26702. }
  26703. else {
  26704. this.activeCamera = null;
  26705. }
  26706. }
  26707. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26708. return index;
  26709. };
  26710. /**
  26711. * Remove a particle system for the list of scene's particle systems
  26712. * @param toRemove defines the particle system to remove
  26713. * @returns the index where the particle system was in the particle system list
  26714. */
  26715. Scene.prototype.removeParticleSystem = function (toRemove) {
  26716. var index = this.particleSystems.indexOf(toRemove);
  26717. if (index !== -1) {
  26718. this.particleSystems.splice(index, 1);
  26719. }
  26720. return index;
  26721. };
  26722. /**
  26723. * Remove a animation for the list of scene's animations
  26724. * @param toRemove defines the animation to remove
  26725. * @returns the index where the animation was in the animation list
  26726. */
  26727. Scene.prototype.removeAnimation = function (toRemove) {
  26728. var index = this.animations.indexOf(toRemove);
  26729. if (index !== -1) {
  26730. this.animations.splice(index, 1);
  26731. }
  26732. return index;
  26733. };
  26734. /**
  26735. * Removes the given animation group from this scene.
  26736. * @param toRemove The animation group to remove
  26737. * @returns The index of the removed animation group
  26738. */
  26739. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26740. var index = this.animationGroups.indexOf(toRemove);
  26741. if (index !== -1) {
  26742. this.animationGroups.splice(index, 1);
  26743. }
  26744. return index;
  26745. };
  26746. /**
  26747. * Removes the given multi-material from this scene.
  26748. * @param toRemove The multi-material to remove
  26749. * @returns The index of the removed multi-material
  26750. */
  26751. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26752. var index = this.multiMaterials.indexOf(toRemove);
  26753. if (index !== -1) {
  26754. this.multiMaterials.splice(index, 1);
  26755. }
  26756. return index;
  26757. };
  26758. /**
  26759. * Removes the given material from this scene.
  26760. * @param toRemove The material to remove
  26761. * @returns The index of the removed material
  26762. */
  26763. Scene.prototype.removeMaterial = function (toRemove) {
  26764. var index = this.materials.indexOf(toRemove);
  26765. if (index !== -1) {
  26766. this.materials.splice(index, 1);
  26767. }
  26768. return index;
  26769. };
  26770. /**
  26771. * Removes the given action manager from this scene.
  26772. * @param toRemove The action manager to remove
  26773. * @returns The index of the removed action manager
  26774. */
  26775. Scene.prototype.removeActionManager = function (toRemove) {
  26776. var index = this.actionManagers.indexOf(toRemove);
  26777. if (index !== -1) {
  26778. this.actionManagers.splice(index, 1);
  26779. }
  26780. return index;
  26781. };
  26782. /**
  26783. * Removes the given texture from this scene.
  26784. * @param toRemove The texture to remove
  26785. * @returns The index of the removed texture
  26786. */
  26787. Scene.prototype.removeTexture = function (toRemove) {
  26788. var index = this.textures.indexOf(toRemove);
  26789. if (index !== -1) {
  26790. this.textures.splice(index, 1);
  26791. }
  26792. return index;
  26793. };
  26794. /**
  26795. * Adds the given light to this scene
  26796. * @param newLight The light to add
  26797. */
  26798. Scene.prototype.addLight = function (newLight) {
  26799. this.lights.push(newLight);
  26800. this.sortLightsByPriority();
  26801. // Add light to all meshes (To support if the light is removed and then readded)
  26802. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26803. var mesh = _a[_i];
  26804. if (mesh._lightSources.indexOf(newLight) === -1) {
  26805. mesh._lightSources.push(newLight);
  26806. mesh._resyncLightSources();
  26807. }
  26808. }
  26809. this.onNewLightAddedObservable.notifyObservers(newLight);
  26810. };
  26811. /**
  26812. * Sorts the list list based on light priorities
  26813. */
  26814. Scene.prototype.sortLightsByPriority = function () {
  26815. if (this.requireLightSorting) {
  26816. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26817. }
  26818. };
  26819. /**
  26820. * Adds the given camera to this scene
  26821. * @param newCamera The camera to add
  26822. */
  26823. Scene.prototype.addCamera = function (newCamera) {
  26824. this.cameras.push(newCamera);
  26825. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26826. };
  26827. /**
  26828. * Adds the given skeleton to this scene
  26829. * @param newSkeleton The skeleton to add
  26830. */
  26831. Scene.prototype.addSkeleton = function (newSkeleton) {
  26832. this.skeletons.push(newSkeleton);
  26833. };
  26834. /**
  26835. * Adds the given particle system to this scene
  26836. * @param newParticleSystem The particle system to add
  26837. */
  26838. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26839. this.particleSystems.push(newParticleSystem);
  26840. };
  26841. /**
  26842. * Adds the given animation to this scene
  26843. * @param newAnimation The animation to add
  26844. */
  26845. Scene.prototype.addAnimation = function (newAnimation) {
  26846. this.animations.push(newAnimation);
  26847. };
  26848. /**
  26849. * Adds the given animation group to this scene.
  26850. * @param newAnimationGroup The animation group to add
  26851. */
  26852. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26853. this.animationGroups.push(newAnimationGroup);
  26854. };
  26855. /**
  26856. * Adds the given multi-material to this scene
  26857. * @param newMultiMaterial The multi-material to add
  26858. */
  26859. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26860. this.multiMaterials.push(newMultiMaterial);
  26861. };
  26862. /**
  26863. * Adds the given material to this scene
  26864. * @param newMaterial The material to add
  26865. */
  26866. Scene.prototype.addMaterial = function (newMaterial) {
  26867. this.materials.push(newMaterial);
  26868. };
  26869. /**
  26870. * Adds the given morph target to this scene
  26871. * @param newMorphTargetManager The morph target to add
  26872. */
  26873. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26874. this.morphTargetManagers.push(newMorphTargetManager);
  26875. };
  26876. /**
  26877. * Adds the given geometry to this scene
  26878. * @param newGeometry The geometry to add
  26879. */
  26880. Scene.prototype.addGeometry = function (newGeometry) {
  26881. this.geometries.push(newGeometry);
  26882. };
  26883. /**
  26884. * Adds the given action manager to this scene
  26885. * @param newActionManager The action manager to add
  26886. */
  26887. Scene.prototype.addActionManager = function (newActionManager) {
  26888. this.actionManagers.push(newActionManager);
  26889. };
  26890. /**
  26891. * Adds the given texture to this scene.
  26892. * @param newTexture The texture to add
  26893. */
  26894. Scene.prototype.addTexture = function (newTexture) {
  26895. this.textures.push(newTexture);
  26896. };
  26897. /**
  26898. * Switch active camera
  26899. * @param newCamera defines the new active camera
  26900. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26901. */
  26902. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26903. if (attachControl === void 0) { attachControl = true; }
  26904. var canvas = this._engine.getRenderingCanvas();
  26905. if (!canvas) {
  26906. return;
  26907. }
  26908. if (this.activeCamera) {
  26909. this.activeCamera.detachControl(canvas);
  26910. }
  26911. this.activeCamera = newCamera;
  26912. if (attachControl) {
  26913. newCamera.attachControl(canvas);
  26914. }
  26915. };
  26916. /**
  26917. * sets the active camera of the scene using its ID
  26918. * @param id defines the camera's ID
  26919. * @return the new active camera or null if none found.
  26920. */
  26921. Scene.prototype.setActiveCameraByID = function (id) {
  26922. var camera = this.getCameraByID(id);
  26923. if (camera) {
  26924. this.activeCamera = camera;
  26925. return camera;
  26926. }
  26927. return null;
  26928. };
  26929. /**
  26930. * sets the active camera of the scene using its name
  26931. * @param name defines the camera's name
  26932. * @returns the new active camera or null if none found.
  26933. */
  26934. Scene.prototype.setActiveCameraByName = function (name) {
  26935. var camera = this.getCameraByName(name);
  26936. if (camera) {
  26937. this.activeCamera = camera;
  26938. return camera;
  26939. }
  26940. return null;
  26941. };
  26942. /**
  26943. * get an animation group using its name
  26944. * @param name defines the material's name
  26945. * @return the animation group or null if none found.
  26946. */
  26947. Scene.prototype.getAnimationGroupByName = function (name) {
  26948. for (var index = 0; index < this.animationGroups.length; index++) {
  26949. if (this.animationGroups[index].name === name) {
  26950. return this.animationGroups[index];
  26951. }
  26952. }
  26953. return null;
  26954. };
  26955. /**
  26956. * get a material using its id
  26957. * @param id defines the material's ID
  26958. * @return the material or null if none found.
  26959. */
  26960. Scene.prototype.getMaterialByID = function (id) {
  26961. for (var index = 0; index < this.materials.length; index++) {
  26962. if (this.materials[index].id === id) {
  26963. return this.materials[index];
  26964. }
  26965. }
  26966. return null;
  26967. };
  26968. /**
  26969. * Gets a material using its name
  26970. * @param name defines the material's name
  26971. * @return the material or null if none found.
  26972. */
  26973. Scene.prototype.getMaterialByName = function (name) {
  26974. for (var index = 0; index < this.materials.length; index++) {
  26975. if (this.materials[index].name === name) {
  26976. return this.materials[index];
  26977. }
  26978. }
  26979. return null;
  26980. };
  26981. /**
  26982. * Gets a camera using its id
  26983. * @param id defines the id to look for
  26984. * @returns the camera or null if not found
  26985. */
  26986. Scene.prototype.getCameraByID = function (id) {
  26987. for (var index = 0; index < this.cameras.length; index++) {
  26988. if (this.cameras[index].id === id) {
  26989. return this.cameras[index];
  26990. }
  26991. }
  26992. return null;
  26993. };
  26994. /**
  26995. * Gets a camera using its unique id
  26996. * @param uniqueId defines the unique id to look for
  26997. * @returns the camera or null if not found
  26998. */
  26999. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27000. for (var index = 0; index < this.cameras.length; index++) {
  27001. if (this.cameras[index].uniqueId === uniqueId) {
  27002. return this.cameras[index];
  27003. }
  27004. }
  27005. return null;
  27006. };
  27007. /**
  27008. * Gets a camera using its name
  27009. * @param name defines the camera's name
  27010. * @return the camera or null if none found.
  27011. */
  27012. Scene.prototype.getCameraByName = function (name) {
  27013. for (var index = 0; index < this.cameras.length; index++) {
  27014. if (this.cameras[index].name === name) {
  27015. return this.cameras[index];
  27016. }
  27017. }
  27018. return null;
  27019. };
  27020. /**
  27021. * Gets a bone using its id
  27022. * @param id defines the bone's id
  27023. * @return the bone or null if not found
  27024. */
  27025. Scene.prototype.getBoneByID = function (id) {
  27026. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27027. var skeleton = this.skeletons[skeletonIndex];
  27028. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27029. if (skeleton.bones[boneIndex].id === id) {
  27030. return skeleton.bones[boneIndex];
  27031. }
  27032. }
  27033. }
  27034. return null;
  27035. };
  27036. /**
  27037. * Gets a bone using its id
  27038. * @param name defines the bone's name
  27039. * @return the bone or null if not found
  27040. */
  27041. Scene.prototype.getBoneByName = function (name) {
  27042. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27043. var skeleton = this.skeletons[skeletonIndex];
  27044. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27045. if (skeleton.bones[boneIndex].name === name) {
  27046. return skeleton.bones[boneIndex];
  27047. }
  27048. }
  27049. }
  27050. return null;
  27051. };
  27052. /**
  27053. * Gets a light node using its name
  27054. * @param name defines the the light's name
  27055. * @return the light or null if none found.
  27056. */
  27057. Scene.prototype.getLightByName = function (name) {
  27058. for (var index = 0; index < this.lights.length; index++) {
  27059. if (this.lights[index].name === name) {
  27060. return this.lights[index];
  27061. }
  27062. }
  27063. return null;
  27064. };
  27065. /**
  27066. * Gets a light node using its id
  27067. * @param id defines the light's id
  27068. * @return the light or null if none found.
  27069. */
  27070. Scene.prototype.getLightByID = function (id) {
  27071. for (var index = 0; index < this.lights.length; index++) {
  27072. if (this.lights[index].id === id) {
  27073. return this.lights[index];
  27074. }
  27075. }
  27076. return null;
  27077. };
  27078. /**
  27079. * Gets a light node using its scene-generated unique ID
  27080. * @param uniqueId defines the light's unique id
  27081. * @return the light or null if none found.
  27082. */
  27083. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27084. for (var index = 0; index < this.lights.length; index++) {
  27085. if (this.lights[index].uniqueId === uniqueId) {
  27086. return this.lights[index];
  27087. }
  27088. }
  27089. return null;
  27090. };
  27091. /**
  27092. * Gets a particle system by id
  27093. * @param id defines the particle system id
  27094. * @return the corresponding system or null if none found
  27095. */
  27096. Scene.prototype.getParticleSystemByID = function (id) {
  27097. for (var index = 0; index < this.particleSystems.length; index++) {
  27098. if (this.particleSystems[index].id === id) {
  27099. return this.particleSystems[index];
  27100. }
  27101. }
  27102. return null;
  27103. };
  27104. /**
  27105. * Gets a geometry using its ID
  27106. * @param id defines the geometry's id
  27107. * @return the geometry or null if none found.
  27108. */
  27109. Scene.prototype.getGeometryByID = function (id) {
  27110. for (var index = 0; index < this.geometries.length; index++) {
  27111. if (this.geometries[index].id === id) {
  27112. return this.geometries[index];
  27113. }
  27114. }
  27115. return null;
  27116. };
  27117. /**
  27118. * Add a new geometry to this scene
  27119. * @param geometry defines the geometry to be added to the scene.
  27120. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27121. * @return a boolean defining if the geometry was added or not
  27122. */
  27123. Scene.prototype.pushGeometry = function (geometry, force) {
  27124. if (!force && this.getGeometryByID(geometry.id)) {
  27125. return false;
  27126. }
  27127. this.geometries.push(geometry);
  27128. //notify the collision coordinator
  27129. if (this.collisionCoordinator) {
  27130. this.collisionCoordinator.onGeometryAdded(geometry);
  27131. }
  27132. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27133. return true;
  27134. };
  27135. /**
  27136. * Removes an existing geometry
  27137. * @param geometry defines the geometry to be removed from the scene
  27138. * @return a boolean defining if the geometry was removed or not
  27139. */
  27140. Scene.prototype.removeGeometry = function (geometry) {
  27141. var index = this.geometries.indexOf(geometry);
  27142. if (index > -1) {
  27143. this.geometries.splice(index, 1);
  27144. //notify the collision coordinator
  27145. if (this.collisionCoordinator) {
  27146. this.collisionCoordinator.onGeometryDeleted(geometry);
  27147. }
  27148. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27149. return true;
  27150. }
  27151. return false;
  27152. };
  27153. /**
  27154. * Gets the list of geometries attached to the scene
  27155. * @returns an array of Geometry
  27156. */
  27157. Scene.prototype.getGeometries = function () {
  27158. return this.geometries;
  27159. };
  27160. /**
  27161. * Gets the first added mesh found of a given ID
  27162. * @param id defines the id to search for
  27163. * @return the mesh found or null if not found at all
  27164. */
  27165. Scene.prototype.getMeshByID = function (id) {
  27166. for (var index = 0; index < this.meshes.length; index++) {
  27167. if (this.meshes[index].id === id) {
  27168. return this.meshes[index];
  27169. }
  27170. }
  27171. return null;
  27172. };
  27173. /**
  27174. * Gets a list of meshes using their id
  27175. * @param id defines the id to search for
  27176. * @returns a list of meshes
  27177. */
  27178. Scene.prototype.getMeshesByID = function (id) {
  27179. return this.meshes.filter(function (m) {
  27180. return m.id === id;
  27181. });
  27182. };
  27183. /**
  27184. * Gets the first added transform node found of a given ID
  27185. * @param id defines the id to search for
  27186. * @return the found transform node or null if not found at all.
  27187. */
  27188. Scene.prototype.getTransformNodeByID = function (id) {
  27189. for (var index = 0; index < this.transformNodes.length; index++) {
  27190. if (this.transformNodes[index].id === id) {
  27191. return this.transformNodes[index];
  27192. }
  27193. }
  27194. return null;
  27195. };
  27196. /**
  27197. * Gets a list of transform nodes using their id
  27198. * @param id defines the id to search for
  27199. * @returns a list of transform nodes
  27200. */
  27201. Scene.prototype.getTransformNodesByID = function (id) {
  27202. return this.transformNodes.filter(function (m) {
  27203. return m.id === id;
  27204. });
  27205. };
  27206. /**
  27207. * Gets a mesh with its auto-generated unique id
  27208. * @param uniqueId defines the unique id to search for
  27209. * @return the found mesh or null if not found at all.
  27210. */
  27211. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27212. for (var index = 0; index < this.meshes.length; index++) {
  27213. if (this.meshes[index].uniqueId === uniqueId) {
  27214. return this.meshes[index];
  27215. }
  27216. }
  27217. return null;
  27218. };
  27219. /**
  27220. * Gets a the last added mesh using a given id
  27221. * @param id defines the id to search for
  27222. * @return the found mesh or null if not found at all.
  27223. */
  27224. Scene.prototype.getLastMeshByID = function (id) {
  27225. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27226. if (this.meshes[index].id === id) {
  27227. return this.meshes[index];
  27228. }
  27229. }
  27230. return null;
  27231. };
  27232. /**
  27233. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27234. * @param id defines the id to search for
  27235. * @return the found node or null if not found at all
  27236. */
  27237. Scene.prototype.getLastEntryByID = function (id) {
  27238. var index;
  27239. for (index = this.meshes.length - 1; index >= 0; index--) {
  27240. if (this.meshes[index].id === id) {
  27241. return this.meshes[index];
  27242. }
  27243. }
  27244. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27245. if (this.transformNodes[index].id === id) {
  27246. return this.transformNodes[index];
  27247. }
  27248. }
  27249. for (index = this.cameras.length - 1; index >= 0; index--) {
  27250. if (this.cameras[index].id === id) {
  27251. return this.cameras[index];
  27252. }
  27253. }
  27254. for (index = this.lights.length - 1; index >= 0; index--) {
  27255. if (this.lights[index].id === id) {
  27256. return this.lights[index];
  27257. }
  27258. }
  27259. return null;
  27260. };
  27261. /**
  27262. * Gets a node (Mesh, Camera, Light) using a given id
  27263. * @param id defines the id to search for
  27264. * @return the found node or null if not found at all
  27265. */
  27266. Scene.prototype.getNodeByID = function (id) {
  27267. var mesh = this.getMeshByID(id);
  27268. if (mesh) {
  27269. return mesh;
  27270. }
  27271. var light = this.getLightByID(id);
  27272. if (light) {
  27273. return light;
  27274. }
  27275. var camera = this.getCameraByID(id);
  27276. if (camera) {
  27277. return camera;
  27278. }
  27279. var bone = this.getBoneByID(id);
  27280. return bone;
  27281. };
  27282. /**
  27283. * Gets a node (Mesh, Camera, Light) using a given name
  27284. * @param name defines the name to search for
  27285. * @return the found node or null if not found at all.
  27286. */
  27287. Scene.prototype.getNodeByName = function (name) {
  27288. var mesh = this.getMeshByName(name);
  27289. if (mesh) {
  27290. return mesh;
  27291. }
  27292. var light = this.getLightByName(name);
  27293. if (light) {
  27294. return light;
  27295. }
  27296. var camera = this.getCameraByName(name);
  27297. if (camera) {
  27298. return camera;
  27299. }
  27300. var bone = this.getBoneByName(name);
  27301. return bone;
  27302. };
  27303. /**
  27304. * Gets a mesh using a given name
  27305. * @param name defines the name to search for
  27306. * @return the found mesh or null if not found at all.
  27307. */
  27308. Scene.prototype.getMeshByName = function (name) {
  27309. for (var index = 0; index < this.meshes.length; index++) {
  27310. if (this.meshes[index].name === name) {
  27311. return this.meshes[index];
  27312. }
  27313. }
  27314. return null;
  27315. };
  27316. /**
  27317. * Gets a transform node using a given name
  27318. * @param name defines the name to search for
  27319. * @return the found transform node or null if not found at all.
  27320. */
  27321. Scene.prototype.getTransformNodeByName = function (name) {
  27322. for (var index = 0; index < this.transformNodes.length; index++) {
  27323. if (this.transformNodes[index].name === name) {
  27324. return this.transformNodes[index];
  27325. }
  27326. }
  27327. return null;
  27328. };
  27329. /**
  27330. * Gets a sound using a given name
  27331. * @param name defines the name to search for
  27332. * @return the found sound or null if not found at all.
  27333. */
  27334. Scene.prototype.getSoundByName = function (name) {
  27335. var index;
  27336. if (BABYLON.AudioEngine) {
  27337. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27338. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27339. return this.mainSoundTrack.soundCollection[index];
  27340. }
  27341. }
  27342. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27343. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27344. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27345. return this.soundTracks[sdIndex].soundCollection[index];
  27346. }
  27347. }
  27348. }
  27349. }
  27350. return null;
  27351. };
  27352. /**
  27353. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27354. * @param id defines the id to search for
  27355. * @return the found skeleton or null if not found at all.
  27356. */
  27357. Scene.prototype.getLastSkeletonByID = function (id) {
  27358. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27359. if (this.skeletons[index].id === id) {
  27360. return this.skeletons[index];
  27361. }
  27362. }
  27363. return null;
  27364. };
  27365. /**
  27366. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27367. * @param id defines the id to search for
  27368. * @return the found skeleton or null if not found at all.
  27369. */
  27370. Scene.prototype.getSkeletonById = function (id) {
  27371. for (var index = 0; index < this.skeletons.length; index++) {
  27372. if (this.skeletons[index].id === id) {
  27373. return this.skeletons[index];
  27374. }
  27375. }
  27376. return null;
  27377. };
  27378. /**
  27379. * Gets a skeleton using a given name
  27380. * @param name defines the name to search for
  27381. * @return the found skeleton or null if not found at all.
  27382. */
  27383. Scene.prototype.getSkeletonByName = function (name) {
  27384. for (var index = 0; index < this.skeletons.length; index++) {
  27385. if (this.skeletons[index].name === name) {
  27386. return this.skeletons[index];
  27387. }
  27388. }
  27389. return null;
  27390. };
  27391. /**
  27392. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27393. * @param id defines the id to search for
  27394. * @return the found morph target manager or null if not found at all.
  27395. */
  27396. Scene.prototype.getMorphTargetManagerById = function (id) {
  27397. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27398. if (this.morphTargetManagers[index].uniqueId === id) {
  27399. return this.morphTargetManagers[index];
  27400. }
  27401. }
  27402. return null;
  27403. };
  27404. /**
  27405. * Gets a boolean indicating if the given mesh is active
  27406. * @param mesh defines the mesh to look for
  27407. * @returns true if the mesh is in the active list
  27408. */
  27409. Scene.prototype.isActiveMesh = function (mesh) {
  27410. return (this._activeMeshes.indexOf(mesh) !== -1);
  27411. };
  27412. Object.defineProperty(Scene.prototype, "uid", {
  27413. /**
  27414. * Return a unique id as a string which can serve as an identifier for the scene
  27415. */
  27416. get: function () {
  27417. if (!this._uid) {
  27418. this._uid = BABYLON.Tools.RandomId();
  27419. }
  27420. return this._uid;
  27421. },
  27422. enumerable: true,
  27423. configurable: true
  27424. });
  27425. /**
  27426. * Add an externaly attached data from its key.
  27427. * This method call will fail and return false, if such key already exists.
  27428. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27429. * @param key the unique key that identifies the data
  27430. * @param data the data object to associate to the key for this Engine instance
  27431. * @return true if no such key were already present and the data was added successfully, false otherwise
  27432. */
  27433. Scene.prototype.addExternalData = function (key, data) {
  27434. if (!this._externalData) {
  27435. this._externalData = new BABYLON.StringDictionary();
  27436. }
  27437. return this._externalData.add(key, data);
  27438. };
  27439. /**
  27440. * Get an externaly attached data from its key
  27441. * @param key the unique key that identifies the data
  27442. * @return the associated data, if present (can be null), or undefined if not present
  27443. */
  27444. Scene.prototype.getExternalData = function (key) {
  27445. if (!this._externalData) {
  27446. return null;
  27447. }
  27448. return this._externalData.get(key);
  27449. };
  27450. /**
  27451. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27452. * @param key the unique key that identifies the data
  27453. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27454. * @return the associated data, can be null if the factory returned null.
  27455. */
  27456. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27457. if (!this._externalData) {
  27458. this._externalData = new BABYLON.StringDictionary();
  27459. }
  27460. return this._externalData.getOrAddWithFactory(key, factory);
  27461. };
  27462. /**
  27463. * Remove an externaly attached data from the Engine instance
  27464. * @param key the unique key that identifies the data
  27465. * @return true if the data was successfully removed, false if it doesn't exist
  27466. */
  27467. Scene.prototype.removeExternalData = function (key) {
  27468. return this._externalData.remove(key);
  27469. };
  27470. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27471. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27472. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27473. var step = _a[_i];
  27474. step.action(mesh, subMesh);
  27475. }
  27476. var material = subMesh.getMaterial();
  27477. if (material !== null && material !== undefined) {
  27478. // Render targets
  27479. if (material.getRenderTargetTextures !== undefined) {
  27480. if (this._processedMaterials.indexOf(material) === -1) {
  27481. this._processedMaterials.push(material);
  27482. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27483. }
  27484. }
  27485. // Dispatch
  27486. this._activeIndices.addCount(subMesh.indexCount, false);
  27487. this._renderingManager.dispatch(subMesh, mesh, material);
  27488. }
  27489. }
  27490. };
  27491. /**
  27492. * Clear the processed materials smart array preventing retention point in material dispose.
  27493. */
  27494. Scene.prototype.freeProcessedMaterials = function () {
  27495. this._processedMaterials.dispose();
  27496. };
  27497. /**
  27498. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27499. */
  27500. Scene.prototype.freeActiveMeshes = function () {
  27501. this._activeMeshes.dispose();
  27502. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27503. this.activeCamera._activeMeshes.dispose();
  27504. }
  27505. if (this.activeCameras) {
  27506. for (var i = 0; i < this.activeCameras.length; i++) {
  27507. var activeCamera = this.activeCameras[i];
  27508. if (activeCamera && activeCamera._activeMeshes) {
  27509. activeCamera._activeMeshes.dispose();
  27510. }
  27511. }
  27512. }
  27513. };
  27514. /**
  27515. * Clear the info related to rendering groups preventing retention points during dispose.
  27516. */
  27517. Scene.prototype.freeRenderingGroups = function () {
  27518. if (this._renderingManager) {
  27519. this._renderingManager.freeRenderingGroups();
  27520. }
  27521. if (this.textures) {
  27522. for (var i = 0; i < this.textures.length; i++) {
  27523. var texture = this.textures[i];
  27524. if (texture && texture.renderList) {
  27525. texture.freeRenderingGroups();
  27526. }
  27527. }
  27528. }
  27529. };
  27530. /** @hidden */
  27531. Scene.prototype._isInIntermediateRendering = function () {
  27532. return this._intermediateRendering;
  27533. };
  27534. /**
  27535. * Defines the current active mesh candidate provider
  27536. * @param provider defines the provider to use
  27537. */
  27538. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27539. this._activeMeshCandidateProvider = provider;
  27540. };
  27541. /**
  27542. * Gets the current active mesh candidate provider
  27543. * @returns the current active mesh candidate provider
  27544. */
  27545. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27546. return this._activeMeshCandidateProvider;
  27547. };
  27548. /**
  27549. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27550. * @returns the current scene
  27551. */
  27552. Scene.prototype.freezeActiveMeshes = function () {
  27553. if (!this.activeCamera) {
  27554. return this;
  27555. }
  27556. if (!this._frustumPlanes) {
  27557. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27558. }
  27559. this._evaluateActiveMeshes();
  27560. this._activeMeshesFrozen = true;
  27561. return this;
  27562. };
  27563. /**
  27564. * Use this function to restart evaluating active meshes on every frame
  27565. * @returns the current scene
  27566. */
  27567. Scene.prototype.unfreezeActiveMeshes = function () {
  27568. this._activeMeshesFrozen = false;
  27569. return this;
  27570. };
  27571. Scene.prototype._evaluateActiveMeshes = function () {
  27572. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27573. return;
  27574. }
  27575. if (!this.activeCamera) {
  27576. return;
  27577. }
  27578. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27579. this.activeCamera._activeMeshes.reset();
  27580. this._activeMeshes.reset();
  27581. this._renderingManager.reset();
  27582. this._processedMaterials.reset();
  27583. this._activeParticleSystems.reset();
  27584. this._activeSkeletons.reset();
  27585. this._softwareSkinnedMeshes.reset();
  27586. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27587. var step = _a[_i];
  27588. step.action();
  27589. }
  27590. // Meshes
  27591. var meshes;
  27592. var len;
  27593. var checkIsEnabled = true;
  27594. // Determine mesh candidates
  27595. if (this._activeMeshCandidateProvider !== undefined) {
  27596. // Use _activeMeshCandidateProvider
  27597. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27598. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27599. if (meshes !== undefined) {
  27600. len = meshes.length;
  27601. }
  27602. else {
  27603. len = 0;
  27604. }
  27605. }
  27606. else if (this._selectionOctree !== undefined) {
  27607. // Octree
  27608. var selection = this._selectionOctree.select(this._frustumPlanes);
  27609. meshes = selection.data;
  27610. len = selection.length;
  27611. }
  27612. else {
  27613. // Full scene traversal
  27614. len = this.meshes.length;
  27615. meshes = this.meshes;
  27616. }
  27617. // Check each mesh
  27618. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27619. mesh = meshes[meshIndex];
  27620. if (mesh.isBlocked) {
  27621. continue;
  27622. }
  27623. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27624. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27625. continue;
  27626. }
  27627. mesh.computeWorldMatrix();
  27628. // Intersections
  27629. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27630. this._meshesForIntersections.pushNoDuplicate(mesh);
  27631. }
  27632. // Switch to current LOD
  27633. meshLOD = mesh.getLOD(this.activeCamera);
  27634. if (meshLOD === undefined || meshLOD === null) {
  27635. continue;
  27636. }
  27637. mesh._preActivate();
  27638. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27639. this._activeMeshes.push(mesh);
  27640. this.activeCamera._activeMeshes.push(mesh);
  27641. mesh._activate(this._renderId);
  27642. if (meshLOD !== mesh) {
  27643. meshLOD._activate(this._renderId);
  27644. }
  27645. this._activeMesh(mesh, meshLOD);
  27646. }
  27647. }
  27648. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27649. // Particle systems
  27650. if (this.particlesEnabled) {
  27651. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27652. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27653. var particleSystem = this.particleSystems[particleIndex];
  27654. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27655. continue;
  27656. }
  27657. var emitter = particleSystem.emitter;
  27658. if (!emitter.position || emitter.isEnabled()) {
  27659. this._activeParticleSystems.push(particleSystem);
  27660. particleSystem.animate();
  27661. this._renderingManager.dispatchParticles(particleSystem);
  27662. }
  27663. }
  27664. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27665. }
  27666. };
  27667. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27668. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27669. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27670. mesh.skeleton.prepare();
  27671. }
  27672. if (!mesh.computeBonesUsingShaders) {
  27673. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27674. }
  27675. }
  27676. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27677. var step = _a[_i];
  27678. step.action(sourceMesh, mesh);
  27679. }
  27680. if (mesh !== undefined && mesh !== null
  27681. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27682. // Submeshes Octrees
  27683. var len;
  27684. var subMeshes;
  27685. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27686. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27687. len = intersections.length;
  27688. subMeshes = intersections.data;
  27689. }
  27690. else {
  27691. subMeshes = mesh.subMeshes;
  27692. len = subMeshes.length;
  27693. }
  27694. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27695. subMesh = subMeshes[subIndex];
  27696. this._evaluateSubMesh(subMesh, mesh);
  27697. }
  27698. }
  27699. };
  27700. /**
  27701. * Update the transform matrix to update from the current active camera
  27702. * @param force defines a boolean used to force the update even if cache is up to date
  27703. */
  27704. Scene.prototype.updateTransformMatrix = function (force) {
  27705. if (!this.activeCamera) {
  27706. return;
  27707. }
  27708. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27709. };
  27710. /**
  27711. * 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)
  27712. * @param alternateCamera defines the camera to use
  27713. */
  27714. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27715. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27716. };
  27717. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27718. if (camera && camera._skipRendering) {
  27719. return;
  27720. }
  27721. var engine = this._engine;
  27722. this.activeCamera = camera;
  27723. if (!this.activeCamera)
  27724. throw new Error("Active camera not set");
  27725. // Viewport
  27726. engine.setViewport(this.activeCamera.viewport);
  27727. // Camera
  27728. this.resetCachedMaterial();
  27729. this._renderId++;
  27730. this.updateTransformMatrix();
  27731. if (camera._alternateCamera) {
  27732. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27733. this._alternateRendering = true;
  27734. }
  27735. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27736. // Meshes
  27737. this._evaluateActiveMeshes();
  27738. // Software skinning
  27739. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27740. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27741. mesh.applySkeleton(mesh.skeleton);
  27742. }
  27743. // Render targets
  27744. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27745. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27746. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27747. }
  27748. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27749. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27750. }
  27751. if (this.renderTargetsEnabled) {
  27752. this._intermediateRendering = true;
  27753. if (this._renderTargets.length > 0) {
  27754. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27755. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27756. var renderTarget = this._renderTargets.data[renderIndex];
  27757. if (renderTarget._shouldRender()) {
  27758. this._renderId++;
  27759. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27760. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27761. }
  27762. }
  27763. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27764. this._renderId++;
  27765. }
  27766. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27767. var step = _a[_i];
  27768. step.action(this.activeCamera);
  27769. }
  27770. this._intermediateRendering = false;
  27771. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27772. }
  27773. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27774. // Prepare Frame
  27775. if (this.postProcessManager) {
  27776. this.postProcessManager._prepareFrame();
  27777. }
  27778. // Before Camera Draw
  27779. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27780. var step = _c[_b];
  27781. step.action(this.activeCamera);
  27782. }
  27783. // Render
  27784. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27785. this._renderingManager.render(null, null, true, true);
  27786. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27787. // After Camera Draw
  27788. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27789. var step = _e[_d];
  27790. step.action(this.activeCamera);
  27791. }
  27792. // Finalize frame
  27793. if (this.postProcessManager) {
  27794. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27795. }
  27796. // Reset some special arrays
  27797. this._renderTargets.reset();
  27798. this._alternateRendering = false;
  27799. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27800. };
  27801. Scene.prototype._processSubCameras = function (camera) {
  27802. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27803. this._renderForCamera(camera);
  27804. return;
  27805. }
  27806. // rig cameras
  27807. for (var index = 0; index < camera._rigCameras.length; index++) {
  27808. this._renderForCamera(camera._rigCameras[index], camera);
  27809. }
  27810. this.activeCamera = camera;
  27811. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27812. };
  27813. Scene.prototype._checkIntersections = function () {
  27814. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27815. var sourceMesh = this._meshesForIntersections.data[index];
  27816. if (!sourceMesh.actionManager) {
  27817. continue;
  27818. }
  27819. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27820. var action = sourceMesh.actionManager.actions[actionIndex];
  27821. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27822. var parameters = action.getTriggerParameter();
  27823. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27824. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27825. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27826. if (areIntersecting && currentIntersectionInProgress === -1) {
  27827. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27828. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27829. sourceMesh._intersectionsInProgress.push(otherMesh);
  27830. }
  27831. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27832. sourceMesh._intersectionsInProgress.push(otherMesh);
  27833. }
  27834. }
  27835. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27836. //They intersected, and now they don't.
  27837. //is this trigger an exit trigger? execute an event.
  27838. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27839. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27840. }
  27841. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27842. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27843. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27844. return otherMesh === parameterMesh;
  27845. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27846. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27847. }
  27848. }
  27849. }
  27850. }
  27851. }
  27852. };
  27853. /**
  27854. * Render the scene
  27855. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27856. */
  27857. Scene.prototype.render = function (updateCameras) {
  27858. if (updateCameras === void 0) { updateCameras = true; }
  27859. if (this.isDisposed) {
  27860. return;
  27861. }
  27862. // Register components that have been associated lately to the scene.
  27863. this._registerTransientComponents();
  27864. this._activeParticles.fetchNewFrame();
  27865. this._totalVertices.fetchNewFrame();
  27866. this._activeIndices.fetchNewFrame();
  27867. this._activeBones.fetchNewFrame();
  27868. this._meshesForIntersections.reset();
  27869. this.resetCachedMaterial();
  27870. this.onBeforeAnimationsObservable.notifyObservers(this);
  27871. // Actions
  27872. if (this.actionManager) {
  27873. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27874. }
  27875. //Simplification Queue
  27876. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27877. this.simplificationQueue.executeNext();
  27878. }
  27879. if (this._engine.isDeterministicLockStep()) {
  27880. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27881. var defaultFPS = (60.0 / 1000.0);
  27882. var defaultFrameTime = 1000 / 60; // frame time in MS
  27883. if (this._physicsEngine) {
  27884. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27885. }
  27886. var stepsTaken = 0;
  27887. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27888. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27889. internalSteps = Math.min(internalSteps, maxSubSteps);
  27890. do {
  27891. this.onBeforeStepObservable.notifyObservers(this);
  27892. // Animations
  27893. this._animationRatio = defaultFrameTime * defaultFPS;
  27894. this._animate();
  27895. this.onAfterAnimationsObservable.notifyObservers(this);
  27896. // Physics
  27897. if (this._physicsEngine) {
  27898. this.onBeforePhysicsObservable.notifyObservers(this);
  27899. this._physicsEngine._step(defaultFrameTime / 1000);
  27900. this.onAfterPhysicsObservable.notifyObservers(this);
  27901. }
  27902. this.onAfterStepObservable.notifyObservers(this);
  27903. this._currentStepId++;
  27904. stepsTaken++;
  27905. deltaTime -= defaultFrameTime;
  27906. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27907. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27908. }
  27909. else {
  27910. // Animations
  27911. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27912. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27913. this._animate();
  27914. this.onAfterAnimationsObservable.notifyObservers(this);
  27915. // Physics
  27916. if (this._physicsEngine) {
  27917. this.onBeforePhysicsObservable.notifyObservers(this);
  27918. this._physicsEngine._step(deltaTime / 1000.0);
  27919. this.onAfterPhysicsObservable.notifyObservers(this);
  27920. }
  27921. }
  27922. // Before camera update steps
  27923. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27924. var step = _a[_i];
  27925. step.action();
  27926. }
  27927. // Update Cameras
  27928. if (updateCameras) {
  27929. if (this.activeCameras.length > 0) {
  27930. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27931. var camera = this.activeCameras[cameraIndex];
  27932. camera.update();
  27933. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27934. // rig cameras
  27935. for (var index = 0; index < camera._rigCameras.length; index++) {
  27936. camera._rigCameras[index].update();
  27937. }
  27938. }
  27939. }
  27940. }
  27941. else if (this.activeCamera) {
  27942. this.activeCamera.update();
  27943. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27944. // rig cameras
  27945. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27946. this.activeCamera._rigCameras[index].update();
  27947. }
  27948. }
  27949. }
  27950. }
  27951. // Before render
  27952. this.onBeforeRenderObservable.notifyObservers(this);
  27953. // Customs render targets
  27954. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27955. var engine = this.getEngine();
  27956. var currentActiveCamera = this.activeCamera;
  27957. if (this.renderTargetsEnabled) {
  27958. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27959. this._intermediateRendering = true;
  27960. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27961. var renderTarget = this.customRenderTargets[customIndex];
  27962. if (renderTarget._shouldRender()) {
  27963. this._renderId++;
  27964. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27965. if (!this.activeCamera)
  27966. throw new Error("Active camera not set");
  27967. // Viewport
  27968. engine.setViewport(this.activeCamera.viewport);
  27969. // Camera
  27970. this.updateTransformMatrix();
  27971. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27972. }
  27973. }
  27974. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27975. this._intermediateRendering = false;
  27976. this._renderId++;
  27977. }
  27978. // Restore back buffer
  27979. if (this.customRenderTargets.length > 0) {
  27980. engine.restoreDefaultFramebuffer();
  27981. }
  27982. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27983. this.activeCamera = currentActiveCamera;
  27984. // Procedural textures
  27985. if (this.proceduralTexturesEnabled) {
  27986. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27987. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27988. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27989. if (proceduralTexture._shouldRender()) {
  27990. proceduralTexture.render();
  27991. }
  27992. }
  27993. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27994. }
  27995. // Clear
  27996. if (this.autoClearDepthAndStencil || this.autoClear) {
  27997. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27998. }
  27999. // Shadows
  28000. if (this.shadowsEnabled) {
  28001. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28002. var light = this.lights[lightIndex];
  28003. var shadowGenerator = light.getShadowGenerator();
  28004. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28005. var shadowMap = (shadowGenerator.getShadowMap());
  28006. if (this.textures.indexOf(shadowMap) !== -1) {
  28007. this._renderTargets.push(shadowMap);
  28008. }
  28009. }
  28010. }
  28011. }
  28012. // Depth renderer
  28013. for (var key in this._depthRenderer) {
  28014. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28015. }
  28016. // Geometry renderer
  28017. if (this._geometryBufferRenderer) {
  28018. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28019. }
  28020. // RenderPipeline
  28021. if (this._postProcessRenderPipelineManager) {
  28022. this._postProcessRenderPipelineManager.update();
  28023. }
  28024. // Multi-cameras?
  28025. if (this.activeCameras.length > 0) {
  28026. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28027. if (cameraIndex > 0) {
  28028. this._engine.clear(null, false, true, true);
  28029. }
  28030. this._processSubCameras(this.activeCameras[cameraIndex]);
  28031. }
  28032. }
  28033. else {
  28034. if (!this.activeCamera) {
  28035. throw new Error("No camera defined");
  28036. }
  28037. this._processSubCameras(this.activeCamera);
  28038. }
  28039. // Intersection checks
  28040. this._checkIntersections();
  28041. // Update the audio listener attached to the camera
  28042. if (BABYLON.AudioEngine) {
  28043. this._updateAudioParameters();
  28044. }
  28045. // After render
  28046. if (this.afterRender) {
  28047. this.afterRender();
  28048. }
  28049. this.onAfterRenderObservable.notifyObservers(this);
  28050. // Cleaning
  28051. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28052. var data = this._toBeDisposed.data[index];
  28053. if (data) {
  28054. data.dispose();
  28055. }
  28056. this._toBeDisposed[index] = null;
  28057. }
  28058. this._toBeDisposed.reset();
  28059. if (this.dumpNextRenderTargets) {
  28060. this.dumpNextRenderTargets = false;
  28061. }
  28062. this._activeBones.addCount(0, true);
  28063. this._activeIndices.addCount(0, true);
  28064. this._activeParticles.addCount(0, true);
  28065. };
  28066. Scene.prototype._updateAudioParameters = function () {
  28067. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28068. return;
  28069. }
  28070. var listeningCamera;
  28071. var audioEngine = BABYLON.Engine.audioEngine;
  28072. if (this.activeCameras.length > 0) {
  28073. listeningCamera = this.activeCameras[0];
  28074. }
  28075. else {
  28076. listeningCamera = this.activeCamera;
  28077. }
  28078. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28079. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28080. // for VR cameras
  28081. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28082. listeningCamera = listeningCamera.rigCameras[0];
  28083. }
  28084. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28085. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28086. cameraDirection.normalize();
  28087. // To avoid some errors on GearVR
  28088. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28089. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28090. }
  28091. var i;
  28092. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28093. var sound = this.mainSoundTrack.soundCollection[i];
  28094. if (sound.useCustomAttenuation) {
  28095. sound.updateDistanceFromListener();
  28096. }
  28097. }
  28098. for (i = 0; i < this.soundTracks.length; i++) {
  28099. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28100. sound = this.soundTracks[i].soundCollection[j];
  28101. if (sound.useCustomAttenuation) {
  28102. sound.updateDistanceFromListener();
  28103. }
  28104. }
  28105. }
  28106. }
  28107. };
  28108. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28109. // Audio
  28110. /**
  28111. * Gets or sets if audio support is enabled
  28112. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28113. */
  28114. get: function () {
  28115. return this._audioEnabled;
  28116. },
  28117. set: function (value) {
  28118. this._audioEnabled = value;
  28119. if (BABYLON.AudioEngine) {
  28120. if (this._audioEnabled) {
  28121. this._enableAudio();
  28122. }
  28123. else {
  28124. this._disableAudio();
  28125. }
  28126. }
  28127. },
  28128. enumerable: true,
  28129. configurable: true
  28130. });
  28131. Scene.prototype._disableAudio = function () {
  28132. var i;
  28133. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28134. this.mainSoundTrack.soundCollection[i].pause();
  28135. }
  28136. for (i = 0; i < this.soundTracks.length; i++) {
  28137. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28138. this.soundTracks[i].soundCollection[j].pause();
  28139. }
  28140. }
  28141. };
  28142. Scene.prototype._enableAudio = function () {
  28143. var i;
  28144. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28145. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28146. this.mainSoundTrack.soundCollection[i].play();
  28147. }
  28148. }
  28149. for (i = 0; i < this.soundTracks.length; i++) {
  28150. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28151. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28152. this.soundTracks[i].soundCollection[j].play();
  28153. }
  28154. }
  28155. }
  28156. };
  28157. Object.defineProperty(Scene.prototype, "headphone", {
  28158. /**
  28159. * Gets or sets if audio will be output to headphones
  28160. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28161. */
  28162. get: function () {
  28163. return this._headphone;
  28164. },
  28165. set: function (value) {
  28166. this._headphone = value;
  28167. if (BABYLON.AudioEngine) {
  28168. if (this._headphone) {
  28169. this._switchAudioModeForHeadphones();
  28170. }
  28171. else {
  28172. this._switchAudioModeForNormalSpeakers();
  28173. }
  28174. }
  28175. },
  28176. enumerable: true,
  28177. configurable: true
  28178. });
  28179. Scene.prototype._switchAudioModeForHeadphones = function () {
  28180. this.mainSoundTrack.switchPanningModelToHRTF();
  28181. for (var i = 0; i < this.soundTracks.length; i++) {
  28182. this.soundTracks[i].switchPanningModelToHRTF();
  28183. }
  28184. };
  28185. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28186. this.mainSoundTrack.switchPanningModelToEqualPower();
  28187. for (var i = 0; i < this.soundTracks.length; i++) {
  28188. this.soundTracks[i].switchPanningModelToEqualPower();
  28189. }
  28190. };
  28191. /**
  28192. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28193. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28194. * @returns the created depth renderer
  28195. */
  28196. Scene.prototype.enableDepthRenderer = function (camera) {
  28197. camera = camera || this.activeCamera;
  28198. if (!camera) {
  28199. throw "No camera available to enable depth renderer";
  28200. }
  28201. if (!this._depthRenderer[camera.id]) {
  28202. var textureType = 0;
  28203. if (this._engine.getCaps().textureHalfFloatRender) {
  28204. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28205. }
  28206. else if (this._engine.getCaps().textureFloatRender) {
  28207. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28208. }
  28209. else {
  28210. throw "Depth renderer does not support int texture type";
  28211. }
  28212. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28213. }
  28214. return this._depthRenderer[camera.id];
  28215. };
  28216. /**
  28217. * Disables a depth renderer for a given camera
  28218. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28219. */
  28220. Scene.prototype.disableDepthRenderer = function (camera) {
  28221. camera = camera || this.activeCamera;
  28222. if (!camera || !this._depthRenderer[camera.id]) {
  28223. return;
  28224. }
  28225. this._depthRenderer[camera.id].dispose();
  28226. delete this._depthRenderer[camera.id];
  28227. };
  28228. /**
  28229. * Enables a GeometryBufferRender and associates it with the scene
  28230. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28231. * @returns the GeometryBufferRenderer
  28232. */
  28233. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28234. if (ratio === void 0) { ratio = 1; }
  28235. if (this._geometryBufferRenderer) {
  28236. return this._geometryBufferRenderer;
  28237. }
  28238. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28239. if (!this._geometryBufferRenderer.isSupported) {
  28240. this._geometryBufferRenderer = null;
  28241. }
  28242. return this._geometryBufferRenderer;
  28243. };
  28244. /**
  28245. * Disables the GeometryBufferRender associated with the scene
  28246. */
  28247. Scene.prototype.disableGeometryBufferRenderer = function () {
  28248. if (!this._geometryBufferRenderer) {
  28249. return;
  28250. }
  28251. this._geometryBufferRenderer.dispose();
  28252. this._geometryBufferRenderer = null;
  28253. };
  28254. /**
  28255. * Freeze all materials
  28256. * A frozen material will not be updatable but should be faster to render
  28257. */
  28258. Scene.prototype.freezeMaterials = function () {
  28259. for (var i = 0; i < this.materials.length; i++) {
  28260. this.materials[i].freeze();
  28261. }
  28262. };
  28263. /**
  28264. * Unfreeze all materials
  28265. * A frozen material will not be updatable but should be faster to render
  28266. */
  28267. Scene.prototype.unfreezeMaterials = function () {
  28268. for (var i = 0; i < this.materials.length; i++) {
  28269. this.materials[i].unfreeze();
  28270. }
  28271. };
  28272. /**
  28273. * Releases all held ressources
  28274. */
  28275. Scene.prototype.dispose = function () {
  28276. this.beforeRender = null;
  28277. this.afterRender = null;
  28278. this.skeletons = [];
  28279. this.morphTargetManagers = [];
  28280. this._transientComponents = [];
  28281. this._isReadyForMeshStage.clear();
  28282. this._beforeEvaluateActiveMeshStage.clear();
  28283. this._evaluateSubMeshStage.clear();
  28284. this._activeMeshStage.clear();
  28285. this._cameraDrawRenderTargetStage.clear();
  28286. this._beforeCameraDrawStage.clear();
  28287. this._beforeRenderingGroupDrawStage.clear();
  28288. this._afterRenderingGroupDrawStage.clear();
  28289. this._afterCameraDrawStage.clear();
  28290. this._beforeCameraUpdateStage.clear();
  28291. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28292. var component = _a[_i];
  28293. component.dispose();
  28294. }
  28295. this.importedMeshesFiles = new Array();
  28296. this.stopAllAnimations();
  28297. this.resetCachedMaterial();
  28298. for (var key in this._depthRenderer) {
  28299. this._depthRenderer[key].dispose();
  28300. }
  28301. // Smart arrays
  28302. if (this.activeCamera) {
  28303. this.activeCamera._activeMeshes.dispose();
  28304. this.activeCamera = null;
  28305. }
  28306. this._activeMeshes.dispose();
  28307. this._renderingManager.dispose();
  28308. this._processedMaterials.dispose();
  28309. this._activeParticleSystems.dispose();
  28310. this._activeSkeletons.dispose();
  28311. this._softwareSkinnedMeshes.dispose();
  28312. this._renderTargets.dispose();
  28313. this._registeredForLateAnimationBindings.dispose();
  28314. this._meshesForIntersections.dispose();
  28315. this._toBeDisposed.dispose();
  28316. // Abort active requests
  28317. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28318. var request = _c[_b];
  28319. request.abort();
  28320. }
  28321. // Debug layer
  28322. if (this._debugLayer) {
  28323. this._debugLayer.hide();
  28324. }
  28325. // Events
  28326. this.onDisposeObservable.notifyObservers(this);
  28327. this.onDisposeObservable.clear();
  28328. this.onBeforeRenderObservable.clear();
  28329. this.onAfterRenderObservable.clear();
  28330. this.onBeforeRenderTargetsRenderObservable.clear();
  28331. this.onAfterRenderTargetsRenderObservable.clear();
  28332. this.onAfterStepObservable.clear();
  28333. this.onBeforeStepObservable.clear();
  28334. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28335. this.onAfterActiveMeshesEvaluationObservable.clear();
  28336. this.onBeforeParticlesRenderingObservable.clear();
  28337. this.onAfterParticlesRenderingObservable.clear();
  28338. this.onBeforeSpritesRenderingObservable.clear();
  28339. this.onAfterSpritesRenderingObservable.clear();
  28340. this.onBeforeDrawPhaseObservable.clear();
  28341. this.onAfterDrawPhaseObservable.clear();
  28342. this.onBeforePhysicsObservable.clear();
  28343. this.onAfterPhysicsObservable.clear();
  28344. this.onBeforeAnimationsObservable.clear();
  28345. this.onAfterAnimationsObservable.clear();
  28346. this.onDataLoadedObservable.clear();
  28347. this.detachControl();
  28348. // Release sounds & sounds tracks
  28349. if (BABYLON.AudioEngine) {
  28350. this.disposeSounds();
  28351. }
  28352. // VR Helper
  28353. if (this.VRHelper) {
  28354. this.VRHelper.dispose();
  28355. }
  28356. // Detach cameras
  28357. var canvas = this._engine.getRenderingCanvas();
  28358. if (canvas) {
  28359. var index;
  28360. for (index = 0; index < this.cameras.length; index++) {
  28361. this.cameras[index].detachControl(canvas);
  28362. }
  28363. }
  28364. // Release animation groups
  28365. while (this.animationGroups.length) {
  28366. this.animationGroups[0].dispose();
  28367. }
  28368. // Release lights
  28369. while (this.lights.length) {
  28370. this.lights[0].dispose();
  28371. }
  28372. // Release meshes
  28373. while (this.meshes.length) {
  28374. this.meshes[0].dispose(true);
  28375. }
  28376. while (this.transformNodes.length) {
  28377. this.removeTransformNode(this.transformNodes[0]);
  28378. }
  28379. // Release cameras
  28380. while (this.cameras.length) {
  28381. this.cameras[0].dispose();
  28382. }
  28383. // Release materials
  28384. if (this.defaultMaterial) {
  28385. this.defaultMaterial.dispose();
  28386. }
  28387. while (this.multiMaterials.length) {
  28388. this.multiMaterials[0].dispose();
  28389. }
  28390. while (this.materials.length) {
  28391. this.materials[0].dispose();
  28392. }
  28393. // Release particles
  28394. while (this.particleSystems.length) {
  28395. this.particleSystems[0].dispose();
  28396. }
  28397. // Release sprites
  28398. while (this.spriteManagers.length) {
  28399. this.spriteManagers[0].dispose();
  28400. }
  28401. // Release postProcesses
  28402. while (this.postProcesses.length) {
  28403. this.postProcesses[0].dispose();
  28404. }
  28405. // Release textures
  28406. while (this.textures.length) {
  28407. this.textures[0].dispose();
  28408. }
  28409. // Release UBO
  28410. this._sceneUbo.dispose();
  28411. if (this._alternateSceneUbo) {
  28412. this._alternateSceneUbo.dispose();
  28413. }
  28414. // Post-processes
  28415. this.postProcessManager.dispose();
  28416. if (this._postProcessRenderPipelineManager) {
  28417. this._postProcessRenderPipelineManager.dispose();
  28418. }
  28419. // Physics
  28420. if (this._physicsEngine) {
  28421. this.disablePhysicsEngine();
  28422. }
  28423. // Remove from engine
  28424. index = this._engine.scenes.indexOf(this);
  28425. if (index > -1) {
  28426. this._engine.scenes.splice(index, 1);
  28427. }
  28428. this._engine.wipeCaches(true);
  28429. this._isDisposed = true;
  28430. };
  28431. Object.defineProperty(Scene.prototype, "isDisposed", {
  28432. /**
  28433. * Gets if the scene is already disposed
  28434. */
  28435. get: function () {
  28436. return this._isDisposed;
  28437. },
  28438. enumerable: true,
  28439. configurable: true
  28440. });
  28441. /**
  28442. * Releases sounds & soundtracks
  28443. */
  28444. Scene.prototype.disposeSounds = function () {
  28445. if (!this._mainSoundTrack) {
  28446. return;
  28447. }
  28448. this.mainSoundTrack.dispose();
  28449. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28450. this.soundTracks[scIndex].dispose();
  28451. }
  28452. };
  28453. /**
  28454. * Call this function to reduce memory footprint of the scene.
  28455. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28456. */
  28457. Scene.prototype.clearCachedVertexData = function () {
  28458. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28459. var mesh = this.meshes[meshIndex];
  28460. var geometry = mesh.geometry;
  28461. if (geometry) {
  28462. geometry._indices = [];
  28463. for (var vbName in geometry._vertexBuffers) {
  28464. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28465. continue;
  28466. }
  28467. geometry._vertexBuffers[vbName]._buffer._data = null;
  28468. }
  28469. }
  28470. }
  28471. };
  28472. /**
  28473. * This function will remove the local cached buffer data from texture.
  28474. * It will save memory but will prevent the texture from being rebuilt
  28475. */
  28476. Scene.prototype.cleanCachedTextureBuffer = function () {
  28477. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28478. var baseTexture = _a[_i];
  28479. var buffer = baseTexture._buffer;
  28480. if (buffer) {
  28481. baseTexture._buffer = null;
  28482. }
  28483. }
  28484. };
  28485. // Octrees
  28486. /**
  28487. * Get the world extend vectors with an optional filter
  28488. *
  28489. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28490. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28491. */
  28492. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28493. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28494. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28495. filterPredicate = filterPredicate || (function () { return true; });
  28496. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28497. mesh.computeWorldMatrix(true);
  28498. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28499. return;
  28500. }
  28501. var boundingInfo = mesh.getBoundingInfo();
  28502. var minBox = boundingInfo.boundingBox.minimumWorld;
  28503. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28504. BABYLON.Tools.CheckExtends(minBox, min, max);
  28505. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28506. });
  28507. return {
  28508. min: min,
  28509. max: max
  28510. };
  28511. };
  28512. /**
  28513. * Creates or updates the octree used to boost selection (picking)
  28514. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28515. * @param maxCapacity defines the maximum capacity per leaf
  28516. * @param maxDepth defines the maximum depth of the octree
  28517. * @returns an octree of AbstractMesh
  28518. */
  28519. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28520. if (maxCapacity === void 0) { maxCapacity = 64; }
  28521. if (maxDepth === void 0) { maxDepth = 2; }
  28522. if (!this._selectionOctree) {
  28523. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28524. }
  28525. var worldExtends = this.getWorldExtends();
  28526. // Update octree
  28527. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28528. return this._selectionOctree;
  28529. };
  28530. // Picking
  28531. /**
  28532. * Creates a ray that can be used to pick in the scene
  28533. * @param x defines the x coordinate of the origin (on-screen)
  28534. * @param y defines the y coordinate of the origin (on-screen)
  28535. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28536. * @param camera defines the camera to use for the picking
  28537. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28538. * @returns a Ray
  28539. */
  28540. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28541. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28542. var result = BABYLON.Ray.Zero();
  28543. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28544. return result;
  28545. };
  28546. /**
  28547. * Creates a ray that can be used to pick in the scene
  28548. * @param x defines the x coordinate of the origin (on-screen)
  28549. * @param y defines the y coordinate of the origin (on-screen)
  28550. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28551. * @param result defines the ray where to store the picking ray
  28552. * @param camera defines the camera to use for the picking
  28553. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28554. * @returns the current scene
  28555. */
  28556. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28557. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28558. var engine = this._engine;
  28559. if (!camera) {
  28560. if (!this.activeCamera)
  28561. throw new Error("Active camera not set");
  28562. camera = this.activeCamera;
  28563. }
  28564. var cameraViewport = camera.viewport;
  28565. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28566. // Moving coordinates to local viewport world
  28567. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28568. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28569. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28570. return this;
  28571. };
  28572. /**
  28573. * Creates a ray that can be used to pick in the scene
  28574. * @param x defines the x coordinate of the origin (on-screen)
  28575. * @param y defines the y coordinate of the origin (on-screen)
  28576. * @param camera defines the camera to use for the picking
  28577. * @returns a Ray
  28578. */
  28579. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28580. var result = BABYLON.Ray.Zero();
  28581. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28582. return result;
  28583. };
  28584. /**
  28585. * Creates a ray that can be used to pick in the scene
  28586. * @param x defines the x coordinate of the origin (on-screen)
  28587. * @param y defines the y coordinate of the origin (on-screen)
  28588. * @param result defines the ray where to store the picking ray
  28589. * @param camera defines the camera to use for the picking
  28590. * @returns the current scene
  28591. */
  28592. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28593. if (!BABYLON.PickingInfo) {
  28594. return this;
  28595. }
  28596. var engine = this._engine;
  28597. if (!camera) {
  28598. if (!this.activeCamera)
  28599. throw new Error("Active camera not set");
  28600. camera = this.activeCamera;
  28601. }
  28602. var cameraViewport = camera.viewport;
  28603. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28604. var identity = BABYLON.Matrix.Identity();
  28605. // Moving coordinates to local viewport world
  28606. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28607. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28608. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28609. return this;
  28610. };
  28611. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28612. if (!BABYLON.PickingInfo) {
  28613. return null;
  28614. }
  28615. var pickingInfo = null;
  28616. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28617. var mesh = this.meshes[meshIndex];
  28618. if (predicate) {
  28619. if (!predicate(mesh)) {
  28620. continue;
  28621. }
  28622. }
  28623. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28624. continue;
  28625. }
  28626. var world = mesh.getWorldMatrix();
  28627. var ray = rayFunction(world);
  28628. var result = mesh.intersects(ray, fastCheck);
  28629. if (!result || !result.hit)
  28630. continue;
  28631. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28632. continue;
  28633. pickingInfo = result;
  28634. if (fastCheck) {
  28635. break;
  28636. }
  28637. }
  28638. return pickingInfo || new BABYLON.PickingInfo();
  28639. };
  28640. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28641. if (!BABYLON.PickingInfo) {
  28642. return null;
  28643. }
  28644. var pickingInfos = new Array();
  28645. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28646. var mesh = this.meshes[meshIndex];
  28647. if (predicate) {
  28648. if (!predicate(mesh)) {
  28649. continue;
  28650. }
  28651. }
  28652. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28653. continue;
  28654. }
  28655. var world = mesh.getWorldMatrix();
  28656. var ray = rayFunction(world);
  28657. var result = mesh.intersects(ray, false);
  28658. if (!result || !result.hit)
  28659. continue;
  28660. pickingInfos.push(result);
  28661. }
  28662. return pickingInfos;
  28663. };
  28664. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28665. if (!BABYLON.PickingInfo) {
  28666. return null;
  28667. }
  28668. var pickingInfo = null;
  28669. if (!camera) {
  28670. if (!this.activeCamera) {
  28671. return null;
  28672. }
  28673. camera = this.activeCamera;
  28674. }
  28675. if (this.spriteManagers.length > 0) {
  28676. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28677. var spriteManager = this.spriteManagers[spriteIndex];
  28678. if (!spriteManager.isPickable) {
  28679. continue;
  28680. }
  28681. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28682. if (!result || !result.hit)
  28683. continue;
  28684. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28685. continue;
  28686. pickingInfo = result;
  28687. if (fastCheck) {
  28688. break;
  28689. }
  28690. }
  28691. }
  28692. return pickingInfo || new BABYLON.PickingInfo();
  28693. };
  28694. /** Launch a ray to try to pick a mesh in the scene
  28695. * @param x position on screen
  28696. * @param y position on screen
  28697. * @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
  28698. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28699. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28700. * @returns a PickingInfo
  28701. */
  28702. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28703. var _this = this;
  28704. if (!BABYLON.PickingInfo) {
  28705. return null;
  28706. }
  28707. var result = this._internalPick(function (world) {
  28708. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28709. return _this._tempPickingRay;
  28710. }, predicate, fastCheck);
  28711. if (result) {
  28712. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28713. }
  28714. return result;
  28715. };
  28716. /** Launch a ray to try to pick a sprite in the scene
  28717. * @param x position on screen
  28718. * @param y position on screen
  28719. * @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
  28720. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28721. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28722. * @returns a PickingInfo
  28723. */
  28724. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28725. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28726. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28727. };
  28728. /** Use the given ray to pick a mesh in the scene
  28729. * @param ray The ray to use to pick meshes
  28730. * @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
  28731. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28732. * @returns a PickingInfo
  28733. */
  28734. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28735. var _this = this;
  28736. var result = this._internalPick(function (world) {
  28737. if (!_this._pickWithRayInverseMatrix) {
  28738. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28739. }
  28740. world.invertToRef(_this._pickWithRayInverseMatrix);
  28741. if (!_this._cachedRayForTransform) {
  28742. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28743. }
  28744. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28745. return _this._cachedRayForTransform;
  28746. }, predicate, fastCheck);
  28747. if (result) {
  28748. result.ray = ray;
  28749. }
  28750. return result;
  28751. };
  28752. /**
  28753. * Launch a ray to try to pick a mesh in the scene
  28754. * @param x X position on screen
  28755. * @param y Y position on screen
  28756. * @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
  28757. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28758. * @returns an array of PickingInfo
  28759. */
  28760. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28761. var _this = this;
  28762. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28763. };
  28764. /**
  28765. * Launch a ray to try to pick a mesh in the scene
  28766. * @param ray Ray to use
  28767. * @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
  28768. * @returns an array of PickingInfo
  28769. */
  28770. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28771. var _this = this;
  28772. return this._internalMultiPick(function (world) {
  28773. if (!_this._pickWithRayInverseMatrix) {
  28774. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28775. }
  28776. world.invertToRef(_this._pickWithRayInverseMatrix);
  28777. if (!_this._cachedRayForTransform) {
  28778. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28779. }
  28780. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28781. return _this._cachedRayForTransform;
  28782. }, predicate);
  28783. };
  28784. /**
  28785. * Force the value of meshUnderPointer
  28786. * @param mesh defines the mesh to use
  28787. */
  28788. Scene.prototype.setPointerOverMesh = function (mesh) {
  28789. if (this._pointerOverMesh === mesh) {
  28790. return;
  28791. }
  28792. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28793. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28794. }
  28795. this._pointerOverMesh = mesh;
  28796. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28797. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28798. }
  28799. };
  28800. /**
  28801. * Gets the mesh under the pointer
  28802. * @returns a Mesh or null if no mesh is under the pointer
  28803. */
  28804. Scene.prototype.getPointerOverMesh = function () {
  28805. return this._pointerOverMesh;
  28806. };
  28807. /**
  28808. * Force the sprite under the pointer
  28809. * @param sprite defines the sprite to use
  28810. */
  28811. Scene.prototype.setPointerOverSprite = function (sprite) {
  28812. if (this._pointerOverSprite === sprite) {
  28813. return;
  28814. }
  28815. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28816. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28817. }
  28818. this._pointerOverSprite = sprite;
  28819. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28820. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28821. }
  28822. };
  28823. /**
  28824. * Gets the sprite under the pointer
  28825. * @returns a Sprite or null if no sprite is under the pointer
  28826. */
  28827. Scene.prototype.getPointerOverSprite = function () {
  28828. return this._pointerOverSprite;
  28829. };
  28830. // Physics
  28831. /**
  28832. * Gets the current physics engine
  28833. * @returns a PhysicsEngine or null if none attached
  28834. */
  28835. Scene.prototype.getPhysicsEngine = function () {
  28836. return this._physicsEngine;
  28837. };
  28838. /**
  28839. * Enables physics to the current scene
  28840. * @param gravity defines the scene's gravity for the physics engine
  28841. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28842. * @return a boolean indicating if the physics engine was initialized
  28843. */
  28844. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28845. if (gravity === void 0) { gravity = null; }
  28846. if (this._physicsEngine) {
  28847. return true;
  28848. }
  28849. try {
  28850. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28851. return true;
  28852. }
  28853. catch (e) {
  28854. BABYLON.Tools.Error(e.message);
  28855. return false;
  28856. }
  28857. };
  28858. /**
  28859. * Disables and disposes the physics engine associated with the scene
  28860. */
  28861. Scene.prototype.disablePhysicsEngine = function () {
  28862. if (!this._physicsEngine) {
  28863. return;
  28864. }
  28865. this._physicsEngine.dispose();
  28866. this._physicsEngine = null;
  28867. };
  28868. /**
  28869. * Gets a boolean indicating if there is an active physics engine
  28870. * @returns a boolean indicating if there is an active physics engine
  28871. */
  28872. Scene.prototype.isPhysicsEnabled = function () {
  28873. return this._physicsEngine !== undefined;
  28874. };
  28875. /**
  28876. * Deletes a physics compound impostor
  28877. * @param compound defines the compound to delete
  28878. */
  28879. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28880. var mesh = compound.parts[0].mesh;
  28881. if (mesh.physicsImpostor) {
  28882. mesh.physicsImpostor.dispose( /*true*/);
  28883. mesh.physicsImpostor = null;
  28884. }
  28885. };
  28886. // Misc.
  28887. /** @hidden */
  28888. Scene.prototype._rebuildGeometries = function () {
  28889. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28890. var geometry = _a[_i];
  28891. geometry._rebuild();
  28892. }
  28893. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28894. var mesh = _c[_b];
  28895. mesh._rebuild();
  28896. }
  28897. if (this.postProcessManager) {
  28898. this.postProcessManager._rebuild();
  28899. }
  28900. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28901. var component = _e[_d];
  28902. component.rebuild();
  28903. }
  28904. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28905. var system = _g[_f];
  28906. system.rebuild();
  28907. }
  28908. if (this._postProcessRenderPipelineManager) {
  28909. this._postProcessRenderPipelineManager._rebuild();
  28910. }
  28911. };
  28912. /** @hidden */
  28913. Scene.prototype._rebuildTextures = function () {
  28914. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28915. var texture = _a[_i];
  28916. texture._rebuild();
  28917. }
  28918. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28919. };
  28920. /**
  28921. * Creates a default light for the scene.
  28922. * @param replace Whether to replace the existing lights in the scene.
  28923. */
  28924. Scene.prototype.createDefaultLight = function (replace) {
  28925. if (replace === void 0) { replace = false; }
  28926. // Dispose existing light in replace mode.
  28927. if (replace) {
  28928. if (this.lights) {
  28929. for (var i = 0; i < this.lights.length; i++) {
  28930. this.lights[i].dispose();
  28931. }
  28932. }
  28933. }
  28934. // Light
  28935. if (this.lights.length === 0) {
  28936. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28937. }
  28938. };
  28939. /**
  28940. * Creates a default camera for the scene.
  28941. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28942. * @param replace Whether to replace the existing active camera in the scene.
  28943. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28944. */
  28945. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28946. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28947. if (replace === void 0) { replace = false; }
  28948. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28949. // Dispose existing camera in replace mode.
  28950. if (replace) {
  28951. if (this.activeCamera) {
  28952. this.activeCamera.dispose();
  28953. this.activeCamera = null;
  28954. }
  28955. }
  28956. // Camera
  28957. if (!this.activeCamera) {
  28958. var worldExtends = this.getWorldExtends();
  28959. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28960. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28961. var camera;
  28962. var radius = worldSize.length() * 1.5;
  28963. // empty scene scenario!
  28964. if (!isFinite(radius)) {
  28965. radius = 1;
  28966. worldCenter.copyFromFloats(0, 0, 0);
  28967. }
  28968. if (createArcRotateCamera) {
  28969. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28970. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28971. arcRotateCamera.wheelPrecision = 100 / radius;
  28972. camera = arcRotateCamera;
  28973. }
  28974. else {
  28975. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28976. freeCamera.setTarget(worldCenter);
  28977. camera = freeCamera;
  28978. }
  28979. camera.minZ = radius * 0.01;
  28980. camera.maxZ = radius * 1000;
  28981. camera.speed = radius * 0.2;
  28982. this.activeCamera = camera;
  28983. var canvas = this.getEngine().getRenderingCanvas();
  28984. if (attachCameraControls && canvas) {
  28985. camera.attachControl(canvas);
  28986. }
  28987. }
  28988. };
  28989. /**
  28990. * Creates a default camera and a default light
  28991. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28992. * @param replace defines if the camera and/or light will replace the existing ones
  28993. * @param attachCameraControls defines if attachControl will be called on the new camera
  28994. */
  28995. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28996. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28997. if (replace === void 0) { replace = false; }
  28998. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28999. this.createDefaultLight(replace);
  29000. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29001. };
  29002. /**
  29003. * Creates a new sky box
  29004. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29005. * @param environmentTexture defines the texture to use as environment texture
  29006. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29007. * @param scale defines the overall scale of the skybox
  29008. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29009. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29010. * @returns a new mesh holding the sky box
  29011. */
  29012. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29013. if (pbr === void 0) { pbr = false; }
  29014. if (scale === void 0) { scale = 1000; }
  29015. if (blur === void 0) { blur = 0; }
  29016. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29017. if (!environmentTexture) {
  29018. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29019. return null;
  29020. }
  29021. if (setGlobalEnvTexture) {
  29022. if (environmentTexture) {
  29023. this.environmentTexture = environmentTexture;
  29024. }
  29025. }
  29026. // Skybox
  29027. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29028. if (pbr) {
  29029. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29030. hdrSkyboxMaterial.backFaceCulling = false;
  29031. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29032. if (hdrSkyboxMaterial.reflectionTexture) {
  29033. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29034. }
  29035. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29036. hdrSkyboxMaterial.disableLighting = true;
  29037. hdrSkyboxMaterial.twoSidedLighting = true;
  29038. hdrSkybox.infiniteDistance = true;
  29039. hdrSkybox.material = hdrSkyboxMaterial;
  29040. }
  29041. else {
  29042. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29043. skyboxMaterial.backFaceCulling = false;
  29044. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29045. if (skyboxMaterial.reflectionTexture) {
  29046. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29047. }
  29048. skyboxMaterial.disableLighting = true;
  29049. hdrSkybox.infiniteDistance = true;
  29050. hdrSkybox.material = skyboxMaterial;
  29051. }
  29052. return hdrSkybox;
  29053. };
  29054. /**
  29055. * Creates a new environment
  29056. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29057. * @param options defines the options you can use to configure the environment
  29058. * @returns the new EnvironmentHelper
  29059. */
  29060. Scene.prototype.createDefaultEnvironment = function (options) {
  29061. if (BABYLON.EnvironmentHelper) {
  29062. return new BABYLON.EnvironmentHelper(options, this);
  29063. }
  29064. return null;
  29065. };
  29066. /**
  29067. * Creates a new VREXperienceHelper
  29068. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29069. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29070. * @returns a new VREXperienceHelper
  29071. */
  29072. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29073. if (webVROptions === void 0) { webVROptions = {}; }
  29074. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29075. };
  29076. // Tags
  29077. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29078. if (tagsQuery === undefined) {
  29079. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29080. return list;
  29081. }
  29082. var listByTags = [];
  29083. forEach = forEach || (function (item) { return; });
  29084. for (var i in list) {
  29085. var item = list[i];
  29086. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29087. listByTags.push(item);
  29088. forEach(item);
  29089. }
  29090. }
  29091. return listByTags;
  29092. };
  29093. /**
  29094. * Get a list of meshes by tags
  29095. * @param tagsQuery defines the tags query to use
  29096. * @param forEach defines a predicate used to filter results
  29097. * @returns an array of Mesh
  29098. */
  29099. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29100. return this._getByTags(this.meshes, tagsQuery, forEach);
  29101. };
  29102. /**
  29103. * Get a list of cameras by tags
  29104. * @param tagsQuery defines the tags query to use
  29105. * @param forEach defines a predicate used to filter results
  29106. * @returns an array of Camera
  29107. */
  29108. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29109. return this._getByTags(this.cameras, tagsQuery, forEach);
  29110. };
  29111. /**
  29112. * Get a list of lights by tags
  29113. * @param tagsQuery defines the tags query to use
  29114. * @param forEach defines a predicate used to filter results
  29115. * @returns an array of Light
  29116. */
  29117. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29118. return this._getByTags(this.lights, tagsQuery, forEach);
  29119. };
  29120. /**
  29121. * Get a list of materials by tags
  29122. * @param tagsQuery defines the tags query to use
  29123. * @param forEach defines a predicate used to filter results
  29124. * @returns an array of Material
  29125. */
  29126. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29127. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29128. };
  29129. /**
  29130. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29131. * This allowed control for front to back rendering or reversly depending of the special needs.
  29132. *
  29133. * @param renderingGroupId The rendering group id corresponding to its index
  29134. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29135. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29136. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29137. */
  29138. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29139. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29140. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29141. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29142. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29143. };
  29144. /**
  29145. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29146. *
  29147. * @param renderingGroupId The rendering group id corresponding to its index
  29148. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29149. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29150. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29151. */
  29152. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29153. if (depth === void 0) { depth = true; }
  29154. if (stencil === void 0) { stencil = true; }
  29155. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29156. };
  29157. /**
  29158. * Will flag all materials as dirty to trigger new shader compilation
  29159. * @param flag defines the flag used to specify which material part must be marked as dirty
  29160. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29161. */
  29162. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29163. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29164. var material = _a[_i];
  29165. if (predicate && !predicate(material)) {
  29166. continue;
  29167. }
  29168. material.markAsDirty(flag);
  29169. }
  29170. };
  29171. /** @hidden */
  29172. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29173. var _this = this;
  29174. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29175. this._activeRequests.push(request);
  29176. request.onCompleteObservable.add(function (request) {
  29177. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29178. });
  29179. return request;
  29180. };
  29181. /** @hidden */
  29182. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29183. var _this = this;
  29184. return new Promise(function (resolve, reject) {
  29185. _this._loadFile(url, function (data) {
  29186. resolve(data);
  29187. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29188. reject(exception);
  29189. });
  29190. });
  29191. };
  29192. // Statics
  29193. Scene._FOGMODE_NONE = 0;
  29194. Scene._FOGMODE_EXP = 1;
  29195. Scene._FOGMODE_EXP2 = 2;
  29196. Scene._FOGMODE_LINEAR = 3;
  29197. Scene._uniqueIdCounter = 0;
  29198. /**
  29199. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29200. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29201. */
  29202. Scene.MinDeltaTime = 1.0;
  29203. /**
  29204. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29205. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29206. */
  29207. Scene.MaxDeltaTime = 1000.0;
  29208. /** The distance in pixel that you have to move to prevent some events */
  29209. Scene.DragMovementThreshold = 10; // in pixels
  29210. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29211. Scene.LongPressDelay = 500; // in milliseconds
  29212. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29213. Scene.DoubleClickDelay = 300; // in milliseconds
  29214. /** If you need to check double click without raising a single click at first click, enable this flag */
  29215. Scene.ExclusiveDoubleClickMode = false;
  29216. return Scene;
  29217. }(BABYLON.AbstractScene));
  29218. BABYLON.Scene = Scene;
  29219. })(BABYLON || (BABYLON = {}));
  29220. //# sourceMappingURL=babylon.scene.js.map
  29221. var BABYLON;
  29222. (function (BABYLON) {
  29223. /**
  29224. * Set of assets to keep when moving a scene into an asset container.
  29225. */
  29226. var KeepAssets = /** @class */ (function (_super) {
  29227. __extends(KeepAssets, _super);
  29228. function KeepAssets() {
  29229. return _super !== null && _super.apply(this, arguments) || this;
  29230. }
  29231. return KeepAssets;
  29232. }(BABYLON.AbstractScene));
  29233. BABYLON.KeepAssets = KeepAssets;
  29234. /**
  29235. * Container with a set of assets that can be added or removed from a scene.
  29236. */
  29237. var AssetContainer = /** @class */ (function (_super) {
  29238. __extends(AssetContainer, _super);
  29239. /**
  29240. * Instantiates an AssetContainer.
  29241. * @param scene The scene the AssetContainer belongs to.
  29242. */
  29243. function AssetContainer(scene) {
  29244. var _this = _super.call(this) || this;
  29245. _this.scene = scene;
  29246. return _this;
  29247. }
  29248. /**
  29249. * Adds all the assets from the container to the scene.
  29250. */
  29251. AssetContainer.prototype.addAllToScene = function () {
  29252. var _this = this;
  29253. this.cameras.forEach(function (o) {
  29254. _this.scene.addCamera(o);
  29255. });
  29256. this.lights.forEach(function (o) {
  29257. _this.scene.addLight(o);
  29258. });
  29259. this.meshes.forEach(function (o) {
  29260. _this.scene.addMesh(o);
  29261. });
  29262. this.skeletons.forEach(function (o) {
  29263. _this.scene.addSkeleton(o);
  29264. });
  29265. this.animations.forEach(function (o) {
  29266. _this.scene.addAnimation(o);
  29267. });
  29268. this.animationGroups.forEach(function (o) {
  29269. _this.scene.addAnimationGroup(o);
  29270. });
  29271. this.multiMaterials.forEach(function (o) {
  29272. _this.scene.addMultiMaterial(o);
  29273. });
  29274. this.materials.forEach(function (o) {
  29275. _this.scene.addMaterial(o);
  29276. });
  29277. this.morphTargetManagers.forEach(function (o) {
  29278. _this.scene.addMorphTargetManager(o);
  29279. });
  29280. this.geometries.forEach(function (o) {
  29281. _this.scene.addGeometry(o);
  29282. });
  29283. this.transformNodes.forEach(function (o) {
  29284. _this.scene.addTransformNode(o);
  29285. });
  29286. this.actionManagers.forEach(function (o) {
  29287. _this.scene.addActionManager(o);
  29288. });
  29289. this.sounds.forEach(function (o) {
  29290. o.play();
  29291. o.autoplay = true;
  29292. _this.scene.mainSoundTrack.AddSound(o);
  29293. });
  29294. this.textures.forEach(function (o) {
  29295. _this.scene.addTexture(o);
  29296. });
  29297. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29298. var component = _a[_i];
  29299. component.addFromContainer(this.scene);
  29300. }
  29301. };
  29302. /**
  29303. * Removes all the assets in the container from the scene
  29304. */
  29305. AssetContainer.prototype.removeAllFromScene = function () {
  29306. var _this = this;
  29307. this.cameras.forEach(function (o) {
  29308. _this.scene.removeCamera(o);
  29309. });
  29310. this.lights.forEach(function (o) {
  29311. _this.scene.removeLight(o);
  29312. });
  29313. this.meshes.forEach(function (o) {
  29314. _this.scene.removeMesh(o);
  29315. });
  29316. this.skeletons.forEach(function (o) {
  29317. _this.scene.removeSkeleton(o);
  29318. });
  29319. this.animations.forEach(function (o) {
  29320. _this.scene.removeAnimation(o);
  29321. });
  29322. this.animationGroups.forEach(function (o) {
  29323. _this.scene.removeAnimationGroup(o);
  29324. });
  29325. this.multiMaterials.forEach(function (o) {
  29326. _this.scene.removeMultiMaterial(o);
  29327. });
  29328. this.materials.forEach(function (o) {
  29329. _this.scene.removeMaterial(o);
  29330. });
  29331. this.morphTargetManagers.forEach(function (o) {
  29332. _this.scene.removeMorphTargetManager(o);
  29333. });
  29334. this.geometries.forEach(function (o) {
  29335. _this.scene.removeGeometry(o);
  29336. });
  29337. this.transformNodes.forEach(function (o) {
  29338. _this.scene.removeTransformNode(o);
  29339. });
  29340. this.actionManagers.forEach(function (o) {
  29341. _this.scene.removeActionManager(o);
  29342. });
  29343. this.sounds.forEach(function (o) {
  29344. o.stop();
  29345. o.autoplay = false;
  29346. _this.scene.mainSoundTrack.RemoveSound(o);
  29347. });
  29348. this.textures.forEach(function (o) {
  29349. _this.scene.removeTexture(o);
  29350. });
  29351. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29352. var component = _a[_i];
  29353. component.removeFromContainer(this.scene);
  29354. }
  29355. };
  29356. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29357. if (!sourceAssets) {
  29358. return;
  29359. }
  29360. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29361. var asset = sourceAssets_1[_i];
  29362. var move = true;
  29363. if (keepAssets) {
  29364. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29365. var keepAsset = keepAssets_1[_a];
  29366. if (asset === keepAsset) {
  29367. move = false;
  29368. break;
  29369. }
  29370. }
  29371. }
  29372. if (move) {
  29373. targetAssets.push(asset);
  29374. }
  29375. }
  29376. };
  29377. /**
  29378. * Removes all the assets contained in the scene and adds them to the container.
  29379. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29380. */
  29381. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29382. if (keepAssets === undefined) {
  29383. keepAssets = new KeepAssets();
  29384. }
  29385. for (var key in this) {
  29386. if (this.hasOwnProperty(key)) {
  29387. this[key] = this[key] || [];
  29388. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29389. }
  29390. }
  29391. this.removeAllFromScene();
  29392. };
  29393. /**
  29394. * 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.
  29395. * @returns the root mesh
  29396. */
  29397. AssetContainer.prototype.createRootMesh = function () {
  29398. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29399. this.meshes.forEach(function (m) {
  29400. if (!m.parent) {
  29401. rootMesh.addChild(m);
  29402. }
  29403. });
  29404. this.meshes.unshift(rootMesh);
  29405. return rootMesh;
  29406. };
  29407. return AssetContainer;
  29408. }(BABYLON.AbstractScene));
  29409. BABYLON.AssetContainer = AssetContainer;
  29410. })(BABYLON || (BABYLON = {}));
  29411. //# sourceMappingURL=babylon.assetContainer.js.map
  29412. var BABYLON;
  29413. (function (BABYLON) {
  29414. var Buffer = /** @class */ (function () {
  29415. /**
  29416. * Constructor
  29417. * @param engine the engine
  29418. * @param data the data to use for this buffer
  29419. * @param updatable whether the data is updatable
  29420. * @param stride the stride (optional)
  29421. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29422. * @param instanced whether the buffer is instanced (optional)
  29423. * @param useBytes set to true if the stride in in bytes (optional)
  29424. */
  29425. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29426. if (stride === void 0) { stride = 0; }
  29427. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29428. if (instanced === void 0) { instanced = false; }
  29429. if (useBytes === void 0) { useBytes = false; }
  29430. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29431. this._engine = engine.getScene().getEngine();
  29432. }
  29433. else {
  29434. this._engine = engine;
  29435. }
  29436. this._updatable = updatable;
  29437. this._instanced = instanced;
  29438. this._data = data;
  29439. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29440. if (!postponeInternalCreation) { // by default
  29441. this.create();
  29442. }
  29443. }
  29444. /**
  29445. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29446. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29447. * @param offset defines offset in the buffer (0 by default)
  29448. * @param size defines the size in floats of attributes (position is 3 for instance)
  29449. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29450. * @param instanced defines if the vertex buffer contains indexed data
  29451. * @param useBytes defines if the offset and stride are in bytes
  29452. * @returns the new vertex buffer
  29453. */
  29454. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29455. if (useBytes === void 0) { useBytes = false; }
  29456. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29457. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29458. // a lot of these parameters are ignored as they are overriden by the buffer
  29459. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29460. };
  29461. // Properties
  29462. Buffer.prototype.isUpdatable = function () {
  29463. return this._updatable;
  29464. };
  29465. Buffer.prototype.getData = function () {
  29466. return this._data;
  29467. };
  29468. Buffer.prototype.getBuffer = function () {
  29469. return this._buffer;
  29470. };
  29471. /**
  29472. * Gets the stride in float32 units (i.e. byte stride / 4).
  29473. * May not be an integer if the byte stride is not divisible by 4.
  29474. * DEPRECATED. Use byteStride instead.
  29475. * @returns the stride in float32 units
  29476. */
  29477. Buffer.prototype.getStrideSize = function () {
  29478. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29479. };
  29480. // Methods
  29481. Buffer.prototype.create = function (data) {
  29482. if (data === void 0) { data = null; }
  29483. if (!data && this._buffer) {
  29484. return; // nothing to do
  29485. }
  29486. data = data || this._data;
  29487. if (!data) {
  29488. return;
  29489. }
  29490. if (!this._buffer) { // create buffer
  29491. if (this._updatable) {
  29492. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29493. this._data = data;
  29494. }
  29495. else {
  29496. this._buffer = this._engine.createVertexBuffer(data);
  29497. }
  29498. }
  29499. else if (this._updatable) { // update buffer
  29500. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29501. this._data = data;
  29502. }
  29503. };
  29504. Buffer.prototype._rebuild = function () {
  29505. this._buffer = null;
  29506. this.create(this._data);
  29507. };
  29508. Buffer.prototype.update = function (data) {
  29509. this.create(data);
  29510. };
  29511. /**
  29512. * Updates the data directly.
  29513. * @param data the new data
  29514. * @param offset the new offset
  29515. * @param vertexCount the vertex count (optional)
  29516. * @param useBytes set to true if the offset is in bytes
  29517. */
  29518. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29519. if (useBytes === void 0) { useBytes = false; }
  29520. if (!this._buffer) {
  29521. return;
  29522. }
  29523. if (this._updatable) { // update buffer
  29524. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29525. this._data = null;
  29526. }
  29527. };
  29528. Buffer.prototype.dispose = function () {
  29529. if (!this._buffer) {
  29530. return;
  29531. }
  29532. if (this._engine._releaseBuffer(this._buffer)) {
  29533. this._buffer = null;
  29534. }
  29535. };
  29536. return Buffer;
  29537. }());
  29538. BABYLON.Buffer = Buffer;
  29539. })(BABYLON || (BABYLON = {}));
  29540. //# sourceMappingURL=babylon.buffer.js.map
  29541. var BABYLON;
  29542. (function (BABYLON) {
  29543. var VertexBuffer = /** @class */ (function () {
  29544. /**
  29545. * Constructor
  29546. * @param engine the engine
  29547. * @param data the data to use for this vertex buffer
  29548. * @param kind the vertex buffer kind
  29549. * @param updatable whether the data is updatable
  29550. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29551. * @param stride the stride (optional)
  29552. * @param instanced whether the buffer is instanced (optional)
  29553. * @param offset the offset of the data (optional)
  29554. * @param size the number of components (optional)
  29555. * @param type the type of the component (optional)
  29556. * @param normalized whether the data contains normalized data (optional)
  29557. * @param useBytes set to true if stride and offset are in bytes (optional)
  29558. */
  29559. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29560. if (normalized === void 0) { normalized = false; }
  29561. if (useBytes === void 0) { useBytes = false; }
  29562. if (data instanceof BABYLON.Buffer) {
  29563. this._buffer = data;
  29564. this._ownsBuffer = false;
  29565. }
  29566. else {
  29567. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29568. this._ownsBuffer = true;
  29569. }
  29570. this._kind = kind;
  29571. if (type == undefined) {
  29572. var data_1 = this.getData();
  29573. this.type = VertexBuffer.FLOAT;
  29574. if (data_1 instanceof Int8Array)
  29575. this.type = VertexBuffer.BYTE;
  29576. else if (data_1 instanceof Uint8Array)
  29577. this.type = VertexBuffer.UNSIGNED_BYTE;
  29578. else if (data_1 instanceof Int16Array)
  29579. this.type = VertexBuffer.SHORT;
  29580. else if (data_1 instanceof Uint16Array)
  29581. this.type = VertexBuffer.UNSIGNED_SHORT;
  29582. else if (data_1 instanceof Int32Array)
  29583. this.type = VertexBuffer.INT;
  29584. else if (data_1 instanceof Uint32Array)
  29585. this.type = VertexBuffer.UNSIGNED_INT;
  29586. }
  29587. else {
  29588. this.type = type;
  29589. }
  29590. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29591. if (useBytes) {
  29592. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29593. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29594. this.byteOffset = offset || 0;
  29595. }
  29596. else {
  29597. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29598. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29599. this.byteOffset = (offset || 0) * typeByteLength;
  29600. }
  29601. this.normalized = normalized;
  29602. this._instanced = instanced !== undefined ? instanced : false;
  29603. this._instanceDivisor = instanced ? 1 : 0;
  29604. }
  29605. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29606. /**
  29607. * Gets or sets the instance divisor when in instanced mode
  29608. */
  29609. get: function () {
  29610. return this._instanceDivisor;
  29611. },
  29612. set: function (value) {
  29613. this._instanceDivisor = value;
  29614. if (value == 0) {
  29615. this._instanced = false;
  29616. }
  29617. else {
  29618. this._instanced = true;
  29619. }
  29620. },
  29621. enumerable: true,
  29622. configurable: true
  29623. });
  29624. VertexBuffer.prototype._rebuild = function () {
  29625. if (!this._buffer) {
  29626. return;
  29627. }
  29628. this._buffer._rebuild();
  29629. };
  29630. /**
  29631. * Returns the kind of the VertexBuffer (string).
  29632. */
  29633. VertexBuffer.prototype.getKind = function () {
  29634. return this._kind;
  29635. };
  29636. // Properties
  29637. /**
  29638. * Boolean : is the VertexBuffer updatable ?
  29639. */
  29640. VertexBuffer.prototype.isUpdatable = function () {
  29641. return this._buffer.isUpdatable();
  29642. };
  29643. /**
  29644. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29645. */
  29646. VertexBuffer.prototype.getData = function () {
  29647. return this._buffer.getData();
  29648. };
  29649. /**
  29650. * Returns the WebGLBuffer associated to the VertexBuffer.
  29651. */
  29652. VertexBuffer.prototype.getBuffer = function () {
  29653. return this._buffer.getBuffer();
  29654. };
  29655. /**
  29656. * Returns the stride as a multiple of the type byte length.
  29657. * DEPRECATED. Use byteStride instead.
  29658. */
  29659. VertexBuffer.prototype.getStrideSize = function () {
  29660. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29661. };
  29662. /**
  29663. * Returns the offset as a multiple of the type byte length.
  29664. * DEPRECATED. Use byteOffset instead.
  29665. */
  29666. VertexBuffer.prototype.getOffset = function () {
  29667. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29668. };
  29669. /**
  29670. * Returns the number of components per vertex attribute (integer).
  29671. */
  29672. VertexBuffer.prototype.getSize = function () {
  29673. return this._size;
  29674. };
  29675. /**
  29676. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29677. */
  29678. VertexBuffer.prototype.getIsInstanced = function () {
  29679. return this._instanced;
  29680. };
  29681. /**
  29682. * Returns the instancing divisor, zero for non-instanced (integer).
  29683. */
  29684. VertexBuffer.prototype.getInstanceDivisor = function () {
  29685. return this._instanceDivisor;
  29686. };
  29687. // Methods
  29688. /**
  29689. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29690. * Returns the created WebGLBuffer.
  29691. */
  29692. VertexBuffer.prototype.create = function (data) {
  29693. return this._buffer.create(data);
  29694. };
  29695. /**
  29696. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29697. * This function will create a new buffer if the current one is not updatable
  29698. * Returns the updated WebGLBuffer.
  29699. */
  29700. VertexBuffer.prototype.update = function (data) {
  29701. return this._buffer.update(data);
  29702. };
  29703. /**
  29704. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29705. * Returns the directly updated WebGLBuffer.
  29706. * @param data the new data
  29707. * @param offset the new offset
  29708. * @param useBytes set to true if the offset is in bytes
  29709. */
  29710. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29711. if (useBytes === void 0) { useBytes = false; }
  29712. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29713. };
  29714. /**
  29715. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29716. */
  29717. VertexBuffer.prototype.dispose = function () {
  29718. if (this._ownsBuffer) {
  29719. this._buffer.dispose();
  29720. }
  29721. };
  29722. /**
  29723. * Enumerates each value of this vertex buffer as numbers.
  29724. * @param count the number of values to enumerate
  29725. * @param callback the callback function called for each value
  29726. */
  29727. VertexBuffer.prototype.forEach = function (count, callback) {
  29728. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29729. };
  29730. Object.defineProperty(VertexBuffer, "PositionKind", {
  29731. get: function () {
  29732. return VertexBuffer._PositionKind;
  29733. },
  29734. enumerable: true,
  29735. configurable: true
  29736. });
  29737. Object.defineProperty(VertexBuffer, "NormalKind", {
  29738. get: function () {
  29739. return VertexBuffer._NormalKind;
  29740. },
  29741. enumerable: true,
  29742. configurable: true
  29743. });
  29744. Object.defineProperty(VertexBuffer, "TangentKind", {
  29745. get: function () {
  29746. return VertexBuffer._TangentKind;
  29747. },
  29748. enumerable: true,
  29749. configurable: true
  29750. });
  29751. Object.defineProperty(VertexBuffer, "UVKind", {
  29752. get: function () {
  29753. return VertexBuffer._UVKind;
  29754. },
  29755. enumerable: true,
  29756. configurable: true
  29757. });
  29758. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29759. get: function () {
  29760. return VertexBuffer._UV2Kind;
  29761. },
  29762. enumerable: true,
  29763. configurable: true
  29764. });
  29765. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29766. get: function () {
  29767. return VertexBuffer._UV3Kind;
  29768. },
  29769. enumerable: true,
  29770. configurable: true
  29771. });
  29772. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29773. get: function () {
  29774. return VertexBuffer._UV4Kind;
  29775. },
  29776. enumerable: true,
  29777. configurable: true
  29778. });
  29779. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29780. get: function () {
  29781. return VertexBuffer._UV5Kind;
  29782. },
  29783. enumerable: true,
  29784. configurable: true
  29785. });
  29786. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29787. get: function () {
  29788. return VertexBuffer._UV6Kind;
  29789. },
  29790. enumerable: true,
  29791. configurable: true
  29792. });
  29793. Object.defineProperty(VertexBuffer, "ColorKind", {
  29794. get: function () {
  29795. return VertexBuffer._ColorKind;
  29796. },
  29797. enumerable: true,
  29798. configurable: true
  29799. });
  29800. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29801. get: function () {
  29802. return VertexBuffer._MatricesIndicesKind;
  29803. },
  29804. enumerable: true,
  29805. configurable: true
  29806. });
  29807. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29808. get: function () {
  29809. return VertexBuffer._MatricesWeightsKind;
  29810. },
  29811. enumerable: true,
  29812. configurable: true
  29813. });
  29814. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29815. get: function () {
  29816. return VertexBuffer._MatricesIndicesExtraKind;
  29817. },
  29818. enumerable: true,
  29819. configurable: true
  29820. });
  29821. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29822. get: function () {
  29823. return VertexBuffer._MatricesWeightsExtraKind;
  29824. },
  29825. enumerable: true,
  29826. configurable: true
  29827. });
  29828. /**
  29829. * Deduces the stride given a kind.
  29830. * @param kind The kind string to deduce
  29831. * @returns The deduced stride
  29832. */
  29833. VertexBuffer.DeduceStride = function (kind) {
  29834. switch (kind) {
  29835. case VertexBuffer.UVKind:
  29836. case VertexBuffer.UV2Kind:
  29837. case VertexBuffer.UV3Kind:
  29838. case VertexBuffer.UV4Kind:
  29839. case VertexBuffer.UV5Kind:
  29840. case VertexBuffer.UV6Kind:
  29841. return 2;
  29842. case VertexBuffer.NormalKind:
  29843. case VertexBuffer.PositionKind:
  29844. return 3;
  29845. case VertexBuffer.ColorKind:
  29846. case VertexBuffer.MatricesIndicesKind:
  29847. case VertexBuffer.MatricesIndicesExtraKind:
  29848. case VertexBuffer.MatricesWeightsKind:
  29849. case VertexBuffer.MatricesWeightsExtraKind:
  29850. case VertexBuffer.TangentKind:
  29851. return 4;
  29852. default:
  29853. throw new Error("Invalid kind '" + kind + "'");
  29854. }
  29855. };
  29856. /**
  29857. * Gets the byte length of the given type.
  29858. * @param type the type
  29859. * @returns the number of bytes
  29860. */
  29861. VertexBuffer.GetTypeByteLength = function (type) {
  29862. switch (type) {
  29863. case VertexBuffer.BYTE:
  29864. case VertexBuffer.UNSIGNED_BYTE:
  29865. return 1;
  29866. case VertexBuffer.SHORT:
  29867. case VertexBuffer.UNSIGNED_SHORT:
  29868. return 2;
  29869. case VertexBuffer.INT:
  29870. case VertexBuffer.FLOAT:
  29871. return 4;
  29872. default:
  29873. throw new Error("Invalid type '" + type + "'");
  29874. }
  29875. };
  29876. /**
  29877. * Enumerates each value of the given parameters as numbers.
  29878. * @param data the data to enumerate
  29879. * @param byteOffset the byte offset of the data
  29880. * @param byteStride the byte stride of the data
  29881. * @param componentCount the number of components per element
  29882. * @param componentType the type of the component
  29883. * @param count the total number of components
  29884. * @param normalized whether the data is normalized
  29885. * @param callback the callback function called for each value
  29886. */
  29887. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29888. if (data instanceof Array) {
  29889. var offset = byteOffset / 4;
  29890. var stride = byteStride / 4;
  29891. for (var index = 0; index < count; index += componentCount) {
  29892. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29893. callback(data[offset + componentIndex], index + componentIndex);
  29894. }
  29895. offset += stride;
  29896. }
  29897. }
  29898. else {
  29899. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29900. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29901. for (var index = 0; index < count; index += componentCount) {
  29902. var componentByteOffset = byteOffset;
  29903. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29904. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29905. callback(value, index + componentIndex);
  29906. componentByteOffset += componentByteLength;
  29907. }
  29908. byteOffset += byteStride;
  29909. }
  29910. }
  29911. };
  29912. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29913. switch (type) {
  29914. case VertexBuffer.BYTE: {
  29915. var value = dataView.getInt8(byteOffset);
  29916. if (normalized) {
  29917. value = Math.max(value / 127, -1);
  29918. }
  29919. return value;
  29920. }
  29921. case VertexBuffer.UNSIGNED_BYTE: {
  29922. var value = dataView.getUint8(byteOffset);
  29923. if (normalized) {
  29924. value = value / 255;
  29925. }
  29926. return value;
  29927. }
  29928. case VertexBuffer.SHORT: {
  29929. var value = dataView.getInt16(byteOffset, true);
  29930. if (normalized) {
  29931. value = Math.max(value / 16383, -1);
  29932. }
  29933. return value;
  29934. }
  29935. case VertexBuffer.UNSIGNED_SHORT: {
  29936. var value = dataView.getUint16(byteOffset, true);
  29937. if (normalized) {
  29938. value = value / 65535;
  29939. }
  29940. return value;
  29941. }
  29942. case VertexBuffer.FLOAT: {
  29943. return dataView.getFloat32(byteOffset, true);
  29944. }
  29945. default: {
  29946. throw new Error("Invalid component type " + type);
  29947. }
  29948. }
  29949. };
  29950. /**
  29951. * The byte type.
  29952. */
  29953. VertexBuffer.BYTE = 5120;
  29954. /**
  29955. * The unsigned byte type.
  29956. */
  29957. VertexBuffer.UNSIGNED_BYTE = 5121;
  29958. /**
  29959. * The short type.
  29960. */
  29961. VertexBuffer.SHORT = 5122;
  29962. /**
  29963. * The unsigned short type.
  29964. */
  29965. VertexBuffer.UNSIGNED_SHORT = 5123;
  29966. /**
  29967. * The integer type.
  29968. */
  29969. VertexBuffer.INT = 5124;
  29970. /**
  29971. * The unsigned integer type.
  29972. */
  29973. VertexBuffer.UNSIGNED_INT = 5125;
  29974. /**
  29975. * The float type.
  29976. */
  29977. VertexBuffer.FLOAT = 5126;
  29978. // Enums
  29979. VertexBuffer._PositionKind = "position";
  29980. VertexBuffer._NormalKind = "normal";
  29981. VertexBuffer._TangentKind = "tangent";
  29982. VertexBuffer._UVKind = "uv";
  29983. VertexBuffer._UV2Kind = "uv2";
  29984. VertexBuffer._UV3Kind = "uv3";
  29985. VertexBuffer._UV4Kind = "uv4";
  29986. VertexBuffer._UV5Kind = "uv5";
  29987. VertexBuffer._UV6Kind = "uv6";
  29988. VertexBuffer._ColorKind = "color";
  29989. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29990. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29991. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29992. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29993. return VertexBuffer;
  29994. }());
  29995. BABYLON.VertexBuffer = VertexBuffer;
  29996. })(BABYLON || (BABYLON = {}));
  29997. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29998. var BABYLON;
  29999. (function (BABYLON) {
  30000. /**
  30001. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30002. */
  30003. var DummyInternalTextureTracker = /** @class */ (function () {
  30004. function DummyInternalTextureTracker() {
  30005. /**
  30006. * Gets or set the previous tracker in the list
  30007. */
  30008. this.previous = null;
  30009. /**
  30010. * Gets or set the next tracker in the list
  30011. */
  30012. this.next = null;
  30013. }
  30014. return DummyInternalTextureTracker;
  30015. }());
  30016. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30017. })(BABYLON || (BABYLON = {}));
  30018. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30019. var BABYLON;
  30020. (function (BABYLON) {
  30021. /**
  30022. * Class used to store data associated with WebGL texture data for the engine
  30023. * This class should not be used directly
  30024. */
  30025. var InternalTexture = /** @class */ (function () {
  30026. /**
  30027. * Creates a new InternalTexture
  30028. * @param engine defines the engine to use
  30029. * @param dataSource defines the type of data that will be used
  30030. */
  30031. function InternalTexture(engine, dataSource) {
  30032. /**
  30033. * Observable called when the texture is loaded
  30034. */
  30035. this.onLoadedObservable = new BABYLON.Observable();
  30036. /**
  30037. * Gets or set the previous tracker in the list
  30038. */
  30039. this.previous = null;
  30040. /**
  30041. * Gets or set the next tracker in the list
  30042. */
  30043. this.next = null;
  30044. // Private
  30045. /** @hidden */
  30046. this._initialSlot = -1;
  30047. /** @hidden */
  30048. this._designatedSlot = -1;
  30049. /** @hidden */
  30050. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30051. /** @hidden */
  30052. this._comparisonFunction = 0;
  30053. /** @hidden */
  30054. this._sphericalPolynomial = null;
  30055. /** @hidden */
  30056. this._lodGenerationScale = 0;
  30057. /** @hidden */
  30058. this._lodGenerationOffset = 0;
  30059. /** @hidden */
  30060. this._isRGBD = false;
  30061. /** @hidden */
  30062. this._references = 1;
  30063. this._engine = engine;
  30064. this._dataSource = dataSource;
  30065. this._webGLTexture = engine._createTexture();
  30066. }
  30067. /**
  30068. * Gets the Engine the texture belongs to.
  30069. * @returns The babylon engine
  30070. */
  30071. InternalTexture.prototype.getEngine = function () {
  30072. return this._engine;
  30073. };
  30074. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30075. /**
  30076. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30077. */
  30078. get: function () {
  30079. return this._dataSource;
  30080. },
  30081. enumerable: true,
  30082. configurable: true
  30083. });
  30084. /**
  30085. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30086. */
  30087. InternalTexture.prototype.incrementReferences = function () {
  30088. this._references++;
  30089. };
  30090. /**
  30091. * Change the size of the texture (not the size of the content)
  30092. * @param width defines the new width
  30093. * @param height defines the new height
  30094. * @param depth defines the new depth (1 by default)
  30095. */
  30096. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30097. if (depth === void 0) { depth = 1; }
  30098. this.width = width;
  30099. this.height = height;
  30100. this.depth = depth;
  30101. this.baseWidth = width;
  30102. this.baseHeight = height;
  30103. this.baseDepth = depth;
  30104. this._size = width * height * depth;
  30105. };
  30106. /** @hidden */
  30107. InternalTexture.prototype._rebuild = function () {
  30108. var _this = this;
  30109. var proxy;
  30110. this.isReady = false;
  30111. this._cachedCoordinatesMode = null;
  30112. this._cachedWrapU = null;
  30113. this._cachedWrapV = null;
  30114. this._cachedAnisotropicFilteringLevel = null;
  30115. switch (this._dataSource) {
  30116. case InternalTexture.DATASOURCE_TEMP:
  30117. return;
  30118. case InternalTexture.DATASOURCE_URL:
  30119. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30120. _this.isReady = true;
  30121. }, null, this._buffer, undefined, this.format);
  30122. proxy._swapAndDie(this);
  30123. return;
  30124. case InternalTexture.DATASOURCE_RAW:
  30125. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30126. proxy._swapAndDie(this);
  30127. this.isReady = true;
  30128. return;
  30129. case InternalTexture.DATASOURCE_RAW3D:
  30130. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30131. proxy._swapAndDie(this);
  30132. this.isReady = true;
  30133. return;
  30134. case InternalTexture.DATASOURCE_DYNAMIC:
  30135. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30136. proxy._swapAndDie(this);
  30137. // The engine will make sure to update content so no need to flag it as isReady = true
  30138. return;
  30139. case InternalTexture.DATASOURCE_RENDERTARGET:
  30140. var options = new BABYLON.RenderTargetCreationOptions();
  30141. options.generateDepthBuffer = this._generateDepthBuffer;
  30142. options.generateMipMaps = this.generateMipMaps;
  30143. options.generateStencilBuffer = this._generateStencilBuffer;
  30144. options.samplingMode = this.samplingMode;
  30145. options.type = this.type;
  30146. if (this.isCube) {
  30147. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30148. }
  30149. else {
  30150. var size = {
  30151. width: this.width,
  30152. height: this.height
  30153. };
  30154. proxy = this._engine.createRenderTargetTexture(size, options);
  30155. }
  30156. proxy._swapAndDie(this);
  30157. this.isReady = true;
  30158. return;
  30159. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30160. var depthTextureOptions = {
  30161. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30162. comparisonFunction: this._comparisonFunction,
  30163. generateStencil: this._generateStencilBuffer,
  30164. isCube: this.isCube
  30165. };
  30166. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30167. proxy._swapAndDie(this);
  30168. this.isReady = true;
  30169. return;
  30170. case InternalTexture.DATASOURCE_CUBE:
  30171. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30172. _this.isReady = true;
  30173. }, null, this.format, this._extension);
  30174. proxy._swapAndDie(this);
  30175. return;
  30176. case InternalTexture.DATASOURCE_CUBERAW:
  30177. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30178. proxy._swapAndDie(this);
  30179. this.isReady = true;
  30180. return;
  30181. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30182. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30183. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30184. _this.isReady = true;
  30185. });
  30186. proxy._swapAndDie(this);
  30187. return;
  30188. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30189. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30190. if (proxy) {
  30191. proxy._swapAndDie(_this);
  30192. }
  30193. _this.isReady = true;
  30194. }, null, this.format, this._extension);
  30195. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30196. return;
  30197. }
  30198. };
  30199. InternalTexture.prototype._swapAndDie = function (target) {
  30200. target._webGLTexture = this._webGLTexture;
  30201. if (this._framebuffer) {
  30202. target._framebuffer = this._framebuffer;
  30203. }
  30204. if (this._depthStencilBuffer) {
  30205. target._depthStencilBuffer = this._depthStencilBuffer;
  30206. }
  30207. if (this._lodTextureHigh) {
  30208. if (target._lodTextureHigh) {
  30209. target._lodTextureHigh.dispose();
  30210. }
  30211. target._lodTextureHigh = this._lodTextureHigh;
  30212. }
  30213. if (this._lodTextureMid) {
  30214. if (target._lodTextureMid) {
  30215. target._lodTextureMid.dispose();
  30216. }
  30217. target._lodTextureMid = this._lodTextureMid;
  30218. }
  30219. if (this._lodTextureLow) {
  30220. if (target._lodTextureLow) {
  30221. target._lodTextureLow.dispose();
  30222. }
  30223. target._lodTextureLow = this._lodTextureLow;
  30224. }
  30225. var cache = this._engine.getLoadedTexturesCache();
  30226. var index = cache.indexOf(this);
  30227. if (index !== -1) {
  30228. cache.splice(index, 1);
  30229. }
  30230. };
  30231. /**
  30232. * Dispose the current allocated resources
  30233. */
  30234. InternalTexture.prototype.dispose = function () {
  30235. if (!this._webGLTexture) {
  30236. return;
  30237. }
  30238. this._references--;
  30239. if (this._references === 0) {
  30240. this._engine._releaseTexture(this);
  30241. this._webGLTexture = null;
  30242. this.previous = null;
  30243. this.next = null;
  30244. }
  30245. };
  30246. /**
  30247. * The source of the texture data is unknown
  30248. */
  30249. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30250. /**
  30251. * Texture data comes from an URL
  30252. */
  30253. InternalTexture.DATASOURCE_URL = 1;
  30254. /**
  30255. * Texture data is only used for temporary storage
  30256. */
  30257. InternalTexture.DATASOURCE_TEMP = 2;
  30258. /**
  30259. * Texture data comes from raw data (ArrayBuffer)
  30260. */
  30261. InternalTexture.DATASOURCE_RAW = 3;
  30262. /**
  30263. * Texture content is dynamic (video or dynamic texture)
  30264. */
  30265. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30266. /**
  30267. * Texture content is generated by rendering to it
  30268. */
  30269. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30270. /**
  30271. * Texture content is part of a multi render target process
  30272. */
  30273. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30274. /**
  30275. * Texture data comes from a cube data file
  30276. */
  30277. InternalTexture.DATASOURCE_CUBE = 7;
  30278. /**
  30279. * Texture data comes from a raw cube data
  30280. */
  30281. InternalTexture.DATASOURCE_CUBERAW = 8;
  30282. /**
  30283. * Texture data come from a prefiltered cube data file
  30284. */
  30285. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30286. /**
  30287. * Texture content is raw 3D data
  30288. */
  30289. InternalTexture.DATASOURCE_RAW3D = 10;
  30290. /**
  30291. * Texture content is a depth texture
  30292. */
  30293. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30294. /**
  30295. * Texture data comes from a raw cube data encoded with RGBD
  30296. */
  30297. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30298. return InternalTexture;
  30299. }());
  30300. BABYLON.InternalTexture = InternalTexture;
  30301. })(BABYLON || (BABYLON = {}));
  30302. //# sourceMappingURL=babylon.internalTexture.js.map
  30303. var BABYLON;
  30304. (function (BABYLON) {
  30305. var BaseTexture = /** @class */ (function () {
  30306. function BaseTexture(scene) {
  30307. this._hasAlpha = false;
  30308. this.getAlphaFromRGB = false;
  30309. this.level = 1;
  30310. this.coordinatesIndex = 0;
  30311. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30312. /**
  30313. * | Value | Type | Description |
  30314. * | ----- | ------------------ | ----------- |
  30315. * | 0 | CLAMP_ADDRESSMODE | |
  30316. * | 1 | WRAP_ADDRESSMODE | |
  30317. * | 2 | MIRROR_ADDRESSMODE | |
  30318. */
  30319. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30320. /**
  30321. * | Value | Type | Description |
  30322. * | ----- | ------------------ | ----------- |
  30323. * | 0 | CLAMP_ADDRESSMODE | |
  30324. * | 1 | WRAP_ADDRESSMODE | |
  30325. * | 2 | MIRROR_ADDRESSMODE | |
  30326. */
  30327. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30328. /**
  30329. * | Value | Type | Description |
  30330. * | ----- | ------------------ | ----------- |
  30331. * | 0 | CLAMP_ADDRESSMODE | |
  30332. * | 1 | WRAP_ADDRESSMODE | |
  30333. * | 2 | MIRROR_ADDRESSMODE | |
  30334. */
  30335. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30336. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30337. this.isCube = false;
  30338. this.is3D = false;
  30339. this.gammaSpace = true;
  30340. this.invertZ = false;
  30341. this.lodLevelInAlpha = false;
  30342. this.isRenderTarget = false;
  30343. this.animations = new Array();
  30344. /**
  30345. * An event triggered when the texture is disposed.
  30346. */
  30347. this.onDisposeObservable = new BABYLON.Observable();
  30348. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30349. this._cachedSize = BABYLON.Size.Zero();
  30350. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30351. if (this._scene) {
  30352. this._scene.textures.push(this);
  30353. }
  30354. this._uid = null;
  30355. }
  30356. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30357. get: function () {
  30358. return this._hasAlpha;
  30359. },
  30360. set: function (value) {
  30361. if (this._hasAlpha === value) {
  30362. return;
  30363. }
  30364. this._hasAlpha = value;
  30365. if (this._scene) {
  30366. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30367. }
  30368. },
  30369. enumerable: true,
  30370. configurable: true
  30371. });
  30372. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30373. get: function () {
  30374. return this._coordinatesMode;
  30375. },
  30376. /**
  30377. * How a texture is mapped.
  30378. *
  30379. * | Value | Type | Description |
  30380. * | ----- | ----------------------------------- | ----------- |
  30381. * | 0 | EXPLICIT_MODE | |
  30382. * | 1 | SPHERICAL_MODE | |
  30383. * | 2 | PLANAR_MODE | |
  30384. * | 3 | CUBIC_MODE | |
  30385. * | 4 | PROJECTION_MODE | |
  30386. * | 5 | SKYBOX_MODE | |
  30387. * | 6 | INVCUBIC_MODE | |
  30388. * | 7 | EQUIRECTANGULAR_MODE | |
  30389. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30390. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30391. */
  30392. set: function (value) {
  30393. if (this._coordinatesMode === value) {
  30394. return;
  30395. }
  30396. this._coordinatesMode = value;
  30397. if (this._scene) {
  30398. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30399. }
  30400. },
  30401. enumerable: true,
  30402. configurable: true
  30403. });
  30404. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30405. /**
  30406. * Gets whether or not the texture contains RGBD data.
  30407. */
  30408. get: function () {
  30409. return this._texture != null && this._texture._isRGBD;
  30410. },
  30411. enumerable: true,
  30412. configurable: true
  30413. });
  30414. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30415. get: function () {
  30416. if (this._texture)
  30417. return this._texture._lodGenerationOffset;
  30418. return 0.0;
  30419. },
  30420. set: function (value) {
  30421. if (this._texture)
  30422. this._texture._lodGenerationOffset = value;
  30423. },
  30424. enumerable: true,
  30425. configurable: true
  30426. });
  30427. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30428. get: function () {
  30429. if (this._texture)
  30430. return this._texture._lodGenerationScale;
  30431. return 0.0;
  30432. },
  30433. set: function (value) {
  30434. if (this._texture)
  30435. this._texture._lodGenerationScale = value;
  30436. },
  30437. enumerable: true,
  30438. configurable: true
  30439. });
  30440. Object.defineProperty(BaseTexture.prototype, "uid", {
  30441. get: function () {
  30442. if (!this._uid) {
  30443. this._uid = BABYLON.Tools.RandomId();
  30444. }
  30445. return this._uid;
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. BaseTexture.prototype.toString = function () {
  30451. return this.name;
  30452. };
  30453. BaseTexture.prototype.getClassName = function () {
  30454. return "BaseTexture";
  30455. };
  30456. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30457. set: function (callback) {
  30458. if (this._onDisposeObserver) {
  30459. this.onDisposeObservable.remove(this._onDisposeObserver);
  30460. }
  30461. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30462. },
  30463. enumerable: true,
  30464. configurable: true
  30465. });
  30466. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30467. get: function () {
  30468. return true;
  30469. },
  30470. enumerable: true,
  30471. configurable: true
  30472. });
  30473. BaseTexture.prototype.getScene = function () {
  30474. return this._scene;
  30475. };
  30476. BaseTexture.prototype.getTextureMatrix = function () {
  30477. return BABYLON.Matrix.IdentityReadOnly;
  30478. };
  30479. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30480. return BABYLON.Matrix.IdentityReadOnly;
  30481. };
  30482. BaseTexture.prototype.getInternalTexture = function () {
  30483. return this._texture;
  30484. };
  30485. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30486. return !this.isBlocking || this.isReady();
  30487. };
  30488. BaseTexture.prototype.isReady = function () {
  30489. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30490. this.delayLoad();
  30491. return false;
  30492. }
  30493. if (this._texture) {
  30494. return this._texture.isReady;
  30495. }
  30496. return false;
  30497. };
  30498. BaseTexture.prototype.getSize = function () {
  30499. if (this._texture) {
  30500. if (this._texture.width) {
  30501. this._cachedSize.width = this._texture.width;
  30502. this._cachedSize.height = this._texture.height;
  30503. return this._cachedSize;
  30504. }
  30505. if (this._texture._size) {
  30506. this._cachedSize.width = this._texture._size;
  30507. this._cachedSize.height = this._texture._size;
  30508. return this._cachedSize;
  30509. }
  30510. }
  30511. return this._cachedSize;
  30512. };
  30513. BaseTexture.prototype.getBaseSize = function () {
  30514. if (!this.isReady() || !this._texture)
  30515. return BABYLON.Size.Zero();
  30516. if (this._texture._size) {
  30517. return new BABYLON.Size(this._texture._size, this._texture._size);
  30518. }
  30519. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30520. };
  30521. BaseTexture.prototype.scale = function (ratio) {
  30522. };
  30523. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30524. get: function () {
  30525. return false;
  30526. },
  30527. enumerable: true,
  30528. configurable: true
  30529. });
  30530. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30531. if (!this._scene) {
  30532. return null;
  30533. }
  30534. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30535. for (var index = 0; index < texturesCache.length; index++) {
  30536. var texturesCacheEntry = texturesCache[index];
  30537. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30538. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30539. texturesCacheEntry.incrementReferences();
  30540. return texturesCacheEntry;
  30541. }
  30542. }
  30543. }
  30544. return null;
  30545. };
  30546. BaseTexture.prototype._rebuild = function () {
  30547. };
  30548. BaseTexture.prototype.delayLoad = function () {
  30549. };
  30550. BaseTexture.prototype.clone = function () {
  30551. return null;
  30552. };
  30553. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30554. get: function () {
  30555. if (!this._texture) {
  30556. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30557. }
  30558. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30559. },
  30560. enumerable: true,
  30561. configurable: true
  30562. });
  30563. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30564. get: function () {
  30565. if (!this._texture) {
  30566. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30567. }
  30568. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30569. },
  30570. enumerable: true,
  30571. configurable: true
  30572. });
  30573. /**
  30574. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30575. * This will returns an RGBA array buffer containing either in values (0-255) or
  30576. * float values (0-1) depending of the underlying buffer type.
  30577. * @param faceIndex The face of the texture to read (in case of cube texture)
  30578. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30579. * @returns The Array buffer containing the pixels data.
  30580. */
  30581. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30582. if (faceIndex === void 0) { faceIndex = 0; }
  30583. if (level === void 0) { level = 0; }
  30584. if (!this._texture) {
  30585. return null;
  30586. }
  30587. var size = this.getSize();
  30588. var width = size.width;
  30589. var height = size.height;
  30590. var scene = this.getScene();
  30591. if (!scene) {
  30592. return null;
  30593. }
  30594. var engine = scene.getEngine();
  30595. if (level != 0) {
  30596. width = width / Math.pow(2, level);
  30597. height = height / Math.pow(2, level);
  30598. width = Math.round(width);
  30599. height = Math.round(height);
  30600. }
  30601. if (this._texture.isCube) {
  30602. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30603. }
  30604. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30605. };
  30606. BaseTexture.prototype.releaseInternalTexture = function () {
  30607. if (this._texture) {
  30608. this._texture.dispose();
  30609. this._texture = null;
  30610. }
  30611. };
  30612. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30613. get: function () {
  30614. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30615. return null;
  30616. }
  30617. if (!this._texture._sphericalPolynomial) {
  30618. this._texture._sphericalPolynomial =
  30619. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30620. }
  30621. return this._texture._sphericalPolynomial;
  30622. },
  30623. set: function (value) {
  30624. if (this._texture) {
  30625. this._texture._sphericalPolynomial = value;
  30626. }
  30627. },
  30628. enumerable: true,
  30629. configurable: true
  30630. });
  30631. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30632. get: function () {
  30633. if (this._texture) {
  30634. return this._texture._lodTextureHigh;
  30635. }
  30636. return null;
  30637. },
  30638. enumerable: true,
  30639. configurable: true
  30640. });
  30641. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30642. get: function () {
  30643. if (this._texture) {
  30644. return this._texture._lodTextureMid;
  30645. }
  30646. return null;
  30647. },
  30648. enumerable: true,
  30649. configurable: true
  30650. });
  30651. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30652. get: function () {
  30653. if (this._texture) {
  30654. return this._texture._lodTextureLow;
  30655. }
  30656. return null;
  30657. },
  30658. enumerable: true,
  30659. configurable: true
  30660. });
  30661. BaseTexture.prototype.dispose = function () {
  30662. if (!this._scene) {
  30663. return;
  30664. }
  30665. // Animations
  30666. this._scene.stopAnimation(this);
  30667. // Remove from scene
  30668. this._scene._removePendingData(this);
  30669. var index = this._scene.textures.indexOf(this);
  30670. if (index >= 0) {
  30671. this._scene.textures.splice(index, 1);
  30672. }
  30673. if (this._texture === undefined) {
  30674. return;
  30675. }
  30676. // Release
  30677. this.releaseInternalTexture();
  30678. // Callback
  30679. this.onDisposeObservable.notifyObservers(this);
  30680. this.onDisposeObservable.clear();
  30681. };
  30682. BaseTexture.prototype.serialize = function () {
  30683. if (!this.name) {
  30684. return null;
  30685. }
  30686. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30687. // Animations
  30688. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30689. return serializationObject;
  30690. };
  30691. BaseTexture.WhenAllReady = function (textures, callback) {
  30692. var numRemaining = textures.length;
  30693. if (numRemaining === 0) {
  30694. callback();
  30695. return;
  30696. }
  30697. var _loop_1 = function () {
  30698. texture = textures[i];
  30699. if (texture.isReady()) {
  30700. if (--numRemaining === 0) {
  30701. callback();
  30702. }
  30703. }
  30704. else {
  30705. onLoadObservable = texture.onLoadObservable;
  30706. var onLoadCallback_1 = function () {
  30707. onLoadObservable.removeCallback(onLoadCallback_1);
  30708. if (--numRemaining === 0) {
  30709. callback();
  30710. }
  30711. };
  30712. onLoadObservable.add(onLoadCallback_1);
  30713. }
  30714. };
  30715. var texture, onLoadObservable;
  30716. for (var i = 0; i < textures.length; i++) {
  30717. _loop_1();
  30718. }
  30719. };
  30720. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30721. __decorate([
  30722. BABYLON.serialize()
  30723. ], BaseTexture.prototype, "name", void 0);
  30724. __decorate([
  30725. BABYLON.serialize("hasAlpha")
  30726. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30727. __decorate([
  30728. BABYLON.serialize()
  30729. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30730. __decorate([
  30731. BABYLON.serialize()
  30732. ], BaseTexture.prototype, "level", void 0);
  30733. __decorate([
  30734. BABYLON.serialize()
  30735. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30736. __decorate([
  30737. BABYLON.serialize("coordinatesMode")
  30738. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30739. __decorate([
  30740. BABYLON.serialize()
  30741. ], BaseTexture.prototype, "wrapU", void 0);
  30742. __decorate([
  30743. BABYLON.serialize()
  30744. ], BaseTexture.prototype, "wrapV", void 0);
  30745. __decorate([
  30746. BABYLON.serialize()
  30747. ], BaseTexture.prototype, "wrapR", void 0);
  30748. __decorate([
  30749. BABYLON.serialize()
  30750. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30751. __decorate([
  30752. BABYLON.serialize()
  30753. ], BaseTexture.prototype, "isCube", void 0);
  30754. __decorate([
  30755. BABYLON.serialize()
  30756. ], BaseTexture.prototype, "is3D", void 0);
  30757. __decorate([
  30758. BABYLON.serialize()
  30759. ], BaseTexture.prototype, "gammaSpace", void 0);
  30760. __decorate([
  30761. BABYLON.serialize()
  30762. ], BaseTexture.prototype, "invertZ", void 0);
  30763. __decorate([
  30764. BABYLON.serialize()
  30765. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30766. __decorate([
  30767. BABYLON.serialize()
  30768. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30769. __decorate([
  30770. BABYLON.serialize()
  30771. ], BaseTexture.prototype, "lodGenerationScale", null);
  30772. __decorate([
  30773. BABYLON.serialize()
  30774. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30775. return BaseTexture;
  30776. }());
  30777. BABYLON.BaseTexture = BaseTexture;
  30778. })(BABYLON || (BABYLON = {}));
  30779. //# sourceMappingURL=babylon.baseTexture.js.map
  30780. var BABYLON;
  30781. (function (BABYLON) {
  30782. var Texture = /** @class */ (function (_super) {
  30783. __extends(Texture, _super);
  30784. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30785. if (noMipmap === void 0) { noMipmap = false; }
  30786. if (invertY === void 0) { invertY = true; }
  30787. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30788. if (onLoad === void 0) { onLoad = null; }
  30789. if (onError === void 0) { onError = null; }
  30790. if (buffer === void 0) { buffer = null; }
  30791. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30792. var _this = _super.call(this, scene) || this;
  30793. _this.uOffset = 0;
  30794. _this.vOffset = 0;
  30795. _this.uScale = 1.0;
  30796. _this.vScale = 1.0;
  30797. _this.uAng = 0;
  30798. _this.vAng = 0;
  30799. _this.wAng = 0;
  30800. /**
  30801. * Defines the center of rotation (U)
  30802. */
  30803. _this.uRotationCenter = 0.5;
  30804. /**
  30805. * Defines the center of rotation (V)
  30806. */
  30807. _this.vRotationCenter = 0.5;
  30808. /**
  30809. * Defines the center of rotation (W)
  30810. */
  30811. _this.wRotationCenter = 0.5;
  30812. _this._isBlocking = true;
  30813. _this.name = url || "";
  30814. _this.url = url;
  30815. _this._noMipmap = noMipmap;
  30816. _this._invertY = invertY;
  30817. _this._samplingMode = samplingMode;
  30818. _this._buffer = buffer;
  30819. _this._deleteBuffer = deleteBuffer;
  30820. if (format) {
  30821. _this._format = format;
  30822. }
  30823. scene = _this.getScene();
  30824. if (!scene) {
  30825. return _this;
  30826. }
  30827. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30828. var load = function () {
  30829. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30830. _this.onLoadObservable.notifyObservers(_this);
  30831. }
  30832. if (onLoad) {
  30833. onLoad();
  30834. }
  30835. if (!_this.isBlocking && scene) {
  30836. scene.resetCachedMaterial();
  30837. }
  30838. };
  30839. if (!_this.url) {
  30840. _this._delayedOnLoad = load;
  30841. _this._delayedOnError = onError;
  30842. return _this;
  30843. }
  30844. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30845. if (!_this._texture) {
  30846. if (!scene.useDelayedTextureLoading) {
  30847. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30848. if (deleteBuffer) {
  30849. delete _this._buffer;
  30850. }
  30851. }
  30852. else {
  30853. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30854. _this._delayedOnLoad = load;
  30855. _this._delayedOnError = onError;
  30856. }
  30857. }
  30858. else {
  30859. if (_this._texture.isReady) {
  30860. BABYLON.Tools.SetImmediate(function () { return load(); });
  30861. }
  30862. else {
  30863. _this._texture.onLoadedObservable.add(load);
  30864. }
  30865. }
  30866. return _this;
  30867. }
  30868. Object.defineProperty(Texture.prototype, "noMipmap", {
  30869. get: function () {
  30870. return this._noMipmap;
  30871. },
  30872. enumerable: true,
  30873. configurable: true
  30874. });
  30875. Object.defineProperty(Texture.prototype, "isBlocking", {
  30876. get: function () {
  30877. return this._isBlocking;
  30878. },
  30879. set: function (value) {
  30880. this._isBlocking = value;
  30881. },
  30882. enumerable: true,
  30883. configurable: true
  30884. });
  30885. Object.defineProperty(Texture.prototype, "samplingMode", {
  30886. get: function () {
  30887. return this._samplingMode;
  30888. },
  30889. enumerable: true,
  30890. configurable: true
  30891. });
  30892. /**
  30893. * Update the url (and optional buffer) of this texture if url was null during construction.
  30894. * @param url the url of the texture
  30895. * @param buffer the buffer of the texture (defaults to null)
  30896. */
  30897. Texture.prototype.updateURL = function (url, buffer) {
  30898. if (buffer === void 0) { buffer = null; }
  30899. if (this.url) {
  30900. throw new Error("URL is already set");
  30901. }
  30902. this.url = url;
  30903. this._buffer = buffer;
  30904. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30905. this.delayLoad();
  30906. };
  30907. Texture.prototype.delayLoad = function () {
  30908. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30909. return;
  30910. }
  30911. var scene = this.getScene();
  30912. if (!scene) {
  30913. return;
  30914. }
  30915. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30916. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30917. if (!this._texture) {
  30918. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30919. if (this._deleteBuffer) {
  30920. delete this._buffer;
  30921. }
  30922. }
  30923. else {
  30924. if (this._delayedOnLoad) {
  30925. if (this._texture.isReady) {
  30926. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30927. }
  30928. else {
  30929. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30930. }
  30931. }
  30932. }
  30933. this._delayedOnLoad = null;
  30934. this._delayedOnError = null;
  30935. };
  30936. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30937. if (!this._texture) {
  30938. return;
  30939. }
  30940. var scene = this.getScene();
  30941. if (!scene) {
  30942. return;
  30943. }
  30944. this._samplingMode = samplingMode;
  30945. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30946. };
  30947. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30948. x *= this.uScale;
  30949. y *= this.vScale;
  30950. x -= this.uRotationCenter * this.uScale;
  30951. y -= this.vRotationCenter * this.vScale;
  30952. z -= this.wRotationCenter;
  30953. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30954. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30955. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30956. t.z += this.wRotationCenter;
  30957. };
  30958. Texture.prototype.getTextureMatrix = function () {
  30959. var _this = this;
  30960. if (this.uOffset === this._cachedUOffset &&
  30961. this.vOffset === this._cachedVOffset &&
  30962. this.uScale === this._cachedUScale &&
  30963. this.vScale === this._cachedVScale &&
  30964. this.uAng === this._cachedUAng &&
  30965. this.vAng === this._cachedVAng &&
  30966. this.wAng === this._cachedWAng) {
  30967. return this._cachedTextureMatrix;
  30968. }
  30969. this._cachedUOffset = this.uOffset;
  30970. this._cachedVOffset = this.vOffset;
  30971. this._cachedUScale = this.uScale;
  30972. this._cachedVScale = this.vScale;
  30973. this._cachedUAng = this.uAng;
  30974. this._cachedVAng = this.vAng;
  30975. this._cachedWAng = this.wAng;
  30976. if (!this._cachedTextureMatrix) {
  30977. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30978. this._rowGenerationMatrix = new BABYLON.Matrix();
  30979. this._t0 = BABYLON.Vector3.Zero();
  30980. this._t1 = BABYLON.Vector3.Zero();
  30981. this._t2 = BABYLON.Vector3.Zero();
  30982. }
  30983. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30984. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30985. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30986. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30987. this._t1.subtractInPlace(this._t0);
  30988. this._t2.subtractInPlace(this._t0);
  30989. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30990. this._cachedTextureMatrix.m[0] = this._t1.x;
  30991. this._cachedTextureMatrix.m[1] = this._t1.y;
  30992. this._cachedTextureMatrix.m[2] = this._t1.z;
  30993. this._cachedTextureMatrix.m[4] = this._t2.x;
  30994. this._cachedTextureMatrix.m[5] = this._t2.y;
  30995. this._cachedTextureMatrix.m[6] = this._t2.z;
  30996. this._cachedTextureMatrix.m[8] = this._t0.x;
  30997. this._cachedTextureMatrix.m[9] = this._t0.y;
  30998. this._cachedTextureMatrix.m[10] = this._t0.z;
  30999. var scene = this.getScene();
  31000. if (!scene) {
  31001. return this._cachedTextureMatrix;
  31002. }
  31003. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31004. return mat.hasTexture(_this);
  31005. });
  31006. return this._cachedTextureMatrix;
  31007. };
  31008. Texture.prototype.getReflectionTextureMatrix = function () {
  31009. var _this = this;
  31010. var scene = this.getScene();
  31011. if (!scene) {
  31012. return this._cachedTextureMatrix;
  31013. }
  31014. if (this.uOffset === this._cachedUOffset &&
  31015. this.vOffset === this._cachedVOffset &&
  31016. this.uScale === this._cachedUScale &&
  31017. this.vScale === this._cachedVScale &&
  31018. this.coordinatesMode === this._cachedCoordinatesMode) {
  31019. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31020. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31021. return this._cachedTextureMatrix;
  31022. }
  31023. }
  31024. else {
  31025. return this._cachedTextureMatrix;
  31026. }
  31027. }
  31028. if (!this._cachedTextureMatrix) {
  31029. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31030. }
  31031. if (!this._projectionModeMatrix) {
  31032. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31033. }
  31034. this._cachedUOffset = this.uOffset;
  31035. this._cachedVOffset = this.vOffset;
  31036. this._cachedUScale = this.uScale;
  31037. this._cachedVScale = this.vScale;
  31038. this._cachedCoordinatesMode = this.coordinatesMode;
  31039. switch (this.coordinatesMode) {
  31040. case Texture.PLANAR_MODE:
  31041. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31042. this._cachedTextureMatrix[0] = this.uScale;
  31043. this._cachedTextureMatrix[5] = this.vScale;
  31044. this._cachedTextureMatrix[12] = this.uOffset;
  31045. this._cachedTextureMatrix[13] = this.vOffset;
  31046. break;
  31047. case Texture.PROJECTION_MODE:
  31048. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31049. this._projectionModeMatrix.m[0] = 0.5;
  31050. this._projectionModeMatrix.m[5] = -0.5;
  31051. this._projectionModeMatrix.m[10] = 0.0;
  31052. this._projectionModeMatrix.m[12] = 0.5;
  31053. this._projectionModeMatrix.m[13] = 0.5;
  31054. this._projectionModeMatrix.m[14] = 1.0;
  31055. this._projectionModeMatrix.m[15] = 1.0;
  31056. var projectionMatrix = scene.getProjectionMatrix();
  31057. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31058. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31059. break;
  31060. default:
  31061. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31062. break;
  31063. }
  31064. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31065. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31066. });
  31067. return this._cachedTextureMatrix;
  31068. };
  31069. Texture.prototype.clone = function () {
  31070. var _this = this;
  31071. return BABYLON.SerializationHelper.Clone(function () {
  31072. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31073. }, this);
  31074. };
  31075. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31076. get: function () {
  31077. if (!this._onLoadObservable) {
  31078. this._onLoadObservable = new BABYLON.Observable();
  31079. }
  31080. return this._onLoadObservable;
  31081. },
  31082. enumerable: true,
  31083. configurable: true
  31084. });
  31085. Texture.prototype.serialize = function () {
  31086. var serializationObject = _super.prototype.serialize.call(this);
  31087. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31088. serializationObject.base64String = this._buffer;
  31089. serializationObject.name = serializationObject.name.replace("data:", "");
  31090. }
  31091. serializationObject.invertY = this._invertY;
  31092. serializationObject.samplingMode = this.samplingMode;
  31093. return serializationObject;
  31094. };
  31095. Texture.prototype.getClassName = function () {
  31096. return "Texture";
  31097. };
  31098. Texture.prototype.dispose = function () {
  31099. _super.prototype.dispose.call(this);
  31100. if (this._onLoadObservable) {
  31101. this._onLoadObservable.clear();
  31102. this._onLoadObservable = null;
  31103. }
  31104. this._delayedOnLoad = null;
  31105. this._delayedOnError = null;
  31106. };
  31107. // Statics
  31108. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31109. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31110. if (onLoad === void 0) { onLoad = null; }
  31111. if (onError === void 0) { onError = null; }
  31112. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31113. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31114. };
  31115. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31116. if (parsedTexture.customType) {
  31117. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31118. // Update Sampling Mode
  31119. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31120. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31121. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31122. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31123. }
  31124. }
  31125. return parsedCustomTexture;
  31126. }
  31127. if (parsedTexture.isCube) {
  31128. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31129. }
  31130. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31131. return null;
  31132. }
  31133. var texture = BABYLON.SerializationHelper.Parse(function () {
  31134. var generateMipMaps = true;
  31135. if (parsedTexture.noMipmap) {
  31136. generateMipMaps = false;
  31137. }
  31138. if (parsedTexture.mirrorPlane) {
  31139. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31140. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31141. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31142. return mirrorTexture;
  31143. }
  31144. else if (parsedTexture.isRenderTarget) {
  31145. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31146. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31147. return renderTargetTexture;
  31148. }
  31149. else {
  31150. var texture;
  31151. if (parsedTexture.base64String) {
  31152. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31153. }
  31154. else {
  31155. var url = rootUrl + parsedTexture.name;
  31156. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31157. url = parsedTexture.url;
  31158. }
  31159. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31160. }
  31161. return texture;
  31162. }
  31163. }, parsedTexture, scene);
  31164. // Update Sampling Mode
  31165. if (parsedTexture.samplingMode) {
  31166. var sampling = parsedTexture.samplingMode;
  31167. if (texture._samplingMode !== sampling) {
  31168. texture.updateSamplingMode(sampling);
  31169. }
  31170. }
  31171. // Animations
  31172. if (parsedTexture.animations) {
  31173. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31174. var parsedAnimation = parsedTexture.animations[animationIndex];
  31175. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31176. }
  31177. }
  31178. return texture;
  31179. };
  31180. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31181. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31182. if (noMipmap === void 0) { noMipmap = false; }
  31183. if (invertY === void 0) { invertY = true; }
  31184. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31185. if (onLoad === void 0) { onLoad = null; }
  31186. if (onError === void 0) { onError = null; }
  31187. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31188. if (name.substr(0, 5) !== "data:") {
  31189. name = "data:" + name;
  31190. }
  31191. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31192. };
  31193. // Constants
  31194. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31195. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31196. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31197. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31198. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31199. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31200. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31201. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31202. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31203. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31204. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31205. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31206. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31207. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31208. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31209. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31210. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31211. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31212. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31213. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31214. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31215. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31216. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31217. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31218. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31219. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31220. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31221. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31222. /**
  31223. * 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
  31224. */
  31225. Texture.UseSerializedUrlIfAny = false;
  31226. __decorate([
  31227. BABYLON.serialize()
  31228. ], Texture.prototype, "url", void 0);
  31229. __decorate([
  31230. BABYLON.serialize()
  31231. ], Texture.prototype, "uOffset", void 0);
  31232. __decorate([
  31233. BABYLON.serialize()
  31234. ], Texture.prototype, "vOffset", void 0);
  31235. __decorate([
  31236. BABYLON.serialize()
  31237. ], Texture.prototype, "uScale", void 0);
  31238. __decorate([
  31239. BABYLON.serialize()
  31240. ], Texture.prototype, "vScale", void 0);
  31241. __decorate([
  31242. BABYLON.serialize()
  31243. ], Texture.prototype, "uAng", void 0);
  31244. __decorate([
  31245. BABYLON.serialize()
  31246. ], Texture.prototype, "vAng", void 0);
  31247. __decorate([
  31248. BABYLON.serialize()
  31249. ], Texture.prototype, "wAng", void 0);
  31250. __decorate([
  31251. BABYLON.serialize()
  31252. ], Texture.prototype, "uRotationCenter", void 0);
  31253. __decorate([
  31254. BABYLON.serialize()
  31255. ], Texture.prototype, "vRotationCenter", void 0);
  31256. __decorate([
  31257. BABYLON.serialize()
  31258. ], Texture.prototype, "wRotationCenter", void 0);
  31259. __decorate([
  31260. BABYLON.serialize()
  31261. ], Texture.prototype, "isBlocking", null);
  31262. return Texture;
  31263. }(BABYLON.BaseTexture));
  31264. BABYLON.Texture = Texture;
  31265. })(BABYLON || (BABYLON = {}));
  31266. //# sourceMappingURL=babylon.texture.js.map
  31267. var BABYLON;
  31268. (function (BABYLON) {
  31269. /**
  31270. * @hidden
  31271. **/
  31272. var _InstancesBatch = /** @class */ (function () {
  31273. function _InstancesBatch() {
  31274. this.mustReturn = false;
  31275. this.visibleInstances = new Array();
  31276. this.renderSelf = new Array();
  31277. }
  31278. return _InstancesBatch;
  31279. }());
  31280. BABYLON._InstancesBatch = _InstancesBatch;
  31281. var Mesh = /** @class */ (function (_super) {
  31282. __extends(Mesh, _super);
  31283. /**
  31284. * @constructor
  31285. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31286. * @param {Scene} scene The scene to add this mesh to.
  31287. * @param {Node} parent The parent of this mesh, if it has one
  31288. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31289. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31290. * When false, achieved by calling a clone(), also passing False.
  31291. * This will make creation of children, recursive.
  31292. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31293. */
  31294. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31295. if (scene === void 0) { scene = null; }
  31296. if (parent === void 0) { parent = null; }
  31297. if (source === void 0) { source = null; }
  31298. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31299. var _this = _super.call(this, name, scene) || this;
  31300. // Events
  31301. /**
  31302. * An event triggered before rendering the mesh
  31303. */
  31304. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31305. /**
  31306. * An event triggered after rendering the mesh
  31307. */
  31308. _this.onAfterRenderObservable = new BABYLON.Observable();
  31309. /**
  31310. * An event triggered before drawing the mesh
  31311. */
  31312. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31313. // Members
  31314. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31315. _this.instances = new Array();
  31316. _this._LODLevels = new Array();
  31317. _this._visibleInstances = {};
  31318. _this._renderIdForInstances = new Array();
  31319. _this._batchCache = new _InstancesBatch();
  31320. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31321. // Use by builder only to know what orientation were the mesh build in.
  31322. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31323. _this.overrideMaterialSideOrientation = null;
  31324. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31325. // Will be used to save a source mesh reference, If any
  31326. _this._source = null;
  31327. scene = _this.getScene();
  31328. if (source) {
  31329. // Geometry
  31330. if (source._geometry) {
  31331. source._geometry.applyToMesh(_this);
  31332. }
  31333. // Deep copy
  31334. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31335. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31336. // Source mesh
  31337. _this._source = source;
  31338. // Metadata
  31339. if (source.metadata && source.metadata.clone) {
  31340. _this.metadata = source.metadata.clone();
  31341. }
  31342. else {
  31343. _this.metadata = source.metadata;
  31344. }
  31345. // Tags
  31346. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31347. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31348. }
  31349. // Parent
  31350. _this.parent = source.parent;
  31351. // Pivot
  31352. _this.setPivotMatrix(source.getPivotMatrix());
  31353. _this.id = name + "." + source.id;
  31354. // Material
  31355. _this.material = source.material;
  31356. var index;
  31357. if (!doNotCloneChildren) {
  31358. // Children
  31359. var directDescendants = source.getDescendants(true);
  31360. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31361. var child = directDescendants[index_1];
  31362. if (child.clone) {
  31363. child.clone(name + "." + child.name, _this);
  31364. }
  31365. }
  31366. }
  31367. // Physics clone
  31368. var physicsEngine = _this.getScene().getPhysicsEngine();
  31369. if (clonePhysicsImpostor && physicsEngine) {
  31370. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31371. if (impostor) {
  31372. _this.physicsImpostor = impostor.clone(_this);
  31373. }
  31374. }
  31375. // Particles
  31376. for (index = 0; index < scene.particleSystems.length; index++) {
  31377. var system = scene.particleSystems[index];
  31378. if (system.emitter === source) {
  31379. system.clone(system.name, _this);
  31380. }
  31381. }
  31382. _this.refreshBoundingInfo();
  31383. _this.computeWorldMatrix(true);
  31384. }
  31385. // Parent
  31386. if (parent !== null) {
  31387. _this.parent = parent;
  31388. }
  31389. return _this;
  31390. }
  31391. Object.defineProperty(Mesh, "FRONTSIDE", {
  31392. /**
  31393. * Mesh side orientation : usually the external or front surface
  31394. */
  31395. get: function () {
  31396. return Mesh._FRONTSIDE;
  31397. },
  31398. enumerable: true,
  31399. configurable: true
  31400. });
  31401. Object.defineProperty(Mesh, "BACKSIDE", {
  31402. /**
  31403. * Mesh side orientation : usually the internal or back surface
  31404. */
  31405. get: function () {
  31406. return Mesh._BACKSIDE;
  31407. },
  31408. enumerable: true,
  31409. configurable: true
  31410. });
  31411. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31412. /**
  31413. * Mesh side orientation : both internal and external or front and back surfaces
  31414. */
  31415. get: function () {
  31416. return Mesh._DOUBLESIDE;
  31417. },
  31418. enumerable: true,
  31419. configurable: true
  31420. });
  31421. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31422. /**
  31423. * Mesh side orientation : by default, `FRONTSIDE`
  31424. */
  31425. get: function () {
  31426. return Mesh._DEFAULTSIDE;
  31427. },
  31428. enumerable: true,
  31429. configurable: true
  31430. });
  31431. Object.defineProperty(Mesh, "NO_CAP", {
  31432. /**
  31433. * Mesh cap setting : no cap
  31434. */
  31435. get: function () {
  31436. return Mesh._NO_CAP;
  31437. },
  31438. enumerable: true,
  31439. configurable: true
  31440. });
  31441. Object.defineProperty(Mesh, "CAP_START", {
  31442. /**
  31443. * Mesh cap setting : one cap at the beginning of the mesh
  31444. */
  31445. get: function () {
  31446. return Mesh._CAP_START;
  31447. },
  31448. enumerable: true,
  31449. configurable: true
  31450. });
  31451. Object.defineProperty(Mesh, "CAP_END", {
  31452. /**
  31453. * Mesh cap setting : one cap at the end of the mesh
  31454. */
  31455. get: function () {
  31456. return Mesh._CAP_END;
  31457. },
  31458. enumerable: true,
  31459. configurable: true
  31460. });
  31461. Object.defineProperty(Mesh, "CAP_ALL", {
  31462. /**
  31463. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31464. */
  31465. get: function () {
  31466. return Mesh._CAP_ALL;
  31467. },
  31468. enumerable: true,
  31469. configurable: true
  31470. });
  31471. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31472. set: function (callback) {
  31473. if (this._onBeforeDrawObserver) {
  31474. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31475. }
  31476. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31477. },
  31478. enumerable: true,
  31479. configurable: true
  31480. });
  31481. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31482. get: function () {
  31483. return this._morphTargetManager;
  31484. },
  31485. set: function (value) {
  31486. if (this._morphTargetManager === value) {
  31487. return;
  31488. }
  31489. this._morphTargetManager = value;
  31490. this._syncGeometryWithMorphTargetManager();
  31491. },
  31492. enumerable: true,
  31493. configurable: true
  31494. });
  31495. Object.defineProperty(Mesh.prototype, "source", {
  31496. get: function () {
  31497. return this._source;
  31498. },
  31499. enumerable: true,
  31500. configurable: true
  31501. });
  31502. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31503. get: function () {
  31504. return this._unIndexed;
  31505. },
  31506. set: function (value) {
  31507. if (this._unIndexed !== value) {
  31508. this._unIndexed = value;
  31509. this._markSubMeshesAsAttributesDirty();
  31510. }
  31511. },
  31512. enumerable: true,
  31513. configurable: true
  31514. });
  31515. // Methods
  31516. /**
  31517. * Returns the string "Mesh".
  31518. */
  31519. Mesh.prototype.getClassName = function () {
  31520. return "Mesh";
  31521. };
  31522. /**
  31523. * Returns a string.
  31524. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31525. */
  31526. Mesh.prototype.toString = function (fullDetails) {
  31527. var ret = _super.prototype.toString.call(this, fullDetails);
  31528. ret += ", n vertices: " + this.getTotalVertices();
  31529. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31530. if (this.animations) {
  31531. for (var i = 0; i < this.animations.length; i++) {
  31532. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31533. }
  31534. }
  31535. if (fullDetails) {
  31536. if (this._geometry) {
  31537. var ib = this.getIndices();
  31538. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31539. if (vb && ib) {
  31540. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31541. }
  31542. }
  31543. else {
  31544. ret += ", flat shading: UNKNOWN";
  31545. }
  31546. }
  31547. return ret;
  31548. };
  31549. Mesh.prototype._unBindEffect = function () {
  31550. _super.prototype._unBindEffect.call(this);
  31551. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31552. var instance = _a[_i];
  31553. instance._unBindEffect();
  31554. }
  31555. };
  31556. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31557. /**
  31558. * True if the mesh has some Levels Of Details (LOD).
  31559. * Returns a boolean.
  31560. */
  31561. get: function () {
  31562. return this._LODLevels.length > 0;
  31563. },
  31564. enumerable: true,
  31565. configurable: true
  31566. });
  31567. /**
  31568. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31569. * @returns an array of {BABYLON.MeshLODLevel}
  31570. */
  31571. Mesh.prototype.getLODLevels = function () {
  31572. return this._LODLevels;
  31573. };
  31574. Mesh.prototype._sortLODLevels = function () {
  31575. this._LODLevels.sort(function (a, b) {
  31576. if (a.distance < b.distance) {
  31577. return 1;
  31578. }
  31579. if (a.distance > b.distance) {
  31580. return -1;
  31581. }
  31582. return 0;
  31583. });
  31584. };
  31585. /**
  31586. * Add a mesh as LOD level triggered at the given distance.
  31587. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31588. * @param distance The distance from the center of the object to show this level
  31589. * @param mesh The mesh to be added as LOD level (can be null)
  31590. * @return This mesh (for chaining)
  31591. */
  31592. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31593. if (mesh && mesh._masterMesh) {
  31594. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31595. return this;
  31596. }
  31597. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31598. this._LODLevels.push(level);
  31599. if (mesh) {
  31600. mesh._masterMesh = this;
  31601. }
  31602. this._sortLODLevels();
  31603. return this;
  31604. };
  31605. /**
  31606. * Returns the LOD level mesh at the passed distance or null if not found.
  31607. * It is related to the method `addLODLevel(distance, mesh)`.
  31608. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31609. * Returns an object Mesh or `null`.
  31610. */
  31611. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31612. for (var index = 0; index < this._LODLevels.length; index++) {
  31613. var level = this._LODLevels[index];
  31614. if (level.distance === distance) {
  31615. return level.mesh;
  31616. }
  31617. }
  31618. return null;
  31619. };
  31620. /**
  31621. * Remove a mesh from the LOD array
  31622. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31623. * @param {Mesh} mesh The mesh to be removed.
  31624. * @return {Mesh} This mesh (for chaining)
  31625. */
  31626. Mesh.prototype.removeLODLevel = function (mesh) {
  31627. for (var index = 0; index < this._LODLevels.length; index++) {
  31628. if (this._LODLevels[index].mesh === mesh) {
  31629. this._LODLevels.splice(index, 1);
  31630. if (mesh) {
  31631. mesh._masterMesh = null;
  31632. }
  31633. }
  31634. }
  31635. this._sortLODLevels();
  31636. return this;
  31637. };
  31638. /**
  31639. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31640. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31641. */
  31642. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31643. if (!this._LODLevels || this._LODLevels.length === 0) {
  31644. return this;
  31645. }
  31646. var bSphere;
  31647. if (boundingSphere) {
  31648. bSphere = boundingSphere;
  31649. }
  31650. else {
  31651. var boundingInfo = this.getBoundingInfo();
  31652. bSphere = boundingInfo.boundingSphere;
  31653. }
  31654. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31655. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31656. if (this.onLODLevelSelection) {
  31657. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31658. }
  31659. return this;
  31660. }
  31661. for (var index = 0; index < this._LODLevels.length; index++) {
  31662. var level = this._LODLevels[index];
  31663. if (level.distance < distanceToCamera) {
  31664. if (level.mesh) {
  31665. level.mesh._preActivate();
  31666. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31667. }
  31668. if (this.onLODLevelSelection) {
  31669. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31670. }
  31671. return level.mesh;
  31672. }
  31673. }
  31674. if (this.onLODLevelSelection) {
  31675. this.onLODLevelSelection(distanceToCamera, this, this);
  31676. }
  31677. return this;
  31678. };
  31679. Object.defineProperty(Mesh.prototype, "geometry", {
  31680. /**
  31681. * Returns the mesh internal Geometry object.
  31682. */
  31683. get: function () {
  31684. return this._geometry;
  31685. },
  31686. enumerable: true,
  31687. configurable: true
  31688. });
  31689. /**
  31690. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31691. */
  31692. Mesh.prototype.getTotalVertices = function () {
  31693. if (this._geometry === null || this._geometry === undefined) {
  31694. return 0;
  31695. }
  31696. return this._geometry.getTotalVertices();
  31697. };
  31698. /**
  31699. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31700. * 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.
  31701. * You can force the copy with forceCopy === true
  31702. * Returns null if the mesh has no geometry or no vertex buffer.
  31703. * Possible `kind` values :
  31704. * - BABYLON.VertexBuffer.PositionKind
  31705. * - BABYLON.VertexBuffer.UVKind
  31706. * - BABYLON.VertexBuffer.UV2Kind
  31707. * - BABYLON.VertexBuffer.UV3Kind
  31708. * - BABYLON.VertexBuffer.UV4Kind
  31709. * - BABYLON.VertexBuffer.UV5Kind
  31710. * - BABYLON.VertexBuffer.UV6Kind
  31711. * - BABYLON.VertexBuffer.ColorKind
  31712. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31713. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31714. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31715. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31716. */
  31717. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31718. if (!this._geometry) {
  31719. return null;
  31720. }
  31721. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31722. };
  31723. /**
  31724. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31725. * Returns `null` if the mesh has no geometry.
  31726. * Possible `kind` values :
  31727. * - BABYLON.VertexBuffer.PositionKind
  31728. * - BABYLON.VertexBuffer.UVKind
  31729. * - BABYLON.VertexBuffer.UV2Kind
  31730. * - BABYLON.VertexBuffer.UV3Kind
  31731. * - BABYLON.VertexBuffer.UV4Kind
  31732. * - BABYLON.VertexBuffer.UV5Kind
  31733. * - BABYLON.VertexBuffer.UV6Kind
  31734. * - BABYLON.VertexBuffer.ColorKind
  31735. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31736. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31737. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31738. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31739. */
  31740. Mesh.prototype.getVertexBuffer = function (kind) {
  31741. if (!this._geometry) {
  31742. return null;
  31743. }
  31744. return this._geometry.getVertexBuffer(kind);
  31745. };
  31746. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31747. if (!this._geometry) {
  31748. if (this._delayInfo) {
  31749. return this._delayInfo.indexOf(kind) !== -1;
  31750. }
  31751. return false;
  31752. }
  31753. return this._geometry.isVerticesDataPresent(kind);
  31754. };
  31755. /**
  31756. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31757. * Possible `kind` values :
  31758. * - BABYLON.VertexBuffer.PositionKind
  31759. * - BABYLON.VertexBuffer.UVKind
  31760. * - BABYLON.VertexBuffer.UV2Kind
  31761. * - BABYLON.VertexBuffer.UV3Kind
  31762. * - BABYLON.VertexBuffer.UV4Kind
  31763. * - BABYLON.VertexBuffer.UV5Kind
  31764. * - BABYLON.VertexBuffer.UV6Kind
  31765. * - BABYLON.VertexBuffer.ColorKind
  31766. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31767. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31768. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31769. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31770. */
  31771. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31772. if (!this._geometry) {
  31773. if (this._delayInfo) {
  31774. return this._delayInfo.indexOf(kind) !== -1;
  31775. }
  31776. return false;
  31777. }
  31778. return this._geometry.isVertexBufferUpdatable(kind);
  31779. };
  31780. /**
  31781. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31782. * Possible `kind` values :
  31783. * - BABYLON.VertexBuffer.PositionKind
  31784. * - BABYLON.VertexBuffer.UVKind
  31785. * - BABYLON.VertexBuffer.UV2Kind
  31786. * - BABYLON.VertexBuffer.UV3Kind
  31787. * - BABYLON.VertexBuffer.UV4Kind
  31788. * - BABYLON.VertexBuffer.UV5Kind
  31789. * - BABYLON.VertexBuffer.UV6Kind
  31790. * - BABYLON.VertexBuffer.ColorKind
  31791. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31792. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31793. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31794. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31795. */
  31796. Mesh.prototype.getVerticesDataKinds = function () {
  31797. if (!this._geometry) {
  31798. var result = new Array();
  31799. if (this._delayInfo) {
  31800. this._delayInfo.forEach(function (kind, index, array) {
  31801. result.push(kind);
  31802. });
  31803. }
  31804. return result;
  31805. }
  31806. return this._geometry.getVerticesDataKinds();
  31807. };
  31808. /**
  31809. * Returns a positive integer : the total number of indices in this mesh geometry.
  31810. * Returns zero if the mesh has no geometry.
  31811. */
  31812. Mesh.prototype.getTotalIndices = function () {
  31813. if (!this._geometry) {
  31814. return 0;
  31815. }
  31816. return this._geometry.getTotalIndices();
  31817. };
  31818. /**
  31819. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31820. * 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.
  31821. * Returns an empty array if the mesh has no geometry.
  31822. */
  31823. Mesh.prototype.getIndices = function (copyWhenShared) {
  31824. if (!this._geometry) {
  31825. return [];
  31826. }
  31827. return this._geometry.getIndices(copyWhenShared);
  31828. };
  31829. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31830. get: function () {
  31831. return this._masterMesh !== null && this._masterMesh !== undefined;
  31832. },
  31833. enumerable: true,
  31834. configurable: true
  31835. });
  31836. /**
  31837. * Determine if the current mesh is ready to be rendered
  31838. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31839. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31840. * @returns true if all associated assets are ready (material, textures, shaders)
  31841. */
  31842. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31843. if (completeCheck === void 0) { completeCheck = false; }
  31844. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31845. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31846. return false;
  31847. }
  31848. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31849. return false;
  31850. }
  31851. if (!this.subMeshes || this.subMeshes.length === 0) {
  31852. return true;
  31853. }
  31854. if (!completeCheck) {
  31855. return true;
  31856. }
  31857. var engine = this.getEngine();
  31858. var scene = this.getScene();
  31859. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31860. this.computeWorldMatrix();
  31861. var mat = this.material || scene.defaultMaterial;
  31862. if (mat) {
  31863. if (mat.storeEffectOnSubMeshes) {
  31864. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31865. var subMesh = _a[_i];
  31866. var effectiveMaterial = subMesh.getMaterial();
  31867. if (effectiveMaterial) {
  31868. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31869. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31870. return false;
  31871. }
  31872. }
  31873. else {
  31874. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31875. return false;
  31876. }
  31877. }
  31878. }
  31879. }
  31880. }
  31881. else {
  31882. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31883. return false;
  31884. }
  31885. }
  31886. }
  31887. // Shadows
  31888. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31889. var light = _c[_b];
  31890. var generator = light.getShadowGenerator();
  31891. if (generator) {
  31892. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31893. var subMesh = _e[_d];
  31894. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31895. return false;
  31896. }
  31897. }
  31898. }
  31899. }
  31900. // LOD
  31901. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31902. var lod = _g[_f];
  31903. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31904. return false;
  31905. }
  31906. }
  31907. return true;
  31908. };
  31909. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31910. /**
  31911. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31912. * This property is pertinent only for updatable parametric shapes.
  31913. */
  31914. get: function () {
  31915. return this._areNormalsFrozen;
  31916. },
  31917. enumerable: true,
  31918. configurable: true
  31919. });
  31920. /**
  31921. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31922. * It has no effect at all on other shapes.
  31923. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31924. * Returns the Mesh.
  31925. */
  31926. Mesh.prototype.freezeNormals = function () {
  31927. this._areNormalsFrozen = true;
  31928. return this;
  31929. };
  31930. /**
  31931. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31932. * It has no effect at all on other shapes.
  31933. * It reactivates the mesh normals computation if it was previously frozen.
  31934. * Returns the Mesh.
  31935. */
  31936. Mesh.prototype.unfreezeNormals = function () {
  31937. this._areNormalsFrozen = false;
  31938. return this;
  31939. };
  31940. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31941. /**
  31942. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31943. */
  31944. set: function (count) {
  31945. this._overridenInstanceCount = count;
  31946. },
  31947. enumerable: true,
  31948. configurable: true
  31949. });
  31950. // Methods
  31951. Mesh.prototype._preActivate = function () {
  31952. var sceneRenderId = this.getScene().getRenderId();
  31953. if (this._preActivateId === sceneRenderId) {
  31954. return this;
  31955. }
  31956. this._preActivateId = sceneRenderId;
  31957. this._visibleInstances = null;
  31958. return this;
  31959. };
  31960. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31961. if (this._visibleInstances) {
  31962. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31963. }
  31964. return this;
  31965. };
  31966. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31967. if (!this._visibleInstances) {
  31968. this._visibleInstances = {};
  31969. this._visibleInstances.defaultRenderId = renderId;
  31970. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31971. }
  31972. if (!this._visibleInstances[renderId]) {
  31973. this._visibleInstances[renderId] = new Array();
  31974. }
  31975. this._visibleInstances[renderId].push(instance);
  31976. return this;
  31977. };
  31978. /**
  31979. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31980. * This means the mesh underlying bounding box and sphere are recomputed.
  31981. * Returns the Mesh.
  31982. */
  31983. Mesh.prototype.refreshBoundingInfo = function () {
  31984. return this._refreshBoundingInfo(false);
  31985. };
  31986. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31987. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31988. return this;
  31989. }
  31990. var data = this._getPositionData(applySkeleton);
  31991. if (data) {
  31992. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31993. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31994. }
  31995. if (this.subMeshes) {
  31996. for (var index = 0; index < this.subMeshes.length; index++) {
  31997. this.subMeshes[index].refreshBoundingInfo();
  31998. }
  31999. }
  32000. this._updateBoundingInfo();
  32001. return this;
  32002. };
  32003. Mesh.prototype._getPositionData = function (applySkeleton) {
  32004. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32005. if (data && applySkeleton && this.skeleton) {
  32006. data = BABYLON.Tools.Slice(data);
  32007. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32008. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32009. if (matricesWeightsData && matricesIndicesData) {
  32010. var needExtras = this.numBoneInfluencers > 4;
  32011. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32012. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32013. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32014. var tempVector = BABYLON.Tmp.Vector3[0];
  32015. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32016. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32017. var matWeightIdx = 0;
  32018. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32019. finalMatrix.reset();
  32020. var inf;
  32021. var weight;
  32022. for (inf = 0; inf < 4; inf++) {
  32023. weight = matricesWeightsData[matWeightIdx + inf];
  32024. if (weight > 0) {
  32025. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32026. finalMatrix.addToSelf(tempMatrix);
  32027. }
  32028. }
  32029. if (needExtras) {
  32030. for (inf = 0; inf < 4; inf++) {
  32031. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32032. if (weight > 0) {
  32033. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32034. finalMatrix.addToSelf(tempMatrix);
  32035. }
  32036. }
  32037. }
  32038. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32039. tempVector.toArray(data, index);
  32040. }
  32041. }
  32042. }
  32043. return data;
  32044. };
  32045. Mesh.prototype._createGlobalSubMesh = function (force) {
  32046. var totalVertices = this.getTotalVertices();
  32047. if (!totalVertices || !this.getIndices()) {
  32048. return null;
  32049. }
  32050. // Check if we need to recreate the submeshes
  32051. if (this.subMeshes && this.subMeshes.length > 0) {
  32052. var ib = this.getIndices();
  32053. if (!ib) {
  32054. return null;
  32055. }
  32056. var totalIndices = ib.length;
  32057. var needToRecreate = false;
  32058. if (force) {
  32059. needToRecreate = true;
  32060. }
  32061. else {
  32062. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32063. var submesh = _a[_i];
  32064. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32065. needToRecreate = true;
  32066. break;
  32067. }
  32068. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32069. needToRecreate = true;
  32070. break;
  32071. }
  32072. }
  32073. }
  32074. if (!needToRecreate) {
  32075. return this.subMeshes[0];
  32076. }
  32077. }
  32078. this.releaseSubMeshes();
  32079. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32080. };
  32081. Mesh.prototype.subdivide = function (count) {
  32082. if (count < 1) {
  32083. return;
  32084. }
  32085. var totalIndices = this.getTotalIndices();
  32086. var subdivisionSize = (totalIndices / count) | 0;
  32087. var offset = 0;
  32088. // Ensure that subdivisionSize is a multiple of 3
  32089. while (subdivisionSize % 3 !== 0) {
  32090. subdivisionSize++;
  32091. }
  32092. this.releaseSubMeshes();
  32093. for (var index = 0; index < count; index++) {
  32094. if (offset >= totalIndices) {
  32095. break;
  32096. }
  32097. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32098. offset += subdivisionSize;
  32099. }
  32100. this.synchronizeInstances();
  32101. };
  32102. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32103. if (updatable === void 0) { updatable = false; }
  32104. if (!this._geometry) {
  32105. var vertexData = new BABYLON.VertexData();
  32106. vertexData.set(data, kind);
  32107. var scene = this.getScene();
  32108. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32109. }
  32110. else {
  32111. this._geometry.setVerticesData(kind, data, updatable, stride);
  32112. }
  32113. return this;
  32114. };
  32115. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32116. if (updatable === void 0) { updatable = true; }
  32117. var vb = this.getVertexBuffer(kind);
  32118. if (!vb || vb.isUpdatable() === updatable) {
  32119. return;
  32120. }
  32121. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32122. };
  32123. /**
  32124. * Sets the mesh VertexBuffer.
  32125. * Returns the Mesh.
  32126. */
  32127. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32128. if (!this._geometry) {
  32129. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32130. }
  32131. this._geometry.setVerticesBuffer(buffer);
  32132. return this;
  32133. };
  32134. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32135. if (!this._geometry) {
  32136. return this;
  32137. }
  32138. if (!makeItUnique) {
  32139. this._geometry.updateVerticesData(kind, data, updateExtends);
  32140. }
  32141. else {
  32142. this.makeGeometryUnique();
  32143. this.updateVerticesData(kind, data, updateExtends, false);
  32144. }
  32145. return this;
  32146. };
  32147. /**
  32148. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32149. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32150. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32151. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32152. * Returns the Mesh.
  32153. */
  32154. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32155. if (computeNormals === void 0) { computeNormals = true; }
  32156. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32157. if (!positions) {
  32158. return this;
  32159. }
  32160. positionFunction(positions);
  32161. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32162. if (computeNormals) {
  32163. var indices = this.getIndices();
  32164. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32165. if (!normals) {
  32166. return this;
  32167. }
  32168. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32169. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32170. }
  32171. return this;
  32172. };
  32173. /**
  32174. * Creates a un-shared specific occurence of the geometry for the mesh.
  32175. * Returns the Mesh.
  32176. */
  32177. Mesh.prototype.makeGeometryUnique = function () {
  32178. if (!this._geometry) {
  32179. return this;
  32180. }
  32181. var oldGeometry = this._geometry;
  32182. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32183. oldGeometry.releaseForMesh(this, true);
  32184. geometry.applyToMesh(this);
  32185. return this;
  32186. };
  32187. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32188. if (totalVertices === void 0) { totalVertices = null; }
  32189. if (updatable === void 0) { updatable = false; }
  32190. if (!this._geometry) {
  32191. var vertexData = new BABYLON.VertexData();
  32192. vertexData.indices = indices;
  32193. var scene = this.getScene();
  32194. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32195. }
  32196. else {
  32197. this._geometry.setIndices(indices, totalVertices, updatable);
  32198. }
  32199. return this;
  32200. };
  32201. /**
  32202. * Update the current index buffer
  32203. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32204. * Returns the Mesh.
  32205. */
  32206. Mesh.prototype.updateIndices = function (indices, offset) {
  32207. if (!this._geometry) {
  32208. return this;
  32209. }
  32210. this._geometry.updateIndices(indices, offset);
  32211. return this;
  32212. };
  32213. /**
  32214. * Invert the geometry to move from a right handed system to a left handed one.
  32215. * Returns the Mesh.
  32216. */
  32217. Mesh.prototype.toLeftHanded = function () {
  32218. if (!this._geometry) {
  32219. return this;
  32220. }
  32221. this._geometry.toLeftHanded();
  32222. return this;
  32223. };
  32224. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32225. if (!this._geometry) {
  32226. return this;
  32227. }
  32228. var engine = this.getScene().getEngine();
  32229. // Wireframe
  32230. var indexToBind;
  32231. if (this._unIndexed) {
  32232. indexToBind = null;
  32233. }
  32234. else {
  32235. switch (fillMode) {
  32236. case BABYLON.Material.PointFillMode:
  32237. indexToBind = null;
  32238. break;
  32239. case BABYLON.Material.WireFrameFillMode:
  32240. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32241. break;
  32242. default:
  32243. case BABYLON.Material.TriangleFillMode:
  32244. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32245. break;
  32246. }
  32247. }
  32248. // VBOs
  32249. this._geometry._bind(effect, indexToBind);
  32250. return this;
  32251. };
  32252. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32253. if (alternate === void 0) { alternate = false; }
  32254. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32255. return this;
  32256. }
  32257. this.onBeforeDrawObservable.notifyObservers(this);
  32258. var scene = this.getScene();
  32259. var engine = scene.getEngine();
  32260. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32261. // or triangles as points
  32262. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32263. }
  32264. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32265. // Triangles as wireframe
  32266. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32267. }
  32268. else {
  32269. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32270. }
  32271. if (scene._isAlternateRenderingEnabled && !alternate) {
  32272. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32273. if (!effect || !scene.activeCamera) {
  32274. return this;
  32275. }
  32276. scene._switchToAlternateCameraConfiguration(true);
  32277. this._effectiveMaterial.bindView(effect);
  32278. this._effectiveMaterial.bindViewProjection(effect);
  32279. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32280. this._draw(subMesh, fillMode, instancesCount, true);
  32281. engine.setViewport(scene.activeCamera.viewport);
  32282. scene._switchToAlternateCameraConfiguration(false);
  32283. this._effectiveMaterial.bindView(effect);
  32284. this._effectiveMaterial.bindViewProjection(effect);
  32285. }
  32286. return this;
  32287. };
  32288. /**
  32289. * Registers for this mesh a javascript function called just before the rendering process.
  32290. * This function is passed the current mesh.
  32291. * Return the Mesh.
  32292. */
  32293. Mesh.prototype.registerBeforeRender = function (func) {
  32294. this.onBeforeRenderObservable.add(func);
  32295. return this;
  32296. };
  32297. /**
  32298. * Disposes a previously registered javascript function called before the rendering.
  32299. * This function is passed the current mesh.
  32300. * Returns the Mesh.
  32301. */
  32302. Mesh.prototype.unregisterBeforeRender = function (func) {
  32303. this.onBeforeRenderObservable.removeCallback(func);
  32304. return this;
  32305. };
  32306. /**
  32307. * Registers for this mesh a javascript function called just after the rendering is complete.
  32308. * This function is passed the current mesh.
  32309. * Returns the Mesh.
  32310. */
  32311. Mesh.prototype.registerAfterRender = function (func) {
  32312. this.onAfterRenderObservable.add(func);
  32313. return this;
  32314. };
  32315. /**
  32316. * Disposes a previously registered javascript function called after the rendering.
  32317. * This function is passed the current mesh.
  32318. * Return the Mesh.
  32319. */
  32320. Mesh.prototype.unregisterAfterRender = function (func) {
  32321. this.onAfterRenderObservable.removeCallback(func);
  32322. return this;
  32323. };
  32324. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32325. var scene = this.getScene();
  32326. this._batchCache.mustReturn = false;
  32327. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32328. this._batchCache.visibleInstances[subMeshId] = null;
  32329. if (this._visibleInstances) {
  32330. var currentRenderId = scene.getRenderId();
  32331. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32332. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32333. var selfRenderId = this._renderId;
  32334. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32335. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32336. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32337. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32338. }
  32339. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32340. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32341. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32342. this._batchCache.mustReturn = true;
  32343. return this._batchCache;
  32344. }
  32345. if (currentRenderId !== selfRenderId) {
  32346. this._batchCache.renderSelf[subMeshId] = false;
  32347. }
  32348. }
  32349. this._renderIdForInstances[subMeshId] = currentRenderId;
  32350. }
  32351. return this._batchCache;
  32352. };
  32353. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32354. var visibleInstances = batch.visibleInstances[subMesh._id];
  32355. if (!visibleInstances) {
  32356. return this;
  32357. }
  32358. var matricesCount = visibleInstances.length + 1;
  32359. var bufferSize = matricesCount * 16 * 4;
  32360. var currentInstancesBufferSize = this._instancesBufferSize;
  32361. var instancesBuffer = this._instancesBuffer;
  32362. while (this._instancesBufferSize < bufferSize) {
  32363. this._instancesBufferSize *= 2;
  32364. }
  32365. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32366. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32367. }
  32368. var offset = 0;
  32369. var instancesCount = 0;
  32370. var world = this.getWorldMatrix();
  32371. if (batch.renderSelf[subMesh._id]) {
  32372. world.copyToArray(this._instancesData, offset);
  32373. offset += 16;
  32374. instancesCount++;
  32375. }
  32376. if (visibleInstances) {
  32377. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32378. var instance = visibleInstances[instanceIndex];
  32379. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32380. offset += 16;
  32381. instancesCount++;
  32382. }
  32383. }
  32384. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32385. if (instancesBuffer) {
  32386. instancesBuffer.dispose();
  32387. }
  32388. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32389. this._instancesBuffer = instancesBuffer;
  32390. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32391. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32392. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32393. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32394. }
  32395. else {
  32396. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32397. }
  32398. this._bind(subMesh, effect, fillMode);
  32399. this._draw(subMesh, fillMode, instancesCount);
  32400. engine.unbindInstanceAttributes();
  32401. return this;
  32402. };
  32403. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32404. var scene = this.getScene();
  32405. var engine = scene.getEngine();
  32406. if (hardwareInstancedRendering) {
  32407. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32408. }
  32409. else {
  32410. if (batch.renderSelf[subMesh._id]) {
  32411. // Draw
  32412. if (onBeforeDraw) {
  32413. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32414. }
  32415. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32416. }
  32417. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32418. if (visibleInstancesForSubMesh) {
  32419. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32420. var instance = visibleInstancesForSubMesh[instanceIndex];
  32421. // World
  32422. var world = instance.getWorldMatrix();
  32423. if (onBeforeDraw) {
  32424. onBeforeDraw(true, world, effectiveMaterial);
  32425. }
  32426. // Draw
  32427. this._draw(subMesh, fillMode);
  32428. }
  32429. }
  32430. }
  32431. return this;
  32432. };
  32433. /**
  32434. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32435. * @param subMesh defines the subMesh to render
  32436. * @param enableAlphaMode defines if alpha mode can be changed
  32437. * @returns the current mesh
  32438. */
  32439. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32440. this._checkOcclusionQuery();
  32441. if (this._isOccluded) {
  32442. return this;
  32443. }
  32444. var scene = this.getScene();
  32445. // Managing instances
  32446. var batch = this._getInstancesRenderList(subMesh._id);
  32447. if (batch.mustReturn) {
  32448. return this;
  32449. }
  32450. // Checking geometry state
  32451. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32452. return this;
  32453. }
  32454. this.onBeforeRenderObservable.notifyObservers(this);
  32455. var engine = scene.getEngine();
  32456. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32457. // Material
  32458. var material = subMesh.getMaterial();
  32459. if (!material) {
  32460. return this;
  32461. }
  32462. this._effectiveMaterial = material;
  32463. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32464. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32465. return this;
  32466. }
  32467. }
  32468. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32469. return this;
  32470. }
  32471. // Alpha mode
  32472. if (enableAlphaMode) {
  32473. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32474. }
  32475. // Outline - step 1
  32476. var savedDepthWrite = engine.getDepthWrite();
  32477. if (this.renderOutline) {
  32478. engine.setDepthWrite(false);
  32479. scene.getOutlineRenderer().render(subMesh, batch);
  32480. engine.setDepthWrite(savedDepthWrite);
  32481. }
  32482. var effect;
  32483. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32484. effect = subMesh.effect;
  32485. }
  32486. else {
  32487. effect = this._effectiveMaterial.getEffect();
  32488. }
  32489. if (!effect) {
  32490. return this;
  32491. }
  32492. var sideOrientation = this.overrideMaterialSideOrientation;
  32493. if (sideOrientation == null) {
  32494. sideOrientation = this._effectiveMaterial.sideOrientation;
  32495. if (this._getWorldMatrixDeterminant() < 0) {
  32496. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32497. }
  32498. }
  32499. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32500. if (this._effectiveMaterial.forceDepthWrite) {
  32501. engine.setDepthWrite(true);
  32502. }
  32503. // Bind
  32504. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32505. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32506. this._bind(subMesh, effect, fillMode);
  32507. }
  32508. var world = this.getWorldMatrix();
  32509. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32510. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32511. }
  32512. else {
  32513. this._effectiveMaterial.bind(world, this);
  32514. }
  32515. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32516. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32517. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32518. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32519. }
  32520. // Draw
  32521. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32522. // Unbind
  32523. this._effectiveMaterial.unbind();
  32524. // Outline - step 2
  32525. if (this.renderOutline && savedDepthWrite) {
  32526. engine.setDepthWrite(true);
  32527. engine.setColorWrite(false);
  32528. scene.getOutlineRenderer().render(subMesh, batch);
  32529. engine.setColorWrite(true);
  32530. }
  32531. // Overlay
  32532. if (this.renderOverlay) {
  32533. var currentMode = engine.getAlphaMode();
  32534. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32535. scene.getOutlineRenderer().render(subMesh, batch, true);
  32536. engine.setAlphaMode(currentMode);
  32537. }
  32538. this.onAfterRenderObservable.notifyObservers(this);
  32539. return this;
  32540. };
  32541. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32542. if (isInstance && effectiveMaterial) {
  32543. effectiveMaterial.bindOnlyWorldMatrix(world);
  32544. }
  32545. };
  32546. /**
  32547. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32548. */
  32549. Mesh.prototype.getEmittedParticleSystems = function () {
  32550. var results = new Array();
  32551. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32552. var particleSystem = this.getScene().particleSystems[index];
  32553. if (particleSystem.emitter === this) {
  32554. results.push(particleSystem);
  32555. }
  32556. }
  32557. return results;
  32558. };
  32559. /**
  32560. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32561. */
  32562. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32563. var results = new Array();
  32564. var descendants = this.getDescendants();
  32565. descendants.push(this);
  32566. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32567. var particleSystem = this.getScene().particleSystems[index];
  32568. var emitter = particleSystem.emitter;
  32569. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32570. results.push(particleSystem);
  32571. }
  32572. }
  32573. return results;
  32574. };
  32575. /**
  32576. * Normalize matrix weights so that all vertices have a total weight set to 1
  32577. */
  32578. Mesh.prototype.cleanMatrixWeights = function () {
  32579. var epsilon = 1e-3;
  32580. var noInfluenceBoneIndex = 0.0;
  32581. if (this.skeleton) {
  32582. noInfluenceBoneIndex = this.skeleton.bones.length;
  32583. }
  32584. else {
  32585. return;
  32586. }
  32587. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32588. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32589. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32590. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32591. var influencers = this.numBoneInfluencers;
  32592. var size = matricesWeights.length;
  32593. for (var i = 0; i < size; i += 4) {
  32594. var weight = 0.0;
  32595. var firstZeroWeight = -1;
  32596. for (var j = 0; j < 4; j++) {
  32597. var w = matricesWeights[i + j];
  32598. weight += w;
  32599. if (w < epsilon && firstZeroWeight < 0) {
  32600. firstZeroWeight = j;
  32601. }
  32602. }
  32603. if (matricesWeightsExtra) {
  32604. for (var j = 0; j < 4; j++) {
  32605. var w = matricesWeightsExtra[i + j];
  32606. weight += w;
  32607. if (w < epsilon && firstZeroWeight < 0) {
  32608. firstZeroWeight = j + 4;
  32609. }
  32610. }
  32611. }
  32612. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32613. firstZeroWeight = influencers - 1;
  32614. }
  32615. if (weight > epsilon) {
  32616. var mweight = 1.0 / weight;
  32617. for (var j = 0; j < 4; j++) {
  32618. matricesWeights[i + j] *= mweight;
  32619. }
  32620. if (matricesWeightsExtra) {
  32621. for (var j = 0; j < 4; j++) {
  32622. matricesWeightsExtra[i + j] *= mweight;
  32623. }
  32624. }
  32625. }
  32626. else {
  32627. if (firstZeroWeight >= 4) {
  32628. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32629. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32630. }
  32631. else {
  32632. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32633. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32634. }
  32635. }
  32636. }
  32637. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32638. if (matricesIndicesExtra) {
  32639. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32640. }
  32641. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32642. if (matricesWeightsExtra) {
  32643. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32644. }
  32645. };
  32646. Mesh.prototype._checkDelayState = function () {
  32647. var scene = this.getScene();
  32648. if (this._geometry) {
  32649. this._geometry.load(scene);
  32650. }
  32651. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32652. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32653. this._queueLoad(scene);
  32654. }
  32655. return this;
  32656. };
  32657. Mesh.prototype._queueLoad = function (scene) {
  32658. var _this = this;
  32659. scene._addPendingData(this);
  32660. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32661. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32662. if (data instanceof ArrayBuffer) {
  32663. _this._delayLoadingFunction(data, _this);
  32664. }
  32665. else {
  32666. _this._delayLoadingFunction(JSON.parse(data), _this);
  32667. }
  32668. _this.instances.forEach(function (instance) {
  32669. instance._syncSubMeshes();
  32670. });
  32671. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32672. scene._removePendingData(_this);
  32673. }, function () { }, scene.database, getBinaryData);
  32674. return this;
  32675. };
  32676. /**
  32677. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32678. */
  32679. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32680. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32681. return false;
  32682. }
  32683. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32684. return false;
  32685. }
  32686. this._checkDelayState();
  32687. return true;
  32688. };
  32689. /**
  32690. * Sets the mesh material by the material or multiMaterial `id` property.
  32691. * The material `id` is a string identifying the material or the multiMaterial.
  32692. * This method returns the Mesh.
  32693. */
  32694. Mesh.prototype.setMaterialByID = function (id) {
  32695. var materials = this.getScene().materials;
  32696. var index;
  32697. for (index = materials.length - 1; index > -1; index--) {
  32698. if (materials[index].id === id) {
  32699. this.material = materials[index];
  32700. return this;
  32701. }
  32702. }
  32703. // Multi
  32704. var multiMaterials = this.getScene().multiMaterials;
  32705. for (index = multiMaterials.length - 1; index > -1; index--) {
  32706. if (multiMaterials[index].id === id) {
  32707. this.material = multiMaterials[index];
  32708. return this;
  32709. }
  32710. }
  32711. return this;
  32712. };
  32713. /**
  32714. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32715. */
  32716. Mesh.prototype.getAnimatables = function () {
  32717. var results = new Array();
  32718. if (this.material) {
  32719. results.push(this.material);
  32720. }
  32721. if (this.skeleton) {
  32722. results.push(this.skeleton);
  32723. }
  32724. return results;
  32725. };
  32726. /**
  32727. * Modifies the mesh geometry according to the passed transformation matrix.
  32728. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32729. * The mesh normals are modified accordingly the same transformation.
  32730. * 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.bakeTransformIntoVertices = function (transform) {
  32735. // Position
  32736. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32737. return this;
  32738. }
  32739. var submeshes = this.subMeshes.splice(0);
  32740. this._resetPointsArrayCache();
  32741. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32742. var temp = new Array();
  32743. var index;
  32744. for (index = 0; index < data.length; index += 3) {
  32745. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32746. }
  32747. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32748. // Normals
  32749. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32750. return this;
  32751. }
  32752. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32753. temp = [];
  32754. for (index = 0; index < data.length; index += 3) {
  32755. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32756. }
  32757. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32758. // flip faces?
  32759. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32760. this.flipFaces();
  32761. }
  32762. // Restore submeshes
  32763. this.releaseSubMeshes();
  32764. this.subMeshes = submeshes;
  32765. return this;
  32766. };
  32767. /**
  32768. * Modifies the mesh geometry according to its own current World Matrix.
  32769. * The mesh World Matrix is then reset.
  32770. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32771. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32772. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32773. * Returns the Mesh.
  32774. */
  32775. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32776. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32777. this.scaling.copyFromFloats(1, 1, 1);
  32778. this.position.copyFromFloats(0, 0, 0);
  32779. this.rotation.copyFromFloats(0, 0, 0);
  32780. //only if quaternion is already set
  32781. if (this.rotationQuaternion) {
  32782. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32783. }
  32784. this._worldMatrix = BABYLON.Matrix.Identity();
  32785. return this;
  32786. };
  32787. Object.defineProperty(Mesh.prototype, "_positions", {
  32788. // Cache
  32789. get: function () {
  32790. if (this._geometry) {
  32791. return this._geometry._positions;
  32792. }
  32793. return null;
  32794. },
  32795. enumerable: true,
  32796. configurable: true
  32797. });
  32798. Mesh.prototype._resetPointsArrayCache = function () {
  32799. if (this._geometry) {
  32800. this._geometry._resetPointsArrayCache();
  32801. }
  32802. return this;
  32803. };
  32804. Mesh.prototype._generatePointsArray = function () {
  32805. if (this._geometry) {
  32806. return this._geometry._generatePointsArray();
  32807. }
  32808. return false;
  32809. };
  32810. /**
  32811. * Returns a new Mesh object generated from the current mesh properties.
  32812. * This method must not get confused with createInstance().
  32813. * The parameter `name` is a string, the name given to the new mesh.
  32814. * The optional parameter `newParent` can be any Node object (default `null`).
  32815. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32816. * 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.
  32817. */
  32818. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32819. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32820. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32821. };
  32822. /**
  32823. * Releases resources associated with this mesh.
  32824. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32825. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32826. */
  32827. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32828. var _this = this;
  32829. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32830. this.morphTargetManager = null;
  32831. if (this._geometry) {
  32832. this._geometry.releaseForMesh(this, true);
  32833. }
  32834. // Sources
  32835. var meshes = this.getScene().meshes;
  32836. meshes.forEach(function (abstractMesh) {
  32837. var mesh = abstractMesh;
  32838. if (mesh._source && mesh._source === _this) {
  32839. mesh._source = null;
  32840. }
  32841. });
  32842. this._source = null;
  32843. // Instances
  32844. if (this._instancesBuffer) {
  32845. this._instancesBuffer.dispose();
  32846. this._instancesBuffer = null;
  32847. }
  32848. while (this.instances.length) {
  32849. this.instances[0].dispose();
  32850. }
  32851. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32852. };
  32853. /**
  32854. * Modifies the mesh geometry according to a displacement map.
  32855. * 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.
  32856. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32857. * This method returns nothing.
  32858. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32859. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32860. * 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.
  32861. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32862. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32863. *
  32864. * Returns the Mesh.
  32865. */
  32866. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32867. var _this = this;
  32868. var scene = this.getScene();
  32869. var onload = function (img) {
  32870. // Getting height map data
  32871. var canvas = document.createElement("canvas");
  32872. var context = canvas.getContext("2d");
  32873. var heightMapWidth = img.width;
  32874. var heightMapHeight = img.height;
  32875. canvas.width = heightMapWidth;
  32876. canvas.height = heightMapHeight;
  32877. context.drawImage(img, 0, 0);
  32878. // Create VertexData from map data
  32879. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32880. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32881. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32882. //execute success callback, if set
  32883. if (onSuccess) {
  32884. onSuccess(_this);
  32885. }
  32886. };
  32887. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32888. return this;
  32889. };
  32890. /**
  32891. * Modifies the mesh geometry according to a displacementMap buffer.
  32892. * 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.
  32893. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32894. * This method returns nothing.
  32895. * 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.
  32896. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32897. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32898. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32899. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32900. *
  32901. * Returns the Mesh.
  32902. */
  32903. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32904. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32905. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32906. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32907. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32908. return this;
  32909. }
  32910. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32911. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32912. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32913. var position = BABYLON.Vector3.Zero();
  32914. var normal = BABYLON.Vector3.Zero();
  32915. var uv = BABYLON.Vector2.Zero();
  32916. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32917. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32918. for (var index = 0; index < positions.length; index += 3) {
  32919. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32920. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32921. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32922. // Compute height
  32923. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32924. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32925. var pos = (u + v * heightMapWidth) * 4;
  32926. var r = buffer[pos] / 255.0;
  32927. var g = buffer[pos + 1] / 255.0;
  32928. var b = buffer[pos + 2] / 255.0;
  32929. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32930. normal.normalize();
  32931. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32932. position = position.add(normal);
  32933. position.toArray(positions, index);
  32934. }
  32935. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32936. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32937. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32938. return this;
  32939. };
  32940. /**
  32941. * Modify the mesh to get a flat shading rendering.
  32942. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32943. * This method returns the Mesh.
  32944. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32945. */
  32946. Mesh.prototype.convertToFlatShadedMesh = function () {
  32947. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32948. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32949. var kinds = this.getVerticesDataKinds();
  32950. var vbs = {};
  32951. var data = {};
  32952. var newdata = {};
  32953. var updatableNormals = false;
  32954. var kindIndex;
  32955. var kind;
  32956. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32957. kind = kinds[kindIndex];
  32958. var vertexBuffer = this.getVertexBuffer(kind);
  32959. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32960. updatableNormals = vertexBuffer.isUpdatable();
  32961. kinds.splice(kindIndex, 1);
  32962. kindIndex--;
  32963. continue;
  32964. }
  32965. vbs[kind] = vertexBuffer;
  32966. data[kind] = vbs[kind].getData();
  32967. newdata[kind] = [];
  32968. }
  32969. // Save previous submeshes
  32970. var previousSubmeshes = this.subMeshes.slice(0);
  32971. var indices = this.getIndices();
  32972. var totalIndices = this.getTotalIndices();
  32973. // Generating unique vertices per face
  32974. var index;
  32975. for (index = 0; index < totalIndices; index++) {
  32976. var vertexIndex = indices[index];
  32977. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32978. kind = kinds[kindIndex];
  32979. var stride = vbs[kind].getStrideSize();
  32980. for (var offset = 0; offset < stride; offset++) {
  32981. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32982. }
  32983. }
  32984. }
  32985. // Updating faces & normal
  32986. var normals = [];
  32987. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32988. for (index = 0; index < totalIndices; index += 3) {
  32989. indices[index] = index;
  32990. indices[index + 1] = index + 1;
  32991. indices[index + 2] = index + 2;
  32992. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32993. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32994. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32995. var p1p2 = p1.subtract(p2);
  32996. var p3p2 = p3.subtract(p2);
  32997. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32998. // Store same normals for every vertex
  32999. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33000. normals.push(normal.x);
  33001. normals.push(normal.y);
  33002. normals.push(normal.z);
  33003. }
  33004. }
  33005. this.setIndices(indices);
  33006. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33007. // Updating vertex buffers
  33008. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33009. kind = kinds[kindIndex];
  33010. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33011. }
  33012. // Updating submeshes
  33013. this.releaseSubMeshes();
  33014. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33015. var previousOne = previousSubmeshes[submeshIndex];
  33016. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33017. }
  33018. this.synchronizeInstances();
  33019. return this;
  33020. };
  33021. /**
  33022. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33023. * In other words, more vertices, no more indices and a single bigger VBO.
  33024. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33025. * Returns the Mesh.
  33026. */
  33027. Mesh.prototype.convertToUnIndexedMesh = function () {
  33028. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33029. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33030. var kinds = this.getVerticesDataKinds();
  33031. var vbs = {};
  33032. var data = {};
  33033. var newdata = {};
  33034. var kindIndex;
  33035. var kind;
  33036. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33037. kind = kinds[kindIndex];
  33038. var vertexBuffer = this.getVertexBuffer(kind);
  33039. vbs[kind] = vertexBuffer;
  33040. data[kind] = vbs[kind].getData();
  33041. newdata[kind] = [];
  33042. }
  33043. // Save previous submeshes
  33044. var previousSubmeshes = this.subMeshes.slice(0);
  33045. var indices = this.getIndices();
  33046. var totalIndices = this.getTotalIndices();
  33047. // Generating unique vertices per face
  33048. var index;
  33049. for (index = 0; index < totalIndices; index++) {
  33050. var vertexIndex = indices[index];
  33051. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33052. kind = kinds[kindIndex];
  33053. var stride = vbs[kind].getStrideSize();
  33054. for (var offset = 0; offset < stride; offset++) {
  33055. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33056. }
  33057. }
  33058. }
  33059. // Updating indices
  33060. for (index = 0; index < totalIndices; index += 3) {
  33061. indices[index] = index;
  33062. indices[index + 1] = index + 1;
  33063. indices[index + 2] = index + 2;
  33064. }
  33065. this.setIndices(indices);
  33066. // Updating vertex buffers
  33067. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33068. kind = kinds[kindIndex];
  33069. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33070. }
  33071. // Updating submeshes
  33072. this.releaseSubMeshes();
  33073. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33074. var previousOne = previousSubmeshes[submeshIndex];
  33075. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33076. }
  33077. this._unIndexed = true;
  33078. this.synchronizeInstances();
  33079. return this;
  33080. };
  33081. /**
  33082. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33083. * This method returns the Mesh.
  33084. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33085. */
  33086. Mesh.prototype.flipFaces = function (flipNormals) {
  33087. if (flipNormals === void 0) { flipNormals = false; }
  33088. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33089. var i;
  33090. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33091. for (i = 0; i < vertex_data.normals.length; i++) {
  33092. vertex_data.normals[i] *= -1;
  33093. }
  33094. }
  33095. if (vertex_data.indices) {
  33096. var temp;
  33097. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33098. // reassign indices
  33099. temp = vertex_data.indices[i + 1];
  33100. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33101. vertex_data.indices[i + 2] = temp;
  33102. }
  33103. }
  33104. vertex_data.applyToMesh(this);
  33105. return this;
  33106. };
  33107. // Instances
  33108. /**
  33109. * Creates a new InstancedMesh object from the mesh model.
  33110. * An instance shares the same properties and the same material than its model.
  33111. * Only these properties of each instance can then be set individually :
  33112. * - position
  33113. * - rotation
  33114. * - rotationQuaternion
  33115. * - setPivotMatrix
  33116. * - scaling
  33117. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33118. * Warning : this method is not supported for Line mesh and LineSystem
  33119. */
  33120. Mesh.prototype.createInstance = function (name) {
  33121. return new BABYLON.InstancedMesh(name, this);
  33122. };
  33123. /**
  33124. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33125. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33126. * This method returns the Mesh.
  33127. */
  33128. Mesh.prototype.synchronizeInstances = function () {
  33129. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33130. var instance = this.instances[instanceIndex];
  33131. instance._syncSubMeshes();
  33132. }
  33133. return this;
  33134. };
  33135. /**
  33136. * Simplify the mesh according to the given array of settings.
  33137. * Function will return immediately and will simplify async. It returns the Mesh.
  33138. * @param settings a collection of simplification settings.
  33139. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33140. * @param type the type of simplification to run.
  33141. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33142. */
  33143. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33144. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33145. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33146. this.getScene().simplificationQueue.addTask({
  33147. settings: settings,
  33148. parallelProcessing: parallelProcessing,
  33149. mesh: this,
  33150. simplificationType: simplificationType,
  33151. successCallback: successCallback
  33152. });
  33153. return this;
  33154. };
  33155. /**
  33156. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33157. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33158. * This should be used together with the simplification to avoid disappearing triangles.
  33159. * Returns the Mesh.
  33160. * @param successCallback an optional success callback to be called after the optimization finished.
  33161. */
  33162. Mesh.prototype.optimizeIndices = function (successCallback) {
  33163. var _this = this;
  33164. var indices = this.getIndices();
  33165. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33166. if (!positions || !indices) {
  33167. return this;
  33168. }
  33169. var vectorPositions = new Array();
  33170. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33171. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33172. }
  33173. var dupes = new Array();
  33174. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33175. var realPos = vectorPositions.length - 1 - iteration;
  33176. var testedPosition = vectorPositions[realPos];
  33177. for (var j = 0; j < realPos; ++j) {
  33178. var againstPosition = vectorPositions[j];
  33179. if (testedPosition.equals(againstPosition)) {
  33180. dupes[realPos] = j;
  33181. break;
  33182. }
  33183. }
  33184. }, function () {
  33185. for (var i = 0; i < indices.length; ++i) {
  33186. indices[i] = dupes[indices[i]] || indices[i];
  33187. }
  33188. //indices are now reordered
  33189. var originalSubMeshes = _this.subMeshes.slice(0);
  33190. _this.setIndices(indices);
  33191. _this.subMeshes = originalSubMeshes;
  33192. if (successCallback) {
  33193. successCallback(_this);
  33194. }
  33195. });
  33196. return this;
  33197. };
  33198. Mesh.prototype.serialize = function (serializationObject) {
  33199. serializationObject.name = this.name;
  33200. serializationObject.id = this.id;
  33201. serializationObject.type = this.getClassName();
  33202. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33203. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33204. }
  33205. serializationObject.position = this.position.asArray();
  33206. if (this.rotationQuaternion) {
  33207. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33208. }
  33209. else if (this.rotation) {
  33210. serializationObject.rotation = this.rotation.asArray();
  33211. }
  33212. serializationObject.scaling = this.scaling.asArray();
  33213. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33214. serializationObject.isEnabled = this.isEnabled(false);
  33215. serializationObject.isVisible = this.isVisible;
  33216. serializationObject.infiniteDistance = this.infiniteDistance;
  33217. serializationObject.pickable = this.isPickable;
  33218. serializationObject.receiveShadows = this.receiveShadows;
  33219. serializationObject.billboardMode = this.billboardMode;
  33220. serializationObject.visibility = this.visibility;
  33221. serializationObject.checkCollisions = this.checkCollisions;
  33222. serializationObject.isBlocker = this.isBlocker;
  33223. // Parent
  33224. if (this.parent) {
  33225. serializationObject.parentId = this.parent.id;
  33226. }
  33227. // Geometry
  33228. serializationObject.isUnIndexed = this.isUnIndexed;
  33229. var geometry = this._geometry;
  33230. if (geometry) {
  33231. var geometryId = geometry.id;
  33232. serializationObject.geometryId = geometryId;
  33233. // SubMeshes
  33234. serializationObject.subMeshes = [];
  33235. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33236. var subMesh = this.subMeshes[subIndex];
  33237. serializationObject.subMeshes.push({
  33238. materialIndex: subMesh.materialIndex,
  33239. verticesStart: subMesh.verticesStart,
  33240. verticesCount: subMesh.verticesCount,
  33241. indexStart: subMesh.indexStart,
  33242. indexCount: subMesh.indexCount
  33243. });
  33244. }
  33245. }
  33246. // Material
  33247. if (this.material) {
  33248. serializationObject.materialId = this.material.id;
  33249. }
  33250. else {
  33251. this.material = null;
  33252. }
  33253. // Morph targets
  33254. if (this.morphTargetManager) {
  33255. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33256. }
  33257. // Skeleton
  33258. if (this.skeleton) {
  33259. serializationObject.skeletonId = this.skeleton.id;
  33260. }
  33261. // Physics
  33262. //TODO implement correct serialization for physics impostors.
  33263. var impostor = this.getPhysicsImpostor();
  33264. if (impostor) {
  33265. serializationObject.physicsMass = impostor.getParam("mass");
  33266. serializationObject.physicsFriction = impostor.getParam("friction");
  33267. serializationObject.physicsRestitution = impostor.getParam("mass");
  33268. serializationObject.physicsImpostor = impostor.type;
  33269. }
  33270. // Metadata
  33271. if (this.metadata) {
  33272. serializationObject.metadata = this.metadata;
  33273. }
  33274. // Instances
  33275. serializationObject.instances = [];
  33276. for (var index = 0; index < this.instances.length; index++) {
  33277. var instance = this.instances[index];
  33278. var serializationInstance = {
  33279. name: instance.name,
  33280. id: instance.id,
  33281. position: instance.position.asArray(),
  33282. scaling: instance.scaling.asArray()
  33283. };
  33284. if (instance.rotationQuaternion) {
  33285. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33286. }
  33287. else if (instance.rotation) {
  33288. serializationInstance.rotation = instance.rotation.asArray();
  33289. }
  33290. serializationObject.instances.push(serializationInstance);
  33291. // Animations
  33292. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33293. serializationInstance.ranges = instance.serializeAnimationRanges();
  33294. }
  33295. //
  33296. // Animations
  33297. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33298. serializationObject.ranges = this.serializeAnimationRanges();
  33299. // Layer mask
  33300. serializationObject.layerMask = this.layerMask;
  33301. // Alpha
  33302. serializationObject.alphaIndex = this.alphaIndex;
  33303. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33304. // Overlay
  33305. serializationObject.overlayAlpha = this.overlayAlpha;
  33306. serializationObject.overlayColor = this.overlayColor.asArray();
  33307. serializationObject.renderOverlay = this.renderOverlay;
  33308. // Fog
  33309. serializationObject.applyFog = this.applyFog;
  33310. // Action Manager
  33311. if (this.actionManager) {
  33312. serializationObject.actions = this.actionManager.serialize(this.name);
  33313. }
  33314. };
  33315. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33316. if (!this.geometry) {
  33317. return;
  33318. }
  33319. this._markSubMeshesAsAttributesDirty();
  33320. var morphTargetManager = this._morphTargetManager;
  33321. if (morphTargetManager && morphTargetManager.vertexCount) {
  33322. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33323. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33324. this.morphTargetManager = null;
  33325. return;
  33326. }
  33327. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33328. var morphTarget = morphTargetManager.getActiveTarget(index);
  33329. var positions = morphTarget.getPositions();
  33330. if (!positions) {
  33331. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33332. return;
  33333. }
  33334. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33335. var normals = morphTarget.getNormals();
  33336. if (normals) {
  33337. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33338. }
  33339. var tangents = morphTarget.getTangents();
  33340. if (tangents) {
  33341. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33342. }
  33343. }
  33344. }
  33345. else {
  33346. var index = 0;
  33347. // Positions
  33348. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33349. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33350. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33351. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33352. }
  33353. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33354. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33355. }
  33356. index++;
  33357. }
  33358. }
  33359. };
  33360. // Statics
  33361. /**
  33362. * Returns a new Mesh object parsed from the source provided.
  33363. * The parameter `parsedMesh` is the source.
  33364. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33365. */
  33366. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33367. var mesh;
  33368. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33369. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33370. }
  33371. else {
  33372. mesh = new Mesh(parsedMesh.name, scene);
  33373. }
  33374. mesh.id = parsedMesh.id;
  33375. if (BABYLON.Tags) {
  33376. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33377. }
  33378. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33379. if (parsedMesh.metadata !== undefined) {
  33380. mesh.metadata = parsedMesh.metadata;
  33381. }
  33382. if (parsedMesh.rotationQuaternion) {
  33383. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33384. }
  33385. else if (parsedMesh.rotation) {
  33386. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33387. }
  33388. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33389. if (parsedMesh.localMatrix) {
  33390. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33391. }
  33392. else if (parsedMesh.pivotMatrix) {
  33393. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33394. }
  33395. mesh.setEnabled(parsedMesh.isEnabled);
  33396. mesh.isVisible = parsedMesh.isVisible;
  33397. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33398. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33399. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33400. if (parsedMesh.applyFog !== undefined) {
  33401. mesh.applyFog = parsedMesh.applyFog;
  33402. }
  33403. if (parsedMesh.pickable !== undefined) {
  33404. mesh.isPickable = parsedMesh.pickable;
  33405. }
  33406. if (parsedMesh.alphaIndex !== undefined) {
  33407. mesh.alphaIndex = parsedMesh.alphaIndex;
  33408. }
  33409. mesh.receiveShadows = parsedMesh.receiveShadows;
  33410. mesh.billboardMode = parsedMesh.billboardMode;
  33411. if (parsedMesh.visibility !== undefined) {
  33412. mesh.visibility = parsedMesh.visibility;
  33413. }
  33414. mesh.checkCollisions = parsedMesh.checkCollisions;
  33415. if (parsedMesh.isBlocker !== undefined) {
  33416. mesh.isBlocker = parsedMesh.isBlocker;
  33417. }
  33418. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33419. // freezeWorldMatrix
  33420. if (parsedMesh.freezeWorldMatrix) {
  33421. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33422. }
  33423. // Parent
  33424. if (parsedMesh.parentId) {
  33425. mesh._waitingParentId = parsedMesh.parentId;
  33426. }
  33427. // Actions
  33428. if (parsedMesh.actions !== undefined) {
  33429. mesh._waitingActions = parsedMesh.actions;
  33430. }
  33431. // Overlay
  33432. if (parsedMesh.overlayAlpha !== undefined) {
  33433. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33434. }
  33435. if (parsedMesh.overlayColor !== undefined) {
  33436. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33437. }
  33438. if (parsedMesh.renderOverlay !== undefined) {
  33439. mesh.renderOverlay = parsedMesh.renderOverlay;
  33440. }
  33441. // Geometry
  33442. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33443. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33444. if (parsedMesh.delayLoadingFile) {
  33445. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33446. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33447. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33448. if (parsedMesh._binaryInfo) {
  33449. mesh._binaryInfo = parsedMesh._binaryInfo;
  33450. }
  33451. mesh._delayInfo = [];
  33452. if (parsedMesh.hasUVs) {
  33453. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33454. }
  33455. if (parsedMesh.hasUVs2) {
  33456. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33457. }
  33458. if (parsedMesh.hasUVs3) {
  33459. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33460. }
  33461. if (parsedMesh.hasUVs4) {
  33462. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33463. }
  33464. if (parsedMesh.hasUVs5) {
  33465. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33466. }
  33467. if (parsedMesh.hasUVs6) {
  33468. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33469. }
  33470. if (parsedMesh.hasColors) {
  33471. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33472. }
  33473. if (parsedMesh.hasMatricesIndices) {
  33474. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33475. }
  33476. if (parsedMesh.hasMatricesWeights) {
  33477. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33478. }
  33479. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33480. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33481. mesh._checkDelayState();
  33482. }
  33483. }
  33484. else {
  33485. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33486. }
  33487. // Material
  33488. if (parsedMesh.materialId) {
  33489. mesh.setMaterialByID(parsedMesh.materialId);
  33490. }
  33491. else {
  33492. mesh.material = null;
  33493. }
  33494. // Morph targets
  33495. if (parsedMesh.morphTargetManagerId > -1) {
  33496. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33497. }
  33498. // Skeleton
  33499. if (parsedMesh.skeletonId > -1) {
  33500. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33501. if (parsedMesh.numBoneInfluencers) {
  33502. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33503. }
  33504. }
  33505. // Animations
  33506. if (parsedMesh.animations) {
  33507. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33508. var parsedAnimation = parsedMesh.animations[animationIndex];
  33509. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33510. }
  33511. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33512. }
  33513. if (parsedMesh.autoAnimate) {
  33514. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33515. }
  33516. // Layer Mask
  33517. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33518. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33519. }
  33520. else {
  33521. mesh.layerMask = 0x0FFFFFFF;
  33522. }
  33523. // Physics
  33524. if (parsedMesh.physicsImpostor) {
  33525. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33526. mass: parsedMesh.physicsMass,
  33527. friction: parsedMesh.physicsFriction,
  33528. restitution: parsedMesh.physicsRestitution
  33529. }, scene);
  33530. }
  33531. // Instances
  33532. if (parsedMesh.instances) {
  33533. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33534. var parsedInstance = parsedMesh.instances[index];
  33535. var instance = mesh.createInstance(parsedInstance.name);
  33536. if (parsedInstance.id) {
  33537. instance.id = parsedInstance.id;
  33538. }
  33539. if (BABYLON.Tags) {
  33540. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33541. }
  33542. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33543. if (parsedInstance.parentId) {
  33544. instance._waitingParentId = parsedInstance.parentId;
  33545. }
  33546. if (parsedInstance.rotationQuaternion) {
  33547. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33548. }
  33549. else if (parsedInstance.rotation) {
  33550. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33551. }
  33552. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33553. instance.checkCollisions = mesh.checkCollisions;
  33554. if (parsedMesh.animations) {
  33555. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33556. parsedAnimation = parsedMesh.animations[animationIndex];
  33557. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33558. }
  33559. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33560. if (parsedMesh.autoAnimate) {
  33561. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33562. }
  33563. }
  33564. }
  33565. }
  33566. return mesh;
  33567. };
  33568. /**
  33569. * Creates a ribbon mesh.
  33570. * Please consider using the same method from the MeshBuilder class instead.
  33571. * 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.
  33572. *
  33573. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33574. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33575. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33576. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33577. * 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.
  33578. * 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.
  33579. * 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
  33580. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33581. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33583. */
  33584. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33585. if (closeArray === void 0) { closeArray = false; }
  33586. if (updatable === void 0) { updatable = false; }
  33587. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33588. pathArray: pathArray,
  33589. closeArray: closeArray,
  33590. closePath: closePath,
  33591. offset: offset,
  33592. updatable: updatable,
  33593. sideOrientation: sideOrientation,
  33594. instance: instance
  33595. }, scene);
  33596. };
  33597. /**
  33598. * Creates a plane polygonal mesh. By default, this is a disc.
  33599. * Please consider using the same method from the MeshBuilder class instead.
  33600. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33601. * 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.
  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.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33607. if (scene === void 0) { scene = null; }
  33608. var options = {
  33609. radius: radius,
  33610. tessellation: tessellation,
  33611. sideOrientation: sideOrientation,
  33612. updatable: updatable
  33613. };
  33614. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33615. };
  33616. /**
  33617. * Creates a box mesh.
  33618. * Please consider using the same method from the MeshBuilder class instead.
  33619. * The parameter `size` sets the size (float) of each box side (default 1).
  33620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33621. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33623. */
  33624. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33625. if (scene === void 0) { scene = null; }
  33626. var options = {
  33627. size: size,
  33628. sideOrientation: sideOrientation,
  33629. updatable: updatable
  33630. };
  33631. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33632. };
  33633. /**
  33634. * Creates a sphere mesh.
  33635. * Please consider using the same method from the MeshBuilder class instead.
  33636. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33637. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33638. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33639. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33641. */
  33642. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33643. var options = {
  33644. segments: segments,
  33645. diameterX: diameter,
  33646. diameterY: diameter,
  33647. diameterZ: diameter,
  33648. sideOrientation: sideOrientation,
  33649. updatable: updatable
  33650. };
  33651. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33652. };
  33653. /**
  33654. * Creates a cylinder or a cone mesh.
  33655. * Please consider using the same method from the MeshBuilder class instead.
  33656. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33657. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33658. * 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.
  33659. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33660. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33661. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33662. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33664. */
  33665. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33666. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33667. if (scene !== undefined) {
  33668. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33669. updatable = scene;
  33670. }
  33671. scene = subdivisions;
  33672. subdivisions = 1;
  33673. }
  33674. var options = {
  33675. height: height,
  33676. diameterTop: diameterTop,
  33677. diameterBottom: diameterBottom,
  33678. tessellation: tessellation,
  33679. subdivisions: subdivisions,
  33680. sideOrientation: sideOrientation,
  33681. updatable: updatable
  33682. };
  33683. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33684. };
  33685. // Torus (Code from SharpDX.org)
  33686. /**
  33687. * Creates a torus mesh.
  33688. * Please consider using the same method from the MeshBuilder class instead.
  33689. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33690. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33691. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33693. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33695. */
  33696. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33697. var options = {
  33698. diameter: diameter,
  33699. thickness: thickness,
  33700. tessellation: tessellation,
  33701. sideOrientation: sideOrientation,
  33702. updatable: updatable
  33703. };
  33704. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33705. };
  33706. /**
  33707. * Creates a torus knot mesh.
  33708. * Please consider using the same method from the MeshBuilder class instead.
  33709. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33710. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33711. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33712. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33713. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33714. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33716. */
  33717. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33718. var options = {
  33719. radius: radius,
  33720. tube: tube,
  33721. radialSegments: radialSegments,
  33722. tubularSegments: tubularSegments,
  33723. p: p,
  33724. q: q,
  33725. sideOrientation: sideOrientation,
  33726. updatable: updatable
  33727. };
  33728. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33729. };
  33730. /**
  33731. * Creates a line mesh.
  33732. * Please consider using the same method from the MeshBuilder class instead.
  33733. * 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.
  33734. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33735. * The parameter `points` is an array successive Vector3.
  33736. * 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
  33737. * When updating an instance, remember that only point positions can change, not the number of points.
  33738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33739. */
  33740. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33741. if (scene === void 0) { scene = null; }
  33742. if (updatable === void 0) { updatable = false; }
  33743. if (instance === void 0) { instance = null; }
  33744. var options = {
  33745. points: points,
  33746. updatable: updatable,
  33747. instance: instance
  33748. };
  33749. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33750. };
  33751. /**
  33752. * Creates a dashed line mesh.
  33753. * Please consider using the same method from the MeshBuilder class instead.
  33754. * 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.
  33755. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33756. * The parameter `points` is an array successive Vector3.
  33757. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33758. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33759. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33760. * 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
  33761. * When updating an instance, remember that only point positions can change, not the number of points.
  33762. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33763. */
  33764. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33765. if (scene === void 0) { scene = null; }
  33766. var options = {
  33767. points: points,
  33768. dashSize: dashSize,
  33769. gapSize: gapSize,
  33770. dashNb: dashNb,
  33771. updatable: updatable,
  33772. instance: instance
  33773. };
  33774. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33775. };
  33776. /**
  33777. * Creates a polygon mesh.
  33778. * Please consider using the same method from the MeshBuilder class instead.
  33779. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33780. * 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.
  33781. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33783. * Remember you can only change the shape positions, not their number when updating a polygon.
  33784. */
  33785. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33786. var options = {
  33787. shape: shape,
  33788. holes: holes,
  33789. updatable: updatable,
  33790. sideOrientation: sideOrientation
  33791. };
  33792. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33793. };
  33794. /**
  33795. * Creates an extruded polygon mesh, with depth in the Y direction.
  33796. * Please consider using the same method from the MeshBuilder class instead.
  33797. */
  33798. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33799. var options = {
  33800. shape: shape,
  33801. holes: holes,
  33802. depth: depth,
  33803. updatable: updatable,
  33804. sideOrientation: sideOrientation
  33805. };
  33806. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33807. };
  33808. /**
  33809. * Creates an extruded shape mesh.
  33810. * 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.
  33811. * Please consider using the same method from the MeshBuilder class instead.
  33812. *
  33813. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33814. * 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
  33815. * extruded along the Z axis.
  33816. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33817. * 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.
  33818. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33819. * 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
  33820. * 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
  33821. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33822. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33823. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33825. */
  33826. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33827. if (scene === void 0) { scene = null; }
  33828. var options = {
  33829. shape: shape,
  33830. path: path,
  33831. scale: scale,
  33832. rotation: rotation,
  33833. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33834. sideOrientation: sideOrientation,
  33835. instance: instance,
  33836. updatable: updatable
  33837. };
  33838. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33839. };
  33840. /**
  33841. * Creates an custom extruded shape mesh.
  33842. * 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.
  33843. * Please consider using the same method from the MeshBuilder class instead.
  33844. *
  33845. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33846. * 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
  33847. * extruded along the Z axis.
  33848. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33849. * 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
  33850. * and the distance of this point from the begining of the path :
  33851. * ```javascript
  33852. * var rotationFunction = function(i, distance) {
  33853. * // do things
  33854. * return rotationValue; }
  33855. * ```
  33856. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33857. * 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
  33858. * and the distance of this point from the begining of the path :
  33859. * ```javascript
  33860. * var scaleFunction = function(i, distance) {
  33861. * // do things
  33862. * return scaleValue;}
  33863. * ```
  33864. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33865. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33866. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33867. * 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
  33868. * 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
  33869. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33870. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33871. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33873. */
  33874. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33875. var options = {
  33876. shape: shape,
  33877. path: path,
  33878. scaleFunction: scaleFunction,
  33879. rotationFunction: rotationFunction,
  33880. ribbonCloseArray: ribbonCloseArray,
  33881. ribbonClosePath: ribbonClosePath,
  33882. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33883. sideOrientation: sideOrientation,
  33884. instance: instance,
  33885. updatable: updatable
  33886. };
  33887. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33888. };
  33889. /**
  33890. * Creates lathe mesh.
  33891. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33892. * Please consider using the same method from the MeshBuilder class instead.
  33893. * 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
  33894. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33895. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33896. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33897. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33898. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33899. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33900. */
  33901. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33902. var options = {
  33903. shape: shape,
  33904. radius: radius,
  33905. tessellation: tessellation,
  33906. sideOrientation: sideOrientation,
  33907. updatable: updatable
  33908. };
  33909. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33910. };
  33911. /**
  33912. * Creates a plane mesh.
  33913. * Please consider using the same method from the MeshBuilder class instead.
  33914. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33915. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33916. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33918. */
  33919. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33920. var options = {
  33921. size: size,
  33922. width: size,
  33923. height: size,
  33924. sideOrientation: sideOrientation,
  33925. updatable: updatable
  33926. };
  33927. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33928. };
  33929. /**
  33930. * Creates a ground mesh.
  33931. * Please consider using the same method from the MeshBuilder class instead.
  33932. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33933. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33935. */
  33936. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33937. var options = {
  33938. width: width,
  33939. height: height,
  33940. subdivisions: subdivisions,
  33941. updatable: updatable
  33942. };
  33943. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33944. };
  33945. /**
  33946. * Creates a tiled ground mesh.
  33947. * Please consider using the same method from the MeshBuilder class instead.
  33948. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33949. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33950. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33951. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33952. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33953. * numbers of subdivisions on the ground width and height of each tile.
  33954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33955. */
  33956. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33957. var options = {
  33958. xmin: xmin,
  33959. zmin: zmin,
  33960. xmax: xmax,
  33961. zmax: zmax,
  33962. subdivisions: subdivisions,
  33963. precision: precision,
  33964. updatable: updatable
  33965. };
  33966. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33967. };
  33968. /**
  33969. * Creates a ground mesh from a height map.
  33970. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33971. * Please consider using the same method from the MeshBuilder class instead.
  33972. * The parameter `url` sets the URL of the height map image resource.
  33973. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33974. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33975. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33976. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33977. * 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).
  33978. * This function is passed the newly built mesh :
  33979. * ```javascript
  33980. * function(mesh) { // do things
  33981. * return; }
  33982. * ```
  33983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33984. */
  33985. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33986. var options = {
  33987. width: width,
  33988. height: height,
  33989. subdivisions: subdivisions,
  33990. minHeight: minHeight,
  33991. maxHeight: maxHeight,
  33992. updatable: updatable,
  33993. onReady: onReady
  33994. };
  33995. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33996. };
  33997. /**
  33998. * Creates a tube mesh.
  33999. * 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.
  34000. * Please consider using the same method from the MeshBuilder class instead.
  34001. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34002. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34003. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34004. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34005. * 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.
  34006. * It must return a radius value (positive float) :
  34007. * ```javascript
  34008. * var radiusFunction = function(i, distance) {
  34009. * // do things
  34010. * return radius; }
  34011. * ```
  34012. * 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
  34013. * 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
  34014. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34015. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34016. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34017. */
  34018. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34019. var options = {
  34020. path: path,
  34021. radius: radius,
  34022. tessellation: tessellation,
  34023. radiusFunction: radiusFunction,
  34024. arc: 1,
  34025. cap: cap,
  34026. updatable: updatable,
  34027. sideOrientation: sideOrientation,
  34028. instance: instance
  34029. };
  34030. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34031. };
  34032. /**
  34033. * Creates a polyhedron mesh.
  34034. * Please consider using the same method from the MeshBuilder class instead.
  34035. * 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
  34036. * to choose the wanted type.
  34037. * The parameter `size` (positive float, default 1) sets the polygon size.
  34038. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34039. * 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`.
  34040. * 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
  34041. * 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)`).
  34042. * 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
  34043. * 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.
  34044. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34045. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34046. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34047. */
  34048. Mesh.CreatePolyhedron = function (name, options, scene) {
  34049. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34050. };
  34051. /**
  34052. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34053. * Please consider using the same method from the MeshBuilder class instead.
  34054. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34055. * 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`).
  34056. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34057. * 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.
  34058. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34059. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34060. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34061. */
  34062. Mesh.CreateIcoSphere = function (name, options, scene) {
  34063. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34064. };
  34065. /**
  34066. * Creates a decal mesh.
  34067. * Please consider using the same method from the MeshBuilder class instead.
  34068. * 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.
  34069. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34070. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34071. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34072. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34073. */
  34074. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34075. var options = {
  34076. position: position,
  34077. normal: normal,
  34078. size: size,
  34079. angle: angle
  34080. };
  34081. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34082. };
  34083. // Skeletons
  34084. /**
  34085. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34086. */
  34087. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34088. if (!this._sourcePositions) {
  34089. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34090. if (!source) {
  34091. return this._sourcePositions;
  34092. }
  34093. this._sourcePositions = new Float32Array(source);
  34094. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34095. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34096. }
  34097. }
  34098. return this._sourcePositions;
  34099. };
  34100. /**
  34101. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34102. */
  34103. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34104. if (!this._sourceNormals) {
  34105. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34106. if (!source) {
  34107. return this._sourceNormals;
  34108. }
  34109. this._sourceNormals = new Float32Array(source);
  34110. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34111. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34112. }
  34113. }
  34114. return this._sourceNormals;
  34115. };
  34116. /**
  34117. * Updates the vertex buffer by applying transformation from the bones.
  34118. * Returns the Mesh.
  34119. *
  34120. * @param {skeleton} skeleton to apply
  34121. */
  34122. Mesh.prototype.applySkeleton = function (skeleton) {
  34123. if (!this.geometry) {
  34124. return this;
  34125. }
  34126. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34127. return this;
  34128. }
  34129. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34130. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34131. return this;
  34132. }
  34133. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34134. return this;
  34135. }
  34136. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34137. return this;
  34138. }
  34139. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34140. return this;
  34141. }
  34142. if (!this._sourcePositions) {
  34143. var submeshes = this.subMeshes.slice();
  34144. this.setPositionsForCPUSkinning();
  34145. this.subMeshes = submeshes;
  34146. }
  34147. if (!this._sourceNormals) {
  34148. this.setNormalsForCPUSkinning();
  34149. }
  34150. // positionsData checks for not being Float32Array will only pass at most once
  34151. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34152. if (!positionsData) {
  34153. return this;
  34154. }
  34155. if (!(positionsData instanceof Float32Array)) {
  34156. positionsData = new Float32Array(positionsData);
  34157. }
  34158. // normalsData checks for not being Float32Array will only pass at most once
  34159. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34160. if (!normalsData) {
  34161. return this;
  34162. }
  34163. if (!(normalsData instanceof Float32Array)) {
  34164. normalsData = new Float32Array(normalsData);
  34165. }
  34166. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34167. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34168. if (!matricesWeightsData || !matricesIndicesData) {
  34169. return this;
  34170. }
  34171. var needExtras = this.numBoneInfluencers > 4;
  34172. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34173. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34174. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34175. var tempVector3 = BABYLON.Vector3.Zero();
  34176. var finalMatrix = new BABYLON.Matrix();
  34177. var tempMatrix = new BABYLON.Matrix();
  34178. var matWeightIdx = 0;
  34179. var inf;
  34180. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34181. var weight;
  34182. for (inf = 0; inf < 4; inf++) {
  34183. weight = matricesWeightsData[matWeightIdx + inf];
  34184. if (weight > 0) {
  34185. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34186. finalMatrix.addToSelf(tempMatrix);
  34187. }
  34188. }
  34189. if (needExtras) {
  34190. for (inf = 0; inf < 4; inf++) {
  34191. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34192. if (weight > 0) {
  34193. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34194. finalMatrix.addToSelf(tempMatrix);
  34195. }
  34196. }
  34197. }
  34198. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34199. tempVector3.toArray(positionsData, index);
  34200. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34201. tempVector3.toArray(normalsData, index);
  34202. finalMatrix.reset();
  34203. }
  34204. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34205. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34206. return this;
  34207. };
  34208. // Tools
  34209. /**
  34210. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34211. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34212. */
  34213. Mesh.MinMax = function (meshes) {
  34214. var minVector = null;
  34215. var maxVector = null;
  34216. meshes.forEach(function (mesh, index, array) {
  34217. var boundingInfo = mesh.getBoundingInfo();
  34218. var boundingBox = boundingInfo.boundingBox;
  34219. if (!minVector || !maxVector) {
  34220. minVector = boundingBox.minimumWorld;
  34221. maxVector = boundingBox.maximumWorld;
  34222. }
  34223. else {
  34224. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34225. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34226. }
  34227. });
  34228. if (!minVector || !maxVector) {
  34229. return {
  34230. min: BABYLON.Vector3.Zero(),
  34231. max: BABYLON.Vector3.Zero()
  34232. };
  34233. }
  34234. return {
  34235. min: minVector,
  34236. max: maxVector
  34237. };
  34238. };
  34239. /**
  34240. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34241. */
  34242. Mesh.Center = function (meshesOrMinMaxVector) {
  34243. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34244. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34245. };
  34246. /**
  34247. * Merge the array of meshes into a single mesh for performance reasons.
  34248. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34249. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34250. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34251. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34252. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34253. */
  34254. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34255. if (disposeSource === void 0) { disposeSource = true; }
  34256. var index;
  34257. if (!allow32BitsIndices) {
  34258. var totalVertices = 0;
  34259. // Counting vertices
  34260. for (index = 0; index < meshes.length; index++) {
  34261. if (meshes[index]) {
  34262. totalVertices += meshes[index].getTotalVertices();
  34263. if (totalVertices > 65536) {
  34264. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34265. return null;
  34266. }
  34267. }
  34268. }
  34269. }
  34270. // Merge
  34271. var vertexData = null;
  34272. var otherVertexData;
  34273. var indiceArray = new Array();
  34274. var source = null;
  34275. for (index = 0; index < meshes.length; index++) {
  34276. if (meshes[index]) {
  34277. meshes[index].computeWorldMatrix(true);
  34278. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34279. otherVertexData.transform(meshes[index].getWorldMatrix());
  34280. if (vertexData) {
  34281. vertexData.merge(otherVertexData);
  34282. }
  34283. else {
  34284. vertexData = otherVertexData;
  34285. source = meshes[index];
  34286. }
  34287. if (subdivideWithSubMeshes) {
  34288. indiceArray.push(meshes[index].getTotalIndices());
  34289. }
  34290. }
  34291. }
  34292. source = source;
  34293. if (!meshSubclass) {
  34294. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34295. }
  34296. vertexData.applyToMesh(meshSubclass);
  34297. // Setting properties
  34298. meshSubclass.material = source.material;
  34299. meshSubclass.checkCollisions = source.checkCollisions;
  34300. // Cleaning
  34301. if (disposeSource) {
  34302. for (index = 0; index < meshes.length; index++) {
  34303. if (meshes[index]) {
  34304. meshes[index].dispose();
  34305. }
  34306. }
  34307. }
  34308. // Subdivide
  34309. if (subdivideWithSubMeshes) {
  34310. //-- removal of global submesh
  34311. meshSubclass.releaseSubMeshes();
  34312. index = 0;
  34313. var offset = 0;
  34314. //-- apply subdivision according to index table
  34315. while (index < indiceArray.length) {
  34316. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34317. offset += indiceArray[index];
  34318. index++;
  34319. }
  34320. }
  34321. return meshSubclass;
  34322. };
  34323. // Consts
  34324. Mesh._FRONTSIDE = 0;
  34325. Mesh._BACKSIDE = 1;
  34326. Mesh._DOUBLESIDE = 2;
  34327. Mesh._DEFAULTSIDE = 0;
  34328. Mesh._NO_CAP = 0;
  34329. Mesh._CAP_START = 1;
  34330. Mesh._CAP_END = 2;
  34331. Mesh._CAP_ALL = 3;
  34332. return Mesh;
  34333. }(BABYLON.AbstractMesh));
  34334. BABYLON.Mesh = Mesh;
  34335. })(BABYLON || (BABYLON = {}));
  34336. //# sourceMappingURL=babylon.mesh.js.map
  34337. var BABYLON;
  34338. (function (BABYLON) {
  34339. var BaseSubMesh = /** @class */ (function () {
  34340. function BaseSubMesh() {
  34341. }
  34342. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34343. get: function () {
  34344. return this._materialEffect;
  34345. },
  34346. enumerable: true,
  34347. configurable: true
  34348. });
  34349. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34350. if (defines === void 0) { defines = null; }
  34351. if (this._materialEffect === effect) {
  34352. if (!effect) {
  34353. this._materialDefines = null;
  34354. }
  34355. return;
  34356. }
  34357. this._materialDefines = defines;
  34358. this._materialEffect = effect;
  34359. };
  34360. return BaseSubMesh;
  34361. }());
  34362. BABYLON.BaseSubMesh = BaseSubMesh;
  34363. var SubMesh = /** @class */ (function (_super) {
  34364. __extends(SubMesh, _super);
  34365. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34366. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34367. var _this = _super.call(this) || this;
  34368. _this.materialIndex = materialIndex;
  34369. _this.verticesStart = verticesStart;
  34370. _this.verticesCount = verticesCount;
  34371. _this.indexStart = indexStart;
  34372. _this.indexCount = indexCount;
  34373. _this._renderId = 0;
  34374. _this._mesh = mesh;
  34375. _this._renderingMesh = renderingMesh || mesh;
  34376. mesh.subMeshes.push(_this);
  34377. _this._trianglePlanes = [];
  34378. _this._id = mesh.subMeshes.length - 1;
  34379. if (createBoundingBox) {
  34380. _this.refreshBoundingInfo();
  34381. mesh.computeWorldMatrix(true);
  34382. }
  34383. return _this;
  34384. }
  34385. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34386. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34387. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34388. };
  34389. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34390. get: function () {
  34391. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34392. },
  34393. enumerable: true,
  34394. configurable: true
  34395. });
  34396. /**
  34397. * Returns the submesh BoudingInfo object.
  34398. */
  34399. SubMesh.prototype.getBoundingInfo = function () {
  34400. if (this.IsGlobal) {
  34401. return this._mesh.getBoundingInfo();
  34402. }
  34403. return this._boundingInfo;
  34404. };
  34405. /**
  34406. * Sets the submesh BoundingInfo.
  34407. * Return the SubMesh.
  34408. */
  34409. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34410. this._boundingInfo = boundingInfo;
  34411. return this;
  34412. };
  34413. /**
  34414. * Returns the mesh of the current submesh.
  34415. */
  34416. SubMesh.prototype.getMesh = function () {
  34417. return this._mesh;
  34418. };
  34419. /**
  34420. * Returns the rendering mesh of the submesh.
  34421. */
  34422. SubMesh.prototype.getRenderingMesh = function () {
  34423. return this._renderingMesh;
  34424. };
  34425. /**
  34426. * Returns the submesh material.
  34427. */
  34428. SubMesh.prototype.getMaterial = function () {
  34429. var rootMaterial = this._renderingMesh.material;
  34430. if (rootMaterial === null || rootMaterial === undefined) {
  34431. return this._mesh.getScene().defaultMaterial;
  34432. }
  34433. else if (rootMaterial.getSubMaterial) {
  34434. var multiMaterial = rootMaterial;
  34435. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34436. if (this._currentMaterial !== effectiveMaterial) {
  34437. this._currentMaterial = effectiveMaterial;
  34438. this._materialDefines = null;
  34439. }
  34440. return effectiveMaterial;
  34441. }
  34442. return rootMaterial;
  34443. };
  34444. // Methods
  34445. /**
  34446. * Sets a new updated BoundingInfo object to the submesh.
  34447. * Returns the SubMesh.
  34448. */
  34449. SubMesh.prototype.refreshBoundingInfo = function () {
  34450. this._lastColliderWorldVertices = null;
  34451. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34452. return this;
  34453. }
  34454. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34455. if (!data) {
  34456. this._boundingInfo = this._mesh.getBoundingInfo();
  34457. return this;
  34458. }
  34459. var indices = this._renderingMesh.getIndices();
  34460. var extend;
  34461. //is this the only submesh?
  34462. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34463. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34464. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34465. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34466. }
  34467. else {
  34468. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34469. }
  34470. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34471. return this;
  34472. };
  34473. SubMesh.prototype._checkCollision = function (collider) {
  34474. var boundingInfo = this.getBoundingInfo();
  34475. return boundingInfo._checkCollision(collider);
  34476. };
  34477. /**
  34478. * Updates the submesh BoundingInfo.
  34479. * Returns the Submesh.
  34480. */
  34481. SubMesh.prototype.updateBoundingInfo = function (world) {
  34482. var boundingInfo = this.getBoundingInfo();
  34483. if (!boundingInfo) {
  34484. this.refreshBoundingInfo();
  34485. boundingInfo = this.getBoundingInfo();
  34486. }
  34487. boundingInfo.update(world);
  34488. return this;
  34489. };
  34490. /**
  34491. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34492. * Boolean returned.
  34493. */
  34494. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34495. var boundingInfo = this.getBoundingInfo();
  34496. if (!boundingInfo) {
  34497. return false;
  34498. }
  34499. return boundingInfo.isInFrustum(frustumPlanes);
  34500. };
  34501. /**
  34502. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34503. * Boolean returned.
  34504. */
  34505. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34506. var boundingInfo = this.getBoundingInfo();
  34507. if (!boundingInfo) {
  34508. return false;
  34509. }
  34510. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34511. };
  34512. /**
  34513. * Renders the submesh.
  34514. * Returns it.
  34515. */
  34516. SubMesh.prototype.render = function (enableAlphaMode) {
  34517. this._renderingMesh.render(this, enableAlphaMode);
  34518. return this;
  34519. };
  34520. /**
  34521. * Returns a new Index Buffer.
  34522. * Type returned : WebGLBuffer.
  34523. */
  34524. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34525. if (!this._linesIndexBuffer) {
  34526. var linesIndices = [];
  34527. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34528. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34529. }
  34530. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34531. this.linesIndexCount = linesIndices.length;
  34532. }
  34533. return this._linesIndexBuffer;
  34534. };
  34535. /**
  34536. * True is the passed Ray intersects the submesh bounding box.
  34537. * Boolean returned.
  34538. */
  34539. SubMesh.prototype.canIntersects = function (ray) {
  34540. var boundingInfo = this.getBoundingInfo();
  34541. if (!boundingInfo) {
  34542. return false;
  34543. }
  34544. return ray.intersectsBox(boundingInfo.boundingBox);
  34545. };
  34546. /**
  34547. * Returns an object IntersectionInfo.
  34548. */
  34549. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34550. var intersectInfo = null;
  34551. var material = this.getMaterial();
  34552. if (!material) {
  34553. return null;
  34554. }
  34555. switch (material.fillMode) {
  34556. case BABYLON.Material.PointListDrawMode:
  34557. case BABYLON.Material.LineListDrawMode:
  34558. case BABYLON.Material.LineLoopDrawMode:
  34559. case BABYLON.Material.LineStripDrawMode:
  34560. case BABYLON.Material.TriangleFanDrawMode:
  34561. case BABYLON.Material.TriangleStripDrawMode:
  34562. return null;
  34563. }
  34564. // LineMesh first as it's also a Mesh...
  34565. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34566. var lineMesh = this._mesh;
  34567. // Line test
  34568. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34569. var p0 = positions[indices[index]];
  34570. var p1 = positions[indices[index + 1]];
  34571. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34572. if (length < 0) {
  34573. continue;
  34574. }
  34575. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34576. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34577. if (fastCheck) {
  34578. break;
  34579. }
  34580. }
  34581. }
  34582. }
  34583. else {
  34584. // Triangles test
  34585. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34586. var p0 = positions[indices[index]];
  34587. var p1 = positions[indices[index + 1]];
  34588. var p2 = positions[indices[index + 2]];
  34589. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34590. if (currentIntersectInfo) {
  34591. if (currentIntersectInfo.distance < 0) {
  34592. continue;
  34593. }
  34594. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34595. intersectInfo = currentIntersectInfo;
  34596. intersectInfo.faceId = index / 3;
  34597. if (fastCheck) {
  34598. break;
  34599. }
  34600. }
  34601. }
  34602. }
  34603. }
  34604. return intersectInfo;
  34605. };
  34606. SubMesh.prototype._rebuild = function () {
  34607. if (this._linesIndexBuffer) {
  34608. this._linesIndexBuffer = null;
  34609. }
  34610. };
  34611. // Clone
  34612. /**
  34613. * Creates a new Submesh from the passed Mesh.
  34614. */
  34615. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34616. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34617. if (!this.IsGlobal) {
  34618. var boundingInfo = this.getBoundingInfo();
  34619. if (!boundingInfo) {
  34620. return result;
  34621. }
  34622. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34623. }
  34624. return result;
  34625. };
  34626. // Dispose
  34627. /**
  34628. * Disposes the Submesh.
  34629. * Returns nothing.
  34630. */
  34631. SubMesh.prototype.dispose = function () {
  34632. if (this._linesIndexBuffer) {
  34633. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34634. this._linesIndexBuffer = null;
  34635. }
  34636. // Remove from mesh
  34637. var index = this._mesh.subMeshes.indexOf(this);
  34638. this._mesh.subMeshes.splice(index, 1);
  34639. };
  34640. // Statics
  34641. /**
  34642. * Creates a new Submesh from the passed parameters :
  34643. * - materialIndex (integer) : the index of the main mesh material.
  34644. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34645. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34646. * - mesh (Mesh) : the main mesh to create the submesh from.
  34647. * - renderingMesh (optional Mesh) : rendering mesh.
  34648. */
  34649. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34650. var minVertexIndex = Number.MAX_VALUE;
  34651. var maxVertexIndex = -Number.MAX_VALUE;
  34652. renderingMesh = (renderingMesh || mesh);
  34653. var indices = renderingMesh.getIndices();
  34654. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34655. var vertexIndex = indices[index];
  34656. if (vertexIndex < minVertexIndex)
  34657. minVertexIndex = vertexIndex;
  34658. if (vertexIndex > maxVertexIndex)
  34659. maxVertexIndex = vertexIndex;
  34660. }
  34661. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34662. };
  34663. return SubMesh;
  34664. }(BaseSubMesh));
  34665. BABYLON.SubMesh = SubMesh;
  34666. })(BABYLON || (BABYLON = {}));
  34667. //# sourceMappingURL=babylon.subMesh.js.map
  34668. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34669. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34670. s = arguments[i];
  34671. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34672. t[p] = s[p];
  34673. }
  34674. return t;
  34675. };
  34676. var BABYLON;
  34677. (function (BABYLON) {
  34678. /**
  34679. * Manages the defines for the Material
  34680. */
  34681. var MaterialDefines = /** @class */ (function () {
  34682. function MaterialDefines() {
  34683. this._isDirty = true;
  34684. /** @hidden */
  34685. this._areLightsDirty = true;
  34686. /** @hidden */
  34687. this._areAttributesDirty = true;
  34688. /** @hidden */
  34689. this._areTexturesDirty = true;
  34690. /** @hidden */
  34691. this._areFresnelDirty = true;
  34692. /** @hidden */
  34693. this._areMiscDirty = true;
  34694. /** @hidden */
  34695. this._areImageProcessingDirty = true;
  34696. /** @hidden */
  34697. this._normals = false;
  34698. /** @hidden */
  34699. this._uvs = false;
  34700. /** @hidden */
  34701. this._needNormals = false;
  34702. /** @hidden */
  34703. this._needUVs = false;
  34704. }
  34705. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34706. /**
  34707. * Specifies if the material needs to be re-calculated
  34708. */
  34709. get: function () {
  34710. return this._isDirty;
  34711. },
  34712. enumerable: true,
  34713. configurable: true
  34714. });
  34715. /**
  34716. * Marks the material to indicate that it has been re-calculated
  34717. */
  34718. MaterialDefines.prototype.markAsProcessed = function () {
  34719. this._isDirty = false;
  34720. this._areAttributesDirty = false;
  34721. this._areTexturesDirty = false;
  34722. this._areFresnelDirty = false;
  34723. this._areLightsDirty = false;
  34724. this._areMiscDirty = false;
  34725. this._areImageProcessingDirty = false;
  34726. };
  34727. /**
  34728. * Marks the material to indicate that it needs to be re-calculated
  34729. */
  34730. MaterialDefines.prototype.markAsUnprocessed = function () {
  34731. this._isDirty = true;
  34732. };
  34733. /**
  34734. * Marks the material to indicate all of its defines need to be re-calculated
  34735. */
  34736. MaterialDefines.prototype.markAllAsDirty = function () {
  34737. this._areTexturesDirty = true;
  34738. this._areAttributesDirty = true;
  34739. this._areLightsDirty = true;
  34740. this._areFresnelDirty = true;
  34741. this._areMiscDirty = true;
  34742. this._areImageProcessingDirty = true;
  34743. this._isDirty = true;
  34744. };
  34745. /**
  34746. * Marks the material to indicate that image processing needs to be re-calculated
  34747. */
  34748. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34749. this._areImageProcessingDirty = true;
  34750. this._isDirty = true;
  34751. };
  34752. /**
  34753. * Marks the material to indicate the lights need to be re-calculated
  34754. */
  34755. MaterialDefines.prototype.markAsLightDirty = function () {
  34756. this._areLightsDirty = true;
  34757. this._isDirty = true;
  34758. };
  34759. /**
  34760. * Marks the attribute state as changed
  34761. */
  34762. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34763. this._areAttributesDirty = true;
  34764. this._isDirty = true;
  34765. };
  34766. /**
  34767. * Marks the texture state as changed
  34768. */
  34769. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34770. this._areTexturesDirty = true;
  34771. this._isDirty = true;
  34772. };
  34773. /**
  34774. * Marks the fresnel state as changed
  34775. */
  34776. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34777. this._areFresnelDirty = true;
  34778. this._isDirty = true;
  34779. };
  34780. /**
  34781. * Marks the misc state as changed
  34782. */
  34783. MaterialDefines.prototype.markAsMiscDirty = function () {
  34784. this._areMiscDirty = true;
  34785. this._isDirty = true;
  34786. };
  34787. /**
  34788. * Rebuilds the material defines
  34789. */
  34790. MaterialDefines.prototype.rebuild = function () {
  34791. if (this._keys) {
  34792. delete this._keys;
  34793. }
  34794. this._keys = [];
  34795. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34796. var key = _a[_i];
  34797. if (key[0] === "_") {
  34798. continue;
  34799. }
  34800. this._keys.push(key);
  34801. }
  34802. };
  34803. /**
  34804. * Specifies if two material defines are equal
  34805. * @param other - A material define instance to compare to
  34806. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34807. */
  34808. MaterialDefines.prototype.isEqual = function (other) {
  34809. if (this._keys.length !== other._keys.length) {
  34810. return false;
  34811. }
  34812. for (var index = 0; index < this._keys.length; index++) {
  34813. var prop = this._keys[index];
  34814. if (this[prop] !== other[prop]) {
  34815. return false;
  34816. }
  34817. }
  34818. return true;
  34819. };
  34820. /**
  34821. * Clones this instance's defines to another instance
  34822. * @param other - material defines to clone values to
  34823. */
  34824. MaterialDefines.prototype.cloneTo = function (other) {
  34825. if (this._keys.length !== other._keys.length) {
  34826. other._keys = this._keys.slice(0);
  34827. }
  34828. for (var index = 0; index < this._keys.length; index++) {
  34829. var prop = this._keys[index];
  34830. other[prop] = this[prop];
  34831. }
  34832. };
  34833. /**
  34834. * Resets the material define values
  34835. */
  34836. MaterialDefines.prototype.reset = function () {
  34837. for (var index = 0; index < this._keys.length; index++) {
  34838. var prop = this._keys[index];
  34839. var type = typeof this[prop];
  34840. switch (type) {
  34841. case "number":
  34842. this[prop] = 0;
  34843. break;
  34844. case "string":
  34845. this[prop] = "";
  34846. break;
  34847. default:
  34848. this[prop] = false;
  34849. break;
  34850. }
  34851. }
  34852. };
  34853. /**
  34854. * Converts the material define values to a string
  34855. * @returns - String of material define information
  34856. */
  34857. MaterialDefines.prototype.toString = function () {
  34858. var result = "";
  34859. for (var index = 0; index < this._keys.length; index++) {
  34860. var prop = this._keys[index];
  34861. var value = this[prop];
  34862. var type = typeof value;
  34863. switch (type) {
  34864. case "number":
  34865. case "string":
  34866. result += "#define " + prop + " " + value + "\n";
  34867. break;
  34868. default:
  34869. if (value) {
  34870. result += "#define " + prop + "\n";
  34871. }
  34872. break;
  34873. }
  34874. }
  34875. return result;
  34876. };
  34877. return MaterialDefines;
  34878. }());
  34879. BABYLON.MaterialDefines = MaterialDefines;
  34880. /**
  34881. * Base class for the main features of a material in Babylon.js
  34882. */
  34883. var Material = /** @class */ (function () {
  34884. /**
  34885. * Creates a material instance
  34886. * @param name defines the name of the material
  34887. * @param scene defines the scene to reference
  34888. * @param doNotAdd specifies if the material should be added to the scene
  34889. */
  34890. function Material(name, scene, doNotAdd) {
  34891. /**
  34892. * Specifies if the ready state should be checked on each call
  34893. */
  34894. this.checkReadyOnEveryCall = false;
  34895. /**
  34896. * Specifies if the ready state should be checked once
  34897. */
  34898. this.checkReadyOnlyOnce = false;
  34899. /**
  34900. * The state of the material
  34901. */
  34902. this.state = "";
  34903. /**
  34904. * The alpha value of the material
  34905. */
  34906. this._alpha = 1.0;
  34907. /**
  34908. * Specifies if back face culling is enabled
  34909. */
  34910. this._backFaceCulling = true;
  34911. /**
  34912. * Specifies if the material should be serialized
  34913. */
  34914. this.doNotSerialize = false;
  34915. /**
  34916. * Specifies if the effect should be stored on sub meshes
  34917. */
  34918. this.storeEffectOnSubMeshes = false;
  34919. /**
  34920. * An event triggered when the material is disposed
  34921. */
  34922. this.onDisposeObservable = new BABYLON.Observable();
  34923. /**
  34924. * An event triggered when the material is bound
  34925. */
  34926. this.onBindObservable = new BABYLON.Observable();
  34927. /**
  34928. * An event triggered when the material is unbound
  34929. */
  34930. this.onUnBindObservable = new BABYLON.Observable();
  34931. /**
  34932. * Stores the value of the alpha mode
  34933. */
  34934. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34935. /**
  34936. * Stores the state of the need depth pre-pass value
  34937. */
  34938. this._needDepthPrePass = false;
  34939. /**
  34940. * Specifies if depth writing should be disabled
  34941. */
  34942. this.disableDepthWrite = false;
  34943. /**
  34944. * Specifies if depth writing should be forced
  34945. */
  34946. this.forceDepthWrite = false;
  34947. /**
  34948. * Specifies if there should be a separate pass for culling
  34949. */
  34950. this.separateCullingPass = false;
  34951. /**
  34952. * Stores the state specifing if fog should be enabled
  34953. */
  34954. this._fogEnabled = true;
  34955. /**
  34956. * Stores the size of points
  34957. */
  34958. this.pointSize = 1.0;
  34959. /**
  34960. * Stores the z offset value
  34961. */
  34962. this.zOffset = 0;
  34963. /**
  34964. * Specifies if the material was previously ready
  34965. */
  34966. this._wasPreviouslyReady = false;
  34967. /**
  34968. * Stores the fill mode state
  34969. */
  34970. this._fillMode = Material.TriangleFillMode;
  34971. this.name = name;
  34972. this.id = name || BABYLON.Tools.RandomId();
  34973. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34974. this.uniqueId = this._scene.getUniqueId();
  34975. if (this._scene.useRightHandedSystem) {
  34976. this.sideOrientation = Material.ClockWiseSideOrientation;
  34977. }
  34978. else {
  34979. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34980. }
  34981. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34982. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34983. if (!doNotAdd) {
  34984. this._scene.materials.push(this);
  34985. }
  34986. }
  34987. Object.defineProperty(Material, "TriangleFillMode", {
  34988. /**
  34989. * Returns the triangle fill mode
  34990. */
  34991. get: function () {
  34992. return Material._TriangleFillMode;
  34993. },
  34994. enumerable: true,
  34995. configurable: true
  34996. });
  34997. Object.defineProperty(Material, "WireFrameFillMode", {
  34998. /**
  34999. * Returns the wireframe mode
  35000. */
  35001. get: function () {
  35002. return Material._WireFrameFillMode;
  35003. },
  35004. enumerable: true,
  35005. configurable: true
  35006. });
  35007. Object.defineProperty(Material, "PointFillMode", {
  35008. /**
  35009. * Returns the point fill mode
  35010. */
  35011. get: function () {
  35012. return Material._PointFillMode;
  35013. },
  35014. enumerable: true,
  35015. configurable: true
  35016. });
  35017. Object.defineProperty(Material, "PointListDrawMode", {
  35018. /**
  35019. * Returns the point list draw mode
  35020. */
  35021. get: function () {
  35022. return Material._PointListDrawMode;
  35023. },
  35024. enumerable: true,
  35025. configurable: true
  35026. });
  35027. Object.defineProperty(Material, "LineListDrawMode", {
  35028. /**
  35029. * Returns the line list draw mode
  35030. */
  35031. get: function () {
  35032. return Material._LineListDrawMode;
  35033. },
  35034. enumerable: true,
  35035. configurable: true
  35036. });
  35037. Object.defineProperty(Material, "LineLoopDrawMode", {
  35038. /**
  35039. * Returns the line loop draw mode
  35040. */
  35041. get: function () {
  35042. return Material._LineLoopDrawMode;
  35043. },
  35044. enumerable: true,
  35045. configurable: true
  35046. });
  35047. Object.defineProperty(Material, "LineStripDrawMode", {
  35048. /**
  35049. * Returns the line strip draw mode
  35050. */
  35051. get: function () {
  35052. return Material._LineStripDrawMode;
  35053. },
  35054. enumerable: true,
  35055. configurable: true
  35056. });
  35057. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35058. /**
  35059. * Returns the triangle strip draw mode
  35060. */
  35061. get: function () {
  35062. return Material._TriangleStripDrawMode;
  35063. },
  35064. enumerable: true,
  35065. configurable: true
  35066. });
  35067. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35068. /**
  35069. * Returns the triangle fan draw mode
  35070. */
  35071. get: function () {
  35072. return Material._TriangleFanDrawMode;
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35078. /**
  35079. * Returns the clock-wise side orientation
  35080. */
  35081. get: function () {
  35082. return Material._ClockWiseSideOrientation;
  35083. },
  35084. enumerable: true,
  35085. configurable: true
  35086. });
  35087. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35088. /**
  35089. * Returns the counter clock-wise side orientation
  35090. */
  35091. get: function () {
  35092. return Material._CounterClockWiseSideOrientation;
  35093. },
  35094. enumerable: true,
  35095. configurable: true
  35096. });
  35097. Object.defineProperty(Material, "TextureDirtyFlag", {
  35098. /**
  35099. * Returns the dirty texture flag value
  35100. */
  35101. get: function () {
  35102. return Material._TextureDirtyFlag;
  35103. },
  35104. enumerable: true,
  35105. configurable: true
  35106. });
  35107. Object.defineProperty(Material, "LightDirtyFlag", {
  35108. /**
  35109. * Returns the dirty light flag value
  35110. */
  35111. get: function () {
  35112. return Material._LightDirtyFlag;
  35113. },
  35114. enumerable: true,
  35115. configurable: true
  35116. });
  35117. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35118. /**
  35119. * Returns the dirty fresnel flag value
  35120. */
  35121. get: function () {
  35122. return Material._FresnelDirtyFlag;
  35123. },
  35124. enumerable: true,
  35125. configurable: true
  35126. });
  35127. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35128. /**
  35129. * Returns the dirty attributes flag value
  35130. */
  35131. get: function () {
  35132. return Material._AttributesDirtyFlag;
  35133. },
  35134. enumerable: true,
  35135. configurable: true
  35136. });
  35137. Object.defineProperty(Material, "MiscDirtyFlag", {
  35138. /**
  35139. * Returns the dirty misc flag value
  35140. */
  35141. get: function () {
  35142. return Material._MiscDirtyFlag;
  35143. },
  35144. enumerable: true,
  35145. configurable: true
  35146. });
  35147. Object.defineProperty(Material.prototype, "alpha", {
  35148. /**
  35149. * Gets the alpha value of the material
  35150. */
  35151. get: function () {
  35152. return this._alpha;
  35153. },
  35154. /**
  35155. * Sets the alpha value of the material
  35156. */
  35157. set: function (value) {
  35158. if (this._alpha === value) {
  35159. return;
  35160. }
  35161. this._alpha = value;
  35162. this.markAsDirty(Material.MiscDirtyFlag);
  35163. },
  35164. enumerable: true,
  35165. configurable: true
  35166. });
  35167. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35168. /**
  35169. * Gets the back-face culling state
  35170. */
  35171. get: function () {
  35172. return this._backFaceCulling;
  35173. },
  35174. /**
  35175. * Sets the back-face culling state
  35176. */
  35177. set: function (value) {
  35178. if (this._backFaceCulling === value) {
  35179. return;
  35180. }
  35181. this._backFaceCulling = value;
  35182. this.markAsDirty(Material.TextureDirtyFlag);
  35183. },
  35184. enumerable: true,
  35185. configurable: true
  35186. });
  35187. Object.defineProperty(Material.prototype, "onDispose", {
  35188. /**
  35189. * Called during a dispose event
  35190. */
  35191. set: function (callback) {
  35192. if (this._onDisposeObserver) {
  35193. this.onDisposeObservable.remove(this._onDisposeObserver);
  35194. }
  35195. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35196. },
  35197. enumerable: true,
  35198. configurable: true
  35199. });
  35200. Object.defineProperty(Material.prototype, "onBind", {
  35201. /**
  35202. * Called during a bind event
  35203. */
  35204. set: function (callback) {
  35205. if (this._onBindObserver) {
  35206. this.onBindObservable.remove(this._onBindObserver);
  35207. }
  35208. this._onBindObserver = this.onBindObservable.add(callback);
  35209. },
  35210. enumerable: true,
  35211. configurable: true
  35212. });
  35213. Object.defineProperty(Material.prototype, "alphaMode", {
  35214. /**
  35215. * Gets the value of the alpha mode
  35216. */
  35217. get: function () {
  35218. return this._alphaMode;
  35219. },
  35220. /**
  35221. * Sets the value of the alpha mode.
  35222. *
  35223. * | Value | Type | Description |
  35224. * | --- | --- | --- |
  35225. * | 0 | ALPHA_DISABLE | |
  35226. * | 1 | ALPHA_ADD | |
  35227. * | 2 | ALPHA_COMBINE | |
  35228. * | 3 | ALPHA_SUBTRACT | |
  35229. * | 4 | ALPHA_MULTIPLY | |
  35230. * | 5 | ALPHA_MAXIMIZED | |
  35231. * | 6 | ALPHA_ONEONE | |
  35232. * | 7 | ALPHA_PREMULTIPLIED | |
  35233. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35234. * | 9 | ALPHA_INTERPOLATE | |
  35235. * | 10 | ALPHA_SCREENMODE | |
  35236. *
  35237. */
  35238. set: function (value) {
  35239. if (this._alphaMode === value) {
  35240. return;
  35241. }
  35242. this._alphaMode = value;
  35243. this.markAsDirty(Material.TextureDirtyFlag);
  35244. },
  35245. enumerable: true,
  35246. configurable: true
  35247. });
  35248. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35249. /**
  35250. * Gets the depth pre-pass value
  35251. */
  35252. get: function () {
  35253. return this._needDepthPrePass;
  35254. },
  35255. /**
  35256. * Sets the need depth pre-pass value
  35257. */
  35258. set: function (value) {
  35259. if (this._needDepthPrePass === value) {
  35260. return;
  35261. }
  35262. this._needDepthPrePass = value;
  35263. if (this._needDepthPrePass) {
  35264. this.checkReadyOnEveryCall = true;
  35265. }
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(Material.prototype, "fogEnabled", {
  35271. /**
  35272. * Gets the value of the fog enabled state
  35273. */
  35274. get: function () {
  35275. return this._fogEnabled;
  35276. },
  35277. /**
  35278. * Sets the state for enabling fog
  35279. */
  35280. set: function (value) {
  35281. if (this._fogEnabled === value) {
  35282. return;
  35283. }
  35284. this._fogEnabled = value;
  35285. this.markAsDirty(Material.MiscDirtyFlag);
  35286. },
  35287. enumerable: true,
  35288. configurable: true
  35289. });
  35290. Object.defineProperty(Material.prototype, "wireframe", {
  35291. /**
  35292. * Gets a value specifying if wireframe mode is enabled
  35293. */
  35294. get: function () {
  35295. switch (this._fillMode) {
  35296. case Material.WireFrameFillMode:
  35297. case Material.LineListDrawMode:
  35298. case Material.LineLoopDrawMode:
  35299. case Material.LineStripDrawMode:
  35300. return true;
  35301. }
  35302. return this._scene.forceWireframe;
  35303. },
  35304. /**
  35305. * Sets the state of wireframe mode
  35306. */
  35307. set: function (value) {
  35308. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35309. },
  35310. enumerable: true,
  35311. configurable: true
  35312. });
  35313. Object.defineProperty(Material.prototype, "pointsCloud", {
  35314. /**
  35315. * Gets the value specifying if point clouds are enabled
  35316. */
  35317. get: function () {
  35318. switch (this._fillMode) {
  35319. case Material.PointFillMode:
  35320. case Material.PointListDrawMode:
  35321. return true;
  35322. }
  35323. return this._scene.forcePointsCloud;
  35324. },
  35325. /**
  35326. * Sets the state of point cloud mode
  35327. */
  35328. set: function (value) {
  35329. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35330. },
  35331. enumerable: true,
  35332. configurable: true
  35333. });
  35334. Object.defineProperty(Material.prototype, "fillMode", {
  35335. /**
  35336. * Gets the material fill mode
  35337. */
  35338. get: function () {
  35339. return this._fillMode;
  35340. },
  35341. /**
  35342. * Sets the material fill mode
  35343. */
  35344. set: function (value) {
  35345. if (this._fillMode === value) {
  35346. return;
  35347. }
  35348. this._fillMode = value;
  35349. this.markAsDirty(Material.MiscDirtyFlag);
  35350. },
  35351. enumerable: true,
  35352. configurable: true
  35353. });
  35354. /**
  35355. * Returns a string representation of the current material
  35356. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35357. * @returns a string with material information
  35358. */
  35359. Material.prototype.toString = function (fullDetails) {
  35360. var ret = "Name: " + this.name;
  35361. if (fullDetails) {
  35362. }
  35363. return ret;
  35364. };
  35365. /**
  35366. * Gets the class name of the material
  35367. * @returns a string with the class name of the material
  35368. */
  35369. Material.prototype.getClassName = function () {
  35370. return "Material";
  35371. };
  35372. Object.defineProperty(Material.prototype, "isFrozen", {
  35373. /**
  35374. * Specifies if updates for the material been locked
  35375. */
  35376. get: function () {
  35377. return this.checkReadyOnlyOnce;
  35378. },
  35379. enumerable: true,
  35380. configurable: true
  35381. });
  35382. /**
  35383. * Locks updates for the material
  35384. */
  35385. Material.prototype.freeze = function () {
  35386. this.checkReadyOnlyOnce = true;
  35387. };
  35388. /**
  35389. * Unlocks updates for the material
  35390. */
  35391. Material.prototype.unfreeze = function () {
  35392. this.checkReadyOnlyOnce = false;
  35393. };
  35394. /**
  35395. * Specifies if the material is ready to be used
  35396. * @param mesh defines the mesh to check
  35397. * @param useInstances specifies if instances should be used
  35398. * @returns a boolean indicating if the material is ready to be used
  35399. */
  35400. Material.prototype.isReady = function (mesh, useInstances) {
  35401. return true;
  35402. };
  35403. /**
  35404. * Specifies that the submesh is ready to be used
  35405. * @param mesh defines the mesh to check
  35406. * @param subMesh defines which submesh to check
  35407. * @param useInstances specifies that instances should be used
  35408. * @returns a boolean indicating that the submesh is ready or not
  35409. */
  35410. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35411. return false;
  35412. };
  35413. /**
  35414. * Returns the material effect
  35415. * @returns the effect associated with the material
  35416. */
  35417. Material.prototype.getEffect = function () {
  35418. return this._effect;
  35419. };
  35420. /**
  35421. * Returns the current scene
  35422. * @returns a Scene
  35423. */
  35424. Material.prototype.getScene = function () {
  35425. return this._scene;
  35426. };
  35427. /**
  35428. * Specifies if the material will require alpha blending
  35429. * @returns a boolean specifying if alpha blending is needed
  35430. */
  35431. Material.prototype.needAlphaBlending = function () {
  35432. return (this.alpha < 1.0);
  35433. };
  35434. /**
  35435. * Specifies if the mesh will require alpha blending
  35436. * @param mesh defines the mesh to check
  35437. * @returns a boolean specifying if alpha blending is needed for the mesh
  35438. */
  35439. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35440. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35441. };
  35442. /**
  35443. * Specifies if this material should be rendered in alpha test mode
  35444. * @returns a boolean specifying if an alpha test is needed.
  35445. */
  35446. Material.prototype.needAlphaTesting = function () {
  35447. return false;
  35448. };
  35449. /**
  35450. * Gets the texture used for the alpha test
  35451. * @returns the texture to use for alpha testing
  35452. */
  35453. Material.prototype.getAlphaTestTexture = function () {
  35454. return null;
  35455. };
  35456. /**
  35457. * Marks the material to indicate that it needs to be re-calculated
  35458. */
  35459. Material.prototype.markDirty = function () {
  35460. this._wasPreviouslyReady = false;
  35461. };
  35462. /** @hidden */
  35463. Material.prototype._preBind = function (effect, overrideOrientation) {
  35464. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35465. var engine = this._scene.getEngine();
  35466. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35467. var reverse = orientation === Material.ClockWiseSideOrientation;
  35468. engine.enableEffect(effect ? effect : this._effect);
  35469. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35470. return reverse;
  35471. };
  35472. /**
  35473. * Binds the material to the mesh
  35474. * @param world defines the world transformation matrix
  35475. * @param mesh defines the mesh to bind the material to
  35476. */
  35477. Material.prototype.bind = function (world, mesh) {
  35478. };
  35479. /**
  35480. * Binds the submesh to the material
  35481. * @param world defines the world transformation matrix
  35482. * @param mesh defines the mesh containing the submesh
  35483. * @param subMesh defines the submesh to bind the material to
  35484. */
  35485. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35486. };
  35487. /**
  35488. * Binds the world matrix to the material
  35489. * @param world defines the world transformation matrix
  35490. */
  35491. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35492. };
  35493. /**
  35494. * Binds the scene's uniform buffer to the effect.
  35495. * @param effect defines the effect to bind to the scene uniform buffer
  35496. * @param sceneUbo defines the uniform buffer storing scene data
  35497. */
  35498. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35499. sceneUbo.bindToEffect(effect, "Scene");
  35500. };
  35501. /**
  35502. * Binds the view matrix to the effect
  35503. * @param effect defines the effect to bind the view matrix to
  35504. */
  35505. Material.prototype.bindView = function (effect) {
  35506. if (!this._useUBO) {
  35507. effect.setMatrix("view", this.getScene().getViewMatrix());
  35508. }
  35509. else {
  35510. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35511. }
  35512. };
  35513. /**
  35514. * Binds the view projection matrix to the effect
  35515. * @param effect defines the effect to bind the view projection matrix to
  35516. */
  35517. Material.prototype.bindViewProjection = function (effect) {
  35518. if (!this._useUBO) {
  35519. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35520. }
  35521. else {
  35522. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35523. }
  35524. };
  35525. /**
  35526. * Specifies if material alpha testing should be turned on for the mesh
  35527. * @param mesh defines the mesh to check
  35528. */
  35529. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35530. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35531. };
  35532. /**
  35533. * Processes to execute after binding the material to a mesh
  35534. * @param mesh defines the rendered mesh
  35535. */
  35536. Material.prototype._afterBind = function (mesh) {
  35537. this._scene._cachedMaterial = this;
  35538. if (mesh) {
  35539. this._scene._cachedVisibility = mesh.visibility;
  35540. }
  35541. else {
  35542. this._scene._cachedVisibility = 1;
  35543. }
  35544. if (mesh) {
  35545. this.onBindObservable.notifyObservers(mesh);
  35546. }
  35547. if (this.disableDepthWrite) {
  35548. var engine = this._scene.getEngine();
  35549. this._cachedDepthWriteState = engine.getDepthWrite();
  35550. engine.setDepthWrite(false);
  35551. }
  35552. };
  35553. /**
  35554. * Unbinds the material from the mesh
  35555. */
  35556. Material.prototype.unbind = function () {
  35557. this.onUnBindObservable.notifyObservers(this);
  35558. if (this.disableDepthWrite) {
  35559. var engine = this._scene.getEngine();
  35560. engine.setDepthWrite(this._cachedDepthWriteState);
  35561. }
  35562. };
  35563. /**
  35564. * Gets the active textures from the material
  35565. * @returns an array of textures
  35566. */
  35567. Material.prototype.getActiveTextures = function () {
  35568. return [];
  35569. };
  35570. /**
  35571. * Specifies if the material uses a texture
  35572. * @param texture defines the texture to check against the material
  35573. * @returns a boolean specifying if the material uses the texture
  35574. */
  35575. Material.prototype.hasTexture = function (texture) {
  35576. return false;
  35577. };
  35578. /**
  35579. * Makes a duplicate of the material, and gives it a new name
  35580. * @param name defines the new name for the duplicated material
  35581. * @returns the cloned material
  35582. */
  35583. Material.prototype.clone = function (name) {
  35584. return null;
  35585. };
  35586. /**
  35587. * Gets the meshes bound to the material
  35588. * @returns an array of meshes bound to the material
  35589. */
  35590. Material.prototype.getBindedMeshes = function () {
  35591. var result = new Array();
  35592. for (var index = 0; index < this._scene.meshes.length; index++) {
  35593. var mesh = this._scene.meshes[index];
  35594. if (mesh.material === this) {
  35595. result.push(mesh);
  35596. }
  35597. }
  35598. return result;
  35599. };
  35600. /**
  35601. * Force shader compilation
  35602. * @param mesh defines the mesh associated with this material
  35603. * @param onCompiled defines a function to execute once the material is compiled
  35604. * @param options defines the options to configure the compilation
  35605. */
  35606. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35607. var _this = this;
  35608. var localOptions = __assign({ clipPlane: false }, options);
  35609. var subMesh = new BABYLON.BaseSubMesh();
  35610. var scene = this.getScene();
  35611. var checkReady = function () {
  35612. if (!_this._scene || !_this._scene.getEngine()) {
  35613. return;
  35614. }
  35615. if (subMesh._materialDefines) {
  35616. subMesh._materialDefines._renderId = -1;
  35617. }
  35618. var clipPlaneState = scene.clipPlane;
  35619. if (localOptions.clipPlane) {
  35620. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35621. }
  35622. if (_this.storeEffectOnSubMeshes) {
  35623. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35624. if (onCompiled) {
  35625. onCompiled(_this);
  35626. }
  35627. }
  35628. else {
  35629. setTimeout(checkReady, 16);
  35630. }
  35631. }
  35632. else {
  35633. if (_this.isReady(mesh)) {
  35634. if (onCompiled) {
  35635. onCompiled(_this);
  35636. }
  35637. }
  35638. else {
  35639. setTimeout(checkReady, 16);
  35640. }
  35641. }
  35642. if (localOptions.clipPlane) {
  35643. scene.clipPlane = clipPlaneState;
  35644. }
  35645. };
  35646. checkReady();
  35647. };
  35648. /**
  35649. * Force shader compilation
  35650. * @param mesh defines the mesh that will use this material
  35651. * @param options defines additional options for compiling the shaders
  35652. * @returns a promise that resolves when the compilation completes
  35653. */
  35654. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35655. var _this = this;
  35656. return new Promise(function (resolve) {
  35657. _this.forceCompilation(mesh, function () {
  35658. resolve();
  35659. }, options);
  35660. });
  35661. };
  35662. /**
  35663. * Marks a define in the material to indicate that it needs to be re-computed
  35664. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35665. */
  35666. Material.prototype.markAsDirty = function (flag) {
  35667. if (flag & Material.TextureDirtyFlag) {
  35668. this._markAllSubMeshesAsTexturesDirty();
  35669. }
  35670. if (flag & Material.LightDirtyFlag) {
  35671. this._markAllSubMeshesAsLightsDirty();
  35672. }
  35673. if (flag & Material.FresnelDirtyFlag) {
  35674. this._markAllSubMeshesAsFresnelDirty();
  35675. }
  35676. if (flag & Material.AttributesDirtyFlag) {
  35677. this._markAllSubMeshesAsAttributesDirty();
  35678. }
  35679. if (flag & Material.MiscDirtyFlag) {
  35680. this._markAllSubMeshesAsMiscDirty();
  35681. }
  35682. this.getScene().resetCachedMaterial();
  35683. };
  35684. /**
  35685. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35686. * @param func defines a function which checks material defines against the submeshes
  35687. */
  35688. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35689. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35690. var mesh = _a[_i];
  35691. if (!mesh.subMeshes) {
  35692. continue;
  35693. }
  35694. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35695. var subMesh = _c[_b];
  35696. if (subMesh.getMaterial() !== this) {
  35697. continue;
  35698. }
  35699. if (!subMesh._materialDefines) {
  35700. continue;
  35701. }
  35702. func(subMesh._materialDefines);
  35703. }
  35704. }
  35705. };
  35706. /**
  35707. * Indicates that image processing needs to be re-calculated for all submeshes
  35708. */
  35709. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35710. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35711. };
  35712. /**
  35713. * Indicates that textures need to be re-calculated for all submeshes
  35714. */
  35715. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35716. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35717. };
  35718. /**
  35719. * Indicates that fresnel needs to be re-calculated for all submeshes
  35720. */
  35721. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35722. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35723. };
  35724. /**
  35725. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35726. */
  35727. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35728. this._markAllSubMeshesAsDirty(function (defines) {
  35729. defines.markAsFresnelDirty();
  35730. defines.markAsMiscDirty();
  35731. });
  35732. };
  35733. /**
  35734. * Indicates that lights need to be re-calculated for all submeshes
  35735. */
  35736. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35737. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35738. };
  35739. /**
  35740. * Indicates that attributes need to be re-calculated for all submeshes
  35741. */
  35742. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35743. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35744. };
  35745. /**
  35746. * Indicates that misc needs to be re-calculated for all submeshes
  35747. */
  35748. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35749. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35750. };
  35751. /**
  35752. * Indicates that textures and misc need to be re-calculated for all submeshes
  35753. */
  35754. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35755. this._markAllSubMeshesAsDirty(function (defines) {
  35756. defines.markAsTexturesDirty();
  35757. defines.markAsMiscDirty();
  35758. });
  35759. };
  35760. /**
  35761. * Disposes the material
  35762. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35763. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35764. */
  35765. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35766. // Animations
  35767. this.getScene().stopAnimation(this);
  35768. this.getScene().freeProcessedMaterials();
  35769. // Remove from scene
  35770. var index = this._scene.materials.indexOf(this);
  35771. if (index >= 0) {
  35772. this._scene.materials.splice(index, 1);
  35773. }
  35774. // Remove from meshes
  35775. for (index = 0; index < this._scene.meshes.length; index++) {
  35776. var mesh = this._scene.meshes[index];
  35777. if (mesh.material === this) {
  35778. mesh.material = null;
  35779. if (mesh.geometry) {
  35780. var geometry = (mesh.geometry);
  35781. if (this.storeEffectOnSubMeshes) {
  35782. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35783. var subMesh = _a[_i];
  35784. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35785. if (forceDisposeEffect && subMesh._materialEffect) {
  35786. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35787. }
  35788. }
  35789. }
  35790. else {
  35791. geometry._releaseVertexArrayObject(this._effect);
  35792. }
  35793. }
  35794. }
  35795. }
  35796. this._uniformBuffer.dispose();
  35797. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35798. if (forceDisposeEffect && this._effect) {
  35799. if (!this.storeEffectOnSubMeshes) {
  35800. this._scene.getEngine()._releaseEffect(this._effect);
  35801. }
  35802. this._effect = null;
  35803. }
  35804. // Callback
  35805. this.onDisposeObservable.notifyObservers(this);
  35806. this.onDisposeObservable.clear();
  35807. this.onBindObservable.clear();
  35808. this.onUnBindObservable.clear();
  35809. };
  35810. /**
  35811. * Serializes this material
  35812. * @returns the serialized material object
  35813. */
  35814. Material.prototype.serialize = function () {
  35815. return BABYLON.SerializationHelper.Serialize(this);
  35816. };
  35817. /**
  35818. * Creates a MultiMaterial from parsed MultiMaterial data.
  35819. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35820. * @param scene defines the hosting scene
  35821. * @returns a new MultiMaterial
  35822. */
  35823. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35824. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35825. multiMaterial.id = parsedMultiMaterial.id;
  35826. if (BABYLON.Tags) {
  35827. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35828. }
  35829. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35830. var subMatId = parsedMultiMaterial.materials[matIndex];
  35831. if (subMatId) {
  35832. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35833. }
  35834. else {
  35835. multiMaterial.subMaterials.push(null);
  35836. }
  35837. }
  35838. return multiMaterial;
  35839. };
  35840. /**
  35841. * Creates a material from parsed material data
  35842. * @param parsedMaterial defines parsed material data
  35843. * @param scene defines the hosting scene
  35844. * @param rootUrl defines the root URL to use to load textures
  35845. * @returns a new material
  35846. */
  35847. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35848. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35849. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35850. }
  35851. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35852. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35853. if (!BABYLON.LegacyPBRMaterial) {
  35854. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35855. return;
  35856. }
  35857. }
  35858. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35859. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35860. };
  35861. // Triangle views
  35862. Material._TriangleFillMode = 0;
  35863. Material._WireFrameFillMode = 1;
  35864. Material._PointFillMode = 2;
  35865. // Draw modes
  35866. Material._PointListDrawMode = 3;
  35867. Material._LineListDrawMode = 4;
  35868. Material._LineLoopDrawMode = 5;
  35869. Material._LineStripDrawMode = 6;
  35870. Material._TriangleStripDrawMode = 7;
  35871. Material._TriangleFanDrawMode = 8;
  35872. /**
  35873. * Stores the clock-wise side orientation
  35874. */
  35875. Material._ClockWiseSideOrientation = 0;
  35876. /**
  35877. * Stores the counter clock-wise side orientation
  35878. */
  35879. Material._CounterClockWiseSideOrientation = 1;
  35880. /**
  35881. * The dirty texture flag value
  35882. */
  35883. Material._TextureDirtyFlag = 1;
  35884. /**
  35885. * The dirty light flag value
  35886. */
  35887. Material._LightDirtyFlag = 2;
  35888. /**
  35889. * The dirty fresnel flag value
  35890. */
  35891. Material._FresnelDirtyFlag = 4;
  35892. /**
  35893. * The dirty attribute flag value
  35894. */
  35895. Material._AttributesDirtyFlag = 8;
  35896. /**
  35897. * The dirty misc flag value
  35898. */
  35899. Material._MiscDirtyFlag = 16;
  35900. __decorate([
  35901. BABYLON.serialize()
  35902. ], Material.prototype, "id", void 0);
  35903. __decorate([
  35904. BABYLON.serialize()
  35905. ], Material.prototype, "uniqueId", void 0);
  35906. __decorate([
  35907. BABYLON.serialize()
  35908. ], Material.prototype, "name", void 0);
  35909. __decorate([
  35910. BABYLON.serialize()
  35911. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35912. __decorate([
  35913. BABYLON.serialize()
  35914. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35915. __decorate([
  35916. BABYLON.serialize()
  35917. ], Material.prototype, "state", void 0);
  35918. __decorate([
  35919. BABYLON.serialize("alpha")
  35920. ], Material.prototype, "_alpha", void 0);
  35921. __decorate([
  35922. BABYLON.serialize("backFaceCulling")
  35923. ], Material.prototype, "_backFaceCulling", void 0);
  35924. __decorate([
  35925. BABYLON.serialize()
  35926. ], Material.prototype, "sideOrientation", void 0);
  35927. __decorate([
  35928. BABYLON.serialize("alphaMode")
  35929. ], Material.prototype, "_alphaMode", void 0);
  35930. __decorate([
  35931. BABYLON.serialize()
  35932. ], Material.prototype, "_needDepthPrePass", void 0);
  35933. __decorate([
  35934. BABYLON.serialize()
  35935. ], Material.prototype, "disableDepthWrite", void 0);
  35936. __decorate([
  35937. BABYLON.serialize()
  35938. ], Material.prototype, "forceDepthWrite", void 0);
  35939. __decorate([
  35940. BABYLON.serialize()
  35941. ], Material.prototype, "separateCullingPass", void 0);
  35942. __decorate([
  35943. BABYLON.serialize("fogEnabled")
  35944. ], Material.prototype, "_fogEnabled", void 0);
  35945. __decorate([
  35946. BABYLON.serialize()
  35947. ], Material.prototype, "pointSize", void 0);
  35948. __decorate([
  35949. BABYLON.serialize()
  35950. ], Material.prototype, "zOffset", void 0);
  35951. __decorate([
  35952. BABYLON.serialize()
  35953. ], Material.prototype, "wireframe", null);
  35954. __decorate([
  35955. BABYLON.serialize()
  35956. ], Material.prototype, "pointsCloud", null);
  35957. __decorate([
  35958. BABYLON.serialize()
  35959. ], Material.prototype, "fillMode", null);
  35960. return Material;
  35961. }());
  35962. BABYLON.Material = Material;
  35963. })(BABYLON || (BABYLON = {}));
  35964. //# sourceMappingURL=babylon.material.js.map
  35965. var BABYLON;
  35966. (function (BABYLON) {
  35967. var UniformBuffer = /** @class */ (function () {
  35968. /**
  35969. * Uniform buffer objects.
  35970. *
  35971. * Handles blocks of uniform on the GPU.
  35972. *
  35973. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35974. *
  35975. * For more information, please refer to :
  35976. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35977. */
  35978. function UniformBuffer(engine, data, dynamic) {
  35979. this._engine = engine;
  35980. this._noUBO = !engine.supportsUniformBuffers;
  35981. this._dynamic = dynamic;
  35982. this._data = data || [];
  35983. this._uniformLocations = {};
  35984. this._uniformSizes = {};
  35985. this._uniformLocationPointer = 0;
  35986. this._needSync = false;
  35987. if (this._noUBO) {
  35988. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35989. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35990. this.updateFloat = this._updateFloatForEffect;
  35991. this.updateFloat2 = this._updateFloat2ForEffect;
  35992. this.updateFloat3 = this._updateFloat3ForEffect;
  35993. this.updateFloat4 = this._updateFloat4ForEffect;
  35994. this.updateMatrix = this._updateMatrixForEffect;
  35995. this.updateVector3 = this._updateVector3ForEffect;
  35996. this.updateVector4 = this._updateVector4ForEffect;
  35997. this.updateColor3 = this._updateColor3ForEffect;
  35998. this.updateColor4 = this._updateColor4ForEffect;
  35999. }
  36000. else {
  36001. this._engine._uniformBuffers.push(this);
  36002. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36003. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36004. this.updateFloat = this._updateFloatForUniform;
  36005. this.updateFloat2 = this._updateFloat2ForUniform;
  36006. this.updateFloat3 = this._updateFloat3ForUniform;
  36007. this.updateFloat4 = this._updateFloat4ForUniform;
  36008. this.updateMatrix = this._updateMatrixForUniform;
  36009. this.updateVector3 = this._updateVector3ForUniform;
  36010. this.updateVector4 = this._updateVector4ForUniform;
  36011. this.updateColor3 = this._updateColor3ForUniform;
  36012. this.updateColor4 = this._updateColor4ForUniform;
  36013. }
  36014. }
  36015. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36016. // Properties
  36017. /**
  36018. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36019. * or just falling back on setUniformXXX calls.
  36020. */
  36021. get: function () {
  36022. return !this._noUBO;
  36023. },
  36024. enumerable: true,
  36025. configurable: true
  36026. });
  36027. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36028. /**
  36029. * Indicates if the WebGL underlying uniform buffer is in sync
  36030. * with the javascript cache data.
  36031. */
  36032. get: function () {
  36033. return !this._needSync;
  36034. },
  36035. enumerable: true,
  36036. configurable: true
  36037. });
  36038. /**
  36039. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36040. * Also, a dynamic UniformBuffer will disable cache verification and always
  36041. * update the underlying WebGL uniform buffer to the GPU.
  36042. */
  36043. UniformBuffer.prototype.isDynamic = function () {
  36044. return this._dynamic !== undefined;
  36045. };
  36046. /**
  36047. * The data cache on JS side.
  36048. */
  36049. UniformBuffer.prototype.getData = function () {
  36050. return this._bufferData;
  36051. };
  36052. /**
  36053. * The underlying WebGL Uniform buffer.
  36054. */
  36055. UniformBuffer.prototype.getBuffer = function () {
  36056. return this._buffer;
  36057. };
  36058. /**
  36059. * std140 layout specifies how to align data within an UBO structure.
  36060. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36061. * for specs.
  36062. */
  36063. UniformBuffer.prototype._fillAlignment = function (size) {
  36064. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36065. // and 4x4 matrices
  36066. // TODO : change if other types are used
  36067. var alignment;
  36068. if (size <= 2) {
  36069. alignment = size;
  36070. }
  36071. else {
  36072. alignment = 4;
  36073. }
  36074. if ((this._uniformLocationPointer % alignment) !== 0) {
  36075. var oldPointer = this._uniformLocationPointer;
  36076. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36077. var diff = this._uniformLocationPointer - oldPointer;
  36078. for (var i = 0; i < diff; i++) {
  36079. this._data.push(0);
  36080. }
  36081. }
  36082. };
  36083. /**
  36084. * Adds an uniform in the buffer.
  36085. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36086. * for the layout to be correct !
  36087. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36088. * @param {number|number[]} size Data size, or data directly.
  36089. */
  36090. UniformBuffer.prototype.addUniform = function (name, size) {
  36091. if (this._noUBO) {
  36092. return;
  36093. }
  36094. if (this._uniformLocations[name] !== undefined) {
  36095. // Already existing uniform
  36096. return;
  36097. }
  36098. // This function must be called in the order of the shader layout !
  36099. // size can be the size of the uniform, or data directly
  36100. var data;
  36101. if (size instanceof Array) {
  36102. data = size;
  36103. size = data.length;
  36104. }
  36105. else {
  36106. size = size;
  36107. data = [];
  36108. // Fill with zeros
  36109. for (var i = 0; i < size; i++) {
  36110. data.push(0);
  36111. }
  36112. }
  36113. this._fillAlignment(size);
  36114. this._uniformSizes[name] = size;
  36115. this._uniformLocations[name] = this._uniformLocationPointer;
  36116. this._uniformLocationPointer += size;
  36117. for (var i = 0; i < size; i++) {
  36118. this._data.push(data[i]);
  36119. }
  36120. this._needSync = true;
  36121. };
  36122. /**
  36123. * Wrapper for addUniform.
  36124. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36125. * @param {Matrix} mat A 4x4 matrix.
  36126. */
  36127. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36128. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36129. };
  36130. /**
  36131. * Wrapper for addUniform.
  36132. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36133. * @param {number} x
  36134. * @param {number} y
  36135. */
  36136. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36137. var temp = [x, y];
  36138. this.addUniform(name, temp);
  36139. };
  36140. /**
  36141. * Wrapper for addUniform.
  36142. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36143. * @param {number} x
  36144. * @param {number} y
  36145. * @param {number} z
  36146. */
  36147. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36148. var temp = [x, y, z];
  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. * @param {Color3} color
  36155. */
  36156. UniformBuffer.prototype.addColor3 = function (name, color) {
  36157. var temp = new Array();
  36158. color.toArray(temp);
  36159. this.addUniform(name, temp);
  36160. };
  36161. /**
  36162. * Wrapper for addUniform.
  36163. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36164. * @param {Color3} color
  36165. * @param {number} alpha
  36166. */
  36167. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36168. var temp = new Array();
  36169. color.toArray(temp);
  36170. temp.push(alpha);
  36171. this.addUniform(name, temp);
  36172. };
  36173. /**
  36174. * Wrapper for addUniform.
  36175. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36176. * @param {Vector3} vector
  36177. */
  36178. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36179. var temp = new Array();
  36180. vector.toArray(temp);
  36181. this.addUniform(name, temp);
  36182. };
  36183. /**
  36184. * Wrapper for addUniform.
  36185. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36186. */
  36187. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36188. this.addUniform(name, 12);
  36189. };
  36190. /**
  36191. * Wrapper for addUniform.
  36192. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36193. */
  36194. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36195. this.addUniform(name, 8);
  36196. };
  36197. /**
  36198. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36199. */
  36200. UniformBuffer.prototype.create = function () {
  36201. if (this._noUBO) {
  36202. return;
  36203. }
  36204. if (this._buffer) {
  36205. return; // nothing to do
  36206. }
  36207. // See spec, alignment must be filled as a vec4
  36208. this._fillAlignment(4);
  36209. this._bufferData = new Float32Array(this._data);
  36210. this._rebuild();
  36211. this._needSync = true;
  36212. };
  36213. UniformBuffer.prototype._rebuild = function () {
  36214. if (this._noUBO) {
  36215. return;
  36216. }
  36217. if (this._dynamic) {
  36218. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36219. }
  36220. else {
  36221. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36222. }
  36223. };
  36224. /**
  36225. * Updates the WebGL Uniform Buffer on the GPU.
  36226. * If the `dynamic` flag is set to true, no cache comparison is done.
  36227. * Otherwise, the buffer will be updated only if the cache differs.
  36228. */
  36229. UniformBuffer.prototype.update = function () {
  36230. if (!this._buffer) {
  36231. this.create();
  36232. return;
  36233. }
  36234. if (!this._dynamic && !this._needSync) {
  36235. return;
  36236. }
  36237. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36238. this._needSync = false;
  36239. };
  36240. /**
  36241. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36242. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36243. * @param {number[]|Float32Array} data Flattened data
  36244. * @param {number} size Size of the data.
  36245. */
  36246. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36247. var location = this._uniformLocations[uniformName];
  36248. if (location === undefined) {
  36249. if (this._buffer) {
  36250. // Cannot add an uniform if the buffer is already created
  36251. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36252. return;
  36253. }
  36254. this.addUniform(uniformName, size);
  36255. location = this._uniformLocations[uniformName];
  36256. }
  36257. if (!this._buffer) {
  36258. this.create();
  36259. }
  36260. if (!this._dynamic) {
  36261. // Cache for static uniform buffers
  36262. var changed = false;
  36263. for (var i = 0; i < size; i++) {
  36264. if (this._bufferData[location + i] !== data[i]) {
  36265. changed = true;
  36266. this._bufferData[location + i] = data[i];
  36267. }
  36268. }
  36269. this._needSync = this._needSync || changed;
  36270. }
  36271. else {
  36272. // No cache for dynamic
  36273. for (var i = 0; i < size; i++) {
  36274. this._bufferData[location + i] = data[i];
  36275. }
  36276. }
  36277. };
  36278. // Update methods
  36279. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36280. // To match std140, matrix must be realigned
  36281. for (var i = 0; i < 3; i++) {
  36282. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36283. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36284. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36285. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36286. }
  36287. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36288. };
  36289. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36290. this._currentEffect.setMatrix3x3(name, matrix);
  36291. };
  36292. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36293. this._currentEffect.setMatrix2x2(name, matrix);
  36294. };
  36295. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36296. // To match std140, matrix must be realigned
  36297. for (var i = 0; i < 2; i++) {
  36298. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36299. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36300. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36301. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36302. }
  36303. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36304. };
  36305. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36306. this._currentEffect.setFloat(name, x);
  36307. };
  36308. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36309. UniformBuffer._tempBuffer[0] = x;
  36310. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36311. };
  36312. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36313. if (suffix === void 0) { suffix = ""; }
  36314. this._currentEffect.setFloat2(name + suffix, x, y);
  36315. };
  36316. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36317. if (suffix === void 0) { suffix = ""; }
  36318. UniformBuffer._tempBuffer[0] = x;
  36319. UniformBuffer._tempBuffer[1] = y;
  36320. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36321. };
  36322. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36323. if (suffix === void 0) { suffix = ""; }
  36324. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36325. };
  36326. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36327. if (suffix === void 0) { suffix = ""; }
  36328. UniformBuffer._tempBuffer[0] = x;
  36329. UniformBuffer._tempBuffer[1] = y;
  36330. UniformBuffer._tempBuffer[2] = z;
  36331. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36332. };
  36333. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36334. if (suffix === void 0) { suffix = ""; }
  36335. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36336. };
  36337. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36338. if (suffix === void 0) { suffix = ""; }
  36339. UniformBuffer._tempBuffer[0] = x;
  36340. UniformBuffer._tempBuffer[1] = y;
  36341. UniformBuffer._tempBuffer[2] = z;
  36342. UniformBuffer._tempBuffer[3] = w;
  36343. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36344. };
  36345. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36346. this._currentEffect.setMatrix(name, mat);
  36347. };
  36348. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36349. this.updateUniform(name, mat.toArray(), 16);
  36350. };
  36351. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36352. this._currentEffect.setVector3(name, vector);
  36353. };
  36354. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36355. vector.toArray(UniformBuffer._tempBuffer);
  36356. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36357. };
  36358. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36359. this._currentEffect.setVector4(name, vector);
  36360. };
  36361. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36362. vector.toArray(UniformBuffer._tempBuffer);
  36363. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36364. };
  36365. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36366. if (suffix === void 0) { suffix = ""; }
  36367. this._currentEffect.setColor3(name + suffix, color);
  36368. };
  36369. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36370. if (suffix === void 0) { suffix = ""; }
  36371. color.toArray(UniformBuffer._tempBuffer);
  36372. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36373. };
  36374. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36375. if (suffix === void 0) { suffix = ""; }
  36376. this._currentEffect.setColor4(name + suffix, color, alpha);
  36377. };
  36378. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36379. if (suffix === void 0) { suffix = ""; }
  36380. color.toArray(UniformBuffer._tempBuffer);
  36381. UniformBuffer._tempBuffer[3] = alpha;
  36382. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36383. };
  36384. /**
  36385. * Sets a sampler uniform on the effect.
  36386. * @param {string} name Name of the sampler.
  36387. * @param {Texture} texture
  36388. */
  36389. UniformBuffer.prototype.setTexture = function (name, texture) {
  36390. this._currentEffect.setTexture(name, texture);
  36391. };
  36392. /**
  36393. * Directly updates the value of the uniform in the cache AND on the GPU.
  36394. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36395. * @param {number[]|Float32Array} data Flattened data
  36396. */
  36397. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36398. this.updateUniform(uniformName, data, data.length);
  36399. this.update();
  36400. };
  36401. /**
  36402. * Binds this uniform buffer to an effect.
  36403. * @param {Effect} effect
  36404. * @param {string} name Name of the uniform block in the shader.
  36405. */
  36406. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36407. this._currentEffect = effect;
  36408. if (this._noUBO || !this._buffer) {
  36409. return;
  36410. }
  36411. effect.bindUniformBuffer(this._buffer, name);
  36412. };
  36413. /**
  36414. * Disposes the uniform buffer.
  36415. */
  36416. UniformBuffer.prototype.dispose = function () {
  36417. if (this._noUBO) {
  36418. return;
  36419. }
  36420. var index = this._engine._uniformBuffers.indexOf(this);
  36421. if (index !== -1) {
  36422. this._engine._uniformBuffers.splice(index, 1);
  36423. }
  36424. if (!this._buffer) {
  36425. return;
  36426. }
  36427. if (this._engine._releaseBuffer(this._buffer)) {
  36428. this._buffer = null;
  36429. }
  36430. };
  36431. // Pool for avoiding memory leaks
  36432. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36433. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36434. return UniformBuffer;
  36435. }());
  36436. BABYLON.UniformBuffer = UniformBuffer;
  36437. })(BABYLON || (BABYLON = {}));
  36438. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36439. var BABYLON;
  36440. (function (BABYLON) {
  36441. /**
  36442. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36443. */
  36444. var VertexData = /** @class */ (function () {
  36445. function VertexData() {
  36446. }
  36447. /**
  36448. * Uses the passed data array to set the set the values for the specified kind of data
  36449. * @param data a linear array of floating numbers
  36450. * @param kind the type of data that is being set, eg positions, colors etc
  36451. */
  36452. VertexData.prototype.set = function (data, kind) {
  36453. switch (kind) {
  36454. case BABYLON.VertexBuffer.PositionKind:
  36455. this.positions = data;
  36456. break;
  36457. case BABYLON.VertexBuffer.NormalKind:
  36458. this.normals = data;
  36459. break;
  36460. case BABYLON.VertexBuffer.TangentKind:
  36461. this.tangents = data;
  36462. break;
  36463. case BABYLON.VertexBuffer.UVKind:
  36464. this.uvs = data;
  36465. break;
  36466. case BABYLON.VertexBuffer.UV2Kind:
  36467. this.uvs2 = data;
  36468. break;
  36469. case BABYLON.VertexBuffer.UV3Kind:
  36470. this.uvs3 = data;
  36471. break;
  36472. case BABYLON.VertexBuffer.UV4Kind:
  36473. this.uvs4 = data;
  36474. break;
  36475. case BABYLON.VertexBuffer.UV5Kind:
  36476. this.uvs5 = data;
  36477. break;
  36478. case BABYLON.VertexBuffer.UV6Kind:
  36479. this.uvs6 = data;
  36480. break;
  36481. case BABYLON.VertexBuffer.ColorKind:
  36482. this.colors = data;
  36483. break;
  36484. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36485. this.matricesIndices = data;
  36486. break;
  36487. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36488. this.matricesWeights = data;
  36489. break;
  36490. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36491. this.matricesIndicesExtra = data;
  36492. break;
  36493. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36494. this.matricesWeightsExtra = data;
  36495. break;
  36496. }
  36497. };
  36498. /**
  36499. * Associates the vertexData to the passed Mesh.
  36500. * Sets it as updatable or not (default `false`)
  36501. * @param mesh the mesh the vertexData is applied to
  36502. * @param updatable when used and having the value true allows new data to update the vertexData
  36503. * @returns the VertexData
  36504. */
  36505. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36506. this._applyTo(mesh, updatable);
  36507. return this;
  36508. };
  36509. /**
  36510. * Associates the vertexData to the passed Geometry.
  36511. * Sets it as updatable or not (default `false`)
  36512. * @param geometry the geometry the vertexData is applied to
  36513. * @param updatable when used and having the value true allows new data to update the vertexData
  36514. * @returns VertexData
  36515. */
  36516. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36517. this._applyTo(geometry, updatable);
  36518. return this;
  36519. };
  36520. /**
  36521. * Updates the associated mesh
  36522. * @param mesh the mesh to be updated
  36523. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36524. * @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
  36525. * @returns VertexData
  36526. */
  36527. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36528. this._update(mesh);
  36529. return this;
  36530. };
  36531. /**
  36532. * Updates the associated geometry
  36533. * @param geometry the geometry to be updated
  36534. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36535. * @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
  36536. * @returns VertexData.
  36537. */
  36538. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36539. this._update(geometry);
  36540. return this;
  36541. };
  36542. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36543. if (updatable === void 0) { updatable = false; }
  36544. if (this.positions) {
  36545. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36546. }
  36547. if (this.normals) {
  36548. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36549. }
  36550. if (this.tangents) {
  36551. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36552. }
  36553. if (this.uvs) {
  36554. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36555. }
  36556. if (this.uvs2) {
  36557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36558. }
  36559. if (this.uvs3) {
  36560. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36561. }
  36562. if (this.uvs4) {
  36563. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36564. }
  36565. if (this.uvs5) {
  36566. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36567. }
  36568. if (this.uvs6) {
  36569. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36570. }
  36571. if (this.colors) {
  36572. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36573. }
  36574. if (this.matricesIndices) {
  36575. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36576. }
  36577. if (this.matricesWeights) {
  36578. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36579. }
  36580. if (this.matricesIndicesExtra) {
  36581. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36582. }
  36583. if (this.matricesWeightsExtra) {
  36584. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36585. }
  36586. if (this.indices) {
  36587. meshOrGeometry.setIndices(this.indices, null, updatable);
  36588. }
  36589. else {
  36590. meshOrGeometry.setIndices([], null);
  36591. }
  36592. return this;
  36593. };
  36594. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36595. if (this.positions) {
  36596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36597. }
  36598. if (this.normals) {
  36599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36600. }
  36601. if (this.tangents) {
  36602. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36603. }
  36604. if (this.uvs) {
  36605. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36606. }
  36607. if (this.uvs2) {
  36608. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36609. }
  36610. if (this.uvs3) {
  36611. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36612. }
  36613. if (this.uvs4) {
  36614. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36615. }
  36616. if (this.uvs5) {
  36617. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36618. }
  36619. if (this.uvs6) {
  36620. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36621. }
  36622. if (this.colors) {
  36623. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36624. }
  36625. if (this.matricesIndices) {
  36626. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36627. }
  36628. if (this.matricesWeights) {
  36629. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36630. }
  36631. if (this.matricesIndicesExtra) {
  36632. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36633. }
  36634. if (this.matricesWeightsExtra) {
  36635. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36636. }
  36637. if (this.indices) {
  36638. meshOrGeometry.setIndices(this.indices, null);
  36639. }
  36640. return this;
  36641. };
  36642. /**
  36643. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36644. * @param matrix the transforming matrix
  36645. * @returns the VertexData
  36646. */
  36647. VertexData.prototype.transform = function (matrix) {
  36648. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36649. var transformed = BABYLON.Vector3.Zero();
  36650. var index;
  36651. if (this.positions) {
  36652. var position = BABYLON.Vector3.Zero();
  36653. for (index = 0; index < this.positions.length; index += 3) {
  36654. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36655. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36656. this.positions[index] = transformed.x;
  36657. this.positions[index + 1] = transformed.y;
  36658. this.positions[index + 2] = transformed.z;
  36659. }
  36660. }
  36661. if (this.normals) {
  36662. var normal = BABYLON.Vector3.Zero();
  36663. for (index = 0; index < this.normals.length; index += 3) {
  36664. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36665. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36666. this.normals[index] = transformed.x;
  36667. this.normals[index + 1] = transformed.y;
  36668. this.normals[index + 2] = transformed.z;
  36669. }
  36670. }
  36671. if (this.tangents) {
  36672. var tangent = BABYLON.Vector4.Zero();
  36673. var tangentTransformed = BABYLON.Vector4.Zero();
  36674. for (index = 0; index < this.tangents.length; index += 4) {
  36675. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36676. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36677. this.tangents[index] = tangentTransformed.x;
  36678. this.tangents[index + 1] = tangentTransformed.y;
  36679. this.tangents[index + 2] = tangentTransformed.z;
  36680. this.tangents[index + 3] = tangentTransformed.w;
  36681. }
  36682. }
  36683. if (flip && this.indices) {
  36684. for (index = 0; index < this.indices.length; index += 3) {
  36685. var tmp = this.indices[index + 1];
  36686. this.indices[index + 1] = this.indices[index + 2];
  36687. this.indices[index + 2] = tmp;
  36688. }
  36689. }
  36690. return this;
  36691. };
  36692. /**
  36693. * Merges the passed VertexData into the current one
  36694. * @param other the VertexData to be merged into the current one
  36695. * @returns the modified VertexData
  36696. */
  36697. VertexData.prototype.merge = function (other) {
  36698. this._validate();
  36699. other._validate();
  36700. if (!this.normals !== !other.normals ||
  36701. !this.tangents !== !other.tangents ||
  36702. !this.uvs !== !other.uvs ||
  36703. !this.uvs2 !== !other.uvs2 ||
  36704. !this.uvs3 !== !other.uvs3 ||
  36705. !this.uvs4 !== !other.uvs4 ||
  36706. !this.uvs5 !== !other.uvs5 ||
  36707. !this.uvs6 !== !other.uvs6 ||
  36708. !this.colors !== !other.colors ||
  36709. !this.matricesIndices !== !other.matricesIndices ||
  36710. !this.matricesWeights !== !other.matricesWeights ||
  36711. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36712. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36713. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36714. }
  36715. if (other.indices) {
  36716. if (!this.indices) {
  36717. this.indices = [];
  36718. }
  36719. var offset = this.positions ? this.positions.length / 3 : 0;
  36720. for (var index = 0; index < other.indices.length; index++) {
  36721. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36722. this.indices.push(other.indices[index] + offset);
  36723. }
  36724. }
  36725. this.positions = this._mergeElement(this.positions, other.positions);
  36726. this.normals = this._mergeElement(this.normals, other.normals);
  36727. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36728. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36729. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36730. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36731. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36732. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36733. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36734. this.colors = this._mergeElement(this.colors, other.colors);
  36735. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36736. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36737. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36738. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36739. return this;
  36740. };
  36741. VertexData.prototype._mergeElement = function (source, other) {
  36742. if (!source) {
  36743. return other;
  36744. }
  36745. if (!other) {
  36746. return source;
  36747. }
  36748. var len = other.length + source.length;
  36749. var isSrcTypedArray = source instanceof Float32Array;
  36750. var isOthTypedArray = other instanceof Float32Array;
  36751. // use non-loop method when the source is Float32Array
  36752. if (isSrcTypedArray) {
  36753. var ret32 = new Float32Array(len);
  36754. ret32.set(source);
  36755. ret32.set(other, source.length);
  36756. return ret32;
  36757. // source is number[], when other is also use concat
  36758. }
  36759. else if (!isOthTypedArray) {
  36760. return source.concat(other);
  36761. // source is a number[], but other is a Float32Array, loop required
  36762. }
  36763. else {
  36764. var ret = source.slice(0); // copy source to a separate array
  36765. for (var i = 0, len = other.length; i < len; i++) {
  36766. ret.push(other[i]);
  36767. }
  36768. return ret;
  36769. }
  36770. };
  36771. VertexData.prototype._validate = function () {
  36772. if (!this.positions) {
  36773. throw new Error("Positions are required");
  36774. }
  36775. var getElementCount = function (kind, values) {
  36776. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36777. if ((values.length % stride) !== 0) {
  36778. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36779. }
  36780. return values.length / stride;
  36781. };
  36782. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36783. var validateElementCount = function (kind, values) {
  36784. var elementCount = getElementCount(kind, values);
  36785. if (elementCount !== positionsElementCount) {
  36786. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36787. }
  36788. };
  36789. if (this.normals)
  36790. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36791. if (this.tangents)
  36792. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36793. if (this.uvs)
  36794. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36795. if (this.uvs2)
  36796. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36797. if (this.uvs3)
  36798. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36799. if (this.uvs4)
  36800. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36801. if (this.uvs5)
  36802. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36803. if (this.uvs6)
  36804. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36805. if (this.colors)
  36806. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36807. if (this.matricesIndices)
  36808. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36809. if (this.matricesWeights)
  36810. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36811. if (this.matricesIndicesExtra)
  36812. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36813. if (this.matricesWeightsExtra)
  36814. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36815. };
  36816. /**
  36817. * Serializes the VertexData
  36818. * @returns a serialized object
  36819. */
  36820. VertexData.prototype.serialize = function () {
  36821. var serializationObject = this.serialize();
  36822. if (this.positions) {
  36823. serializationObject.positions = this.positions;
  36824. }
  36825. if (this.normals) {
  36826. serializationObject.normals = this.normals;
  36827. }
  36828. if (this.tangents) {
  36829. serializationObject.tangents = this.tangents;
  36830. }
  36831. if (this.uvs) {
  36832. serializationObject.uvs = this.uvs;
  36833. }
  36834. if (this.uvs2) {
  36835. serializationObject.uvs2 = this.uvs2;
  36836. }
  36837. if (this.uvs3) {
  36838. serializationObject.uvs3 = this.uvs3;
  36839. }
  36840. if (this.uvs4) {
  36841. serializationObject.uvs4 = this.uvs4;
  36842. }
  36843. if (this.uvs5) {
  36844. serializationObject.uvs5 = this.uvs5;
  36845. }
  36846. if (this.uvs6) {
  36847. serializationObject.uvs6 = this.uvs6;
  36848. }
  36849. if (this.colors) {
  36850. serializationObject.colors = this.colors;
  36851. }
  36852. if (this.matricesIndices) {
  36853. serializationObject.matricesIndices = this.matricesIndices;
  36854. serializationObject.matricesIndices._isExpanded = true;
  36855. }
  36856. if (this.matricesWeights) {
  36857. serializationObject.matricesWeights = this.matricesWeights;
  36858. }
  36859. if (this.matricesIndicesExtra) {
  36860. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36861. serializationObject.matricesIndicesExtra._isExpanded = true;
  36862. }
  36863. if (this.matricesWeightsExtra) {
  36864. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36865. }
  36866. serializationObject.indices = this.indices;
  36867. return serializationObject;
  36868. };
  36869. // Statics
  36870. /**
  36871. * Extracts the vertexData from a mesh
  36872. * @param mesh the mesh from which to extract the VertexData
  36873. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36874. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36875. * @returns the object VertexData associated to the passed mesh
  36876. */
  36877. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36878. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36879. };
  36880. /**
  36881. * Extracts the vertexData from the geometry
  36882. * @param geometry the geometry from which to extract the VertexData
  36883. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36884. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36885. * @returns the object VertexData associated to the passed mesh
  36886. */
  36887. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36888. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36889. };
  36890. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36891. var result = new VertexData();
  36892. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36893. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36894. }
  36895. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36896. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36897. }
  36898. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36899. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36900. }
  36901. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36902. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36903. }
  36904. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36905. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36906. }
  36907. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36908. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36909. }
  36910. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36911. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36912. }
  36913. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36914. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36915. }
  36916. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36917. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36918. }
  36919. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36920. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36921. }
  36922. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36923. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36924. }
  36925. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36926. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36927. }
  36928. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36929. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36930. }
  36931. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36932. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36933. }
  36934. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36935. return result;
  36936. };
  36937. /**
  36938. * Creates the VertexData for a Ribbon
  36939. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36940. * * pathArray array of paths, each of which an array of successive Vector3
  36941. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36942. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36943. * * 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
  36944. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36945. * * 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)
  36946. * * 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)
  36947. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36948. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36949. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36950. * @returns the VertexData of the ribbon
  36951. */
  36952. VertexData.CreateRibbon = function (options) {
  36953. var pathArray = options.pathArray;
  36954. var closeArray = options.closeArray || false;
  36955. var closePath = options.closePath || false;
  36956. var invertUV = options.invertUV || false;
  36957. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36958. var offset = options.offset || defaultOffset;
  36959. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36960. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36961. var customUV = options.uvs;
  36962. var customColors = options.colors;
  36963. var positions = [];
  36964. var indices = [];
  36965. var normals = [];
  36966. var uvs = [];
  36967. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36968. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36969. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36970. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36971. var minlg; // minimal length among all paths from pathArray
  36972. var lg = []; // array of path lengths : nb of vertex per path
  36973. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36974. var p; // path iterator
  36975. var i; // point iterator
  36976. var j; // point iterator
  36977. // if single path in pathArray
  36978. if (pathArray.length < 2) {
  36979. var ar1 = [];
  36980. var ar2 = [];
  36981. for (i = 0; i < pathArray[0].length - offset; i++) {
  36982. ar1.push(pathArray[0][i]);
  36983. ar2.push(pathArray[0][i + offset]);
  36984. }
  36985. pathArray = [ar1, ar2];
  36986. }
  36987. // positions and horizontal distances (u)
  36988. var idc = 0;
  36989. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36990. var path;
  36991. var l;
  36992. minlg = pathArray[0].length;
  36993. var vectlg;
  36994. var dist;
  36995. for (p = 0; p < pathArray.length; p++) {
  36996. uTotalDistance[p] = 0;
  36997. us[p] = [0];
  36998. path = pathArray[p];
  36999. l = path.length;
  37000. minlg = (minlg < l) ? minlg : l;
  37001. j = 0;
  37002. while (j < l) {
  37003. positions.push(path[j].x, path[j].y, path[j].z);
  37004. if (j > 0) {
  37005. vectlg = path[j].subtract(path[j - 1]).length();
  37006. dist = vectlg + uTotalDistance[p];
  37007. us[p].push(dist);
  37008. uTotalDistance[p] = dist;
  37009. }
  37010. j++;
  37011. }
  37012. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37013. j--;
  37014. positions.push(path[0].x, path[0].y, path[0].z);
  37015. vectlg = path[j].subtract(path[0]).length();
  37016. dist = vectlg + uTotalDistance[p];
  37017. us[p].push(dist);
  37018. uTotalDistance[p] = dist;
  37019. }
  37020. lg[p] = l + closePathCorr;
  37021. idx[p] = idc;
  37022. idc += (l + closePathCorr);
  37023. }
  37024. // vertical distances (v)
  37025. var path1;
  37026. var path2;
  37027. var vertex1 = null;
  37028. var vertex2 = null;
  37029. for (i = 0; i < minlg + closePathCorr; i++) {
  37030. vTotalDistance[i] = 0;
  37031. vs[i] = [0];
  37032. for (p = 0; p < pathArray.length - 1; p++) {
  37033. path1 = pathArray[p];
  37034. path2 = pathArray[p + 1];
  37035. if (i === minlg) { // closePath
  37036. vertex1 = path1[0];
  37037. vertex2 = path2[0];
  37038. }
  37039. else {
  37040. vertex1 = path1[i];
  37041. vertex2 = path2[i];
  37042. }
  37043. vectlg = vertex2.subtract(vertex1).length();
  37044. dist = vectlg + vTotalDistance[i];
  37045. vs[i].push(dist);
  37046. vTotalDistance[i] = dist;
  37047. }
  37048. if (closeArray && vertex2 && vertex1) {
  37049. path1 = pathArray[p];
  37050. path2 = pathArray[0];
  37051. if (i === minlg) { // closePath
  37052. vertex2 = path2[0];
  37053. }
  37054. vectlg = vertex2.subtract(vertex1).length();
  37055. dist = vectlg + vTotalDistance[i];
  37056. vTotalDistance[i] = dist;
  37057. }
  37058. }
  37059. // uvs
  37060. var u;
  37061. var v;
  37062. if (customUV) {
  37063. for (p = 0; p < customUV.length; p++) {
  37064. uvs.push(customUV[p].x, customUV[p].y);
  37065. }
  37066. }
  37067. else {
  37068. for (p = 0; p < pathArray.length; p++) {
  37069. for (i = 0; i < minlg + closePathCorr; i++) {
  37070. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37071. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37072. if (invertUV) {
  37073. uvs.push(v, u);
  37074. }
  37075. else {
  37076. uvs.push(u, v);
  37077. }
  37078. }
  37079. }
  37080. }
  37081. // indices
  37082. p = 0; // path index
  37083. var pi = 0; // positions array index
  37084. var l1 = lg[p] - 1; // path1 length
  37085. var l2 = lg[p + 1] - 1; // path2 length
  37086. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37087. var shft = idx[1] - idx[0]; // shift
  37088. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37089. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37090. // 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
  37091. indices.push(pi, pi + shft, pi + 1);
  37092. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37093. pi += 1;
  37094. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37095. p++;
  37096. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37097. shft = idx[0] - idx[p];
  37098. l1 = lg[p] - 1;
  37099. l2 = lg[0] - 1;
  37100. }
  37101. else {
  37102. shft = idx[p + 1] - idx[p];
  37103. l1 = lg[p] - 1;
  37104. l2 = lg[p + 1] - 1;
  37105. }
  37106. pi = idx[p];
  37107. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37108. }
  37109. }
  37110. // normals
  37111. VertexData.ComputeNormals(positions, indices, normals);
  37112. if (closePath) { // update both the first and last vertex normals to their average value
  37113. var indexFirst = 0;
  37114. var indexLast = 0;
  37115. for (p = 0; p < pathArray.length; p++) {
  37116. indexFirst = idx[p] * 3;
  37117. if (p + 1 < pathArray.length) {
  37118. indexLast = (idx[p + 1] - 1) * 3;
  37119. }
  37120. else {
  37121. indexLast = normals.length - 3;
  37122. }
  37123. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37124. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37125. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37126. normals[indexLast] = normals[indexFirst];
  37127. normals[indexLast + 1] = normals[indexFirst + 1];
  37128. normals[indexLast + 2] = normals[indexFirst + 2];
  37129. }
  37130. }
  37131. // sides
  37132. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37133. // Colors
  37134. var colors = null;
  37135. if (customColors) {
  37136. colors = new Float32Array(customColors.length * 4);
  37137. for (var c = 0; c < customColors.length; c++) {
  37138. colors[c * 4] = customColors[c].r;
  37139. colors[c * 4 + 1] = customColors[c].g;
  37140. colors[c * 4 + 2] = customColors[c].b;
  37141. colors[c * 4 + 3] = customColors[c].a;
  37142. }
  37143. }
  37144. // Result
  37145. var vertexData = new VertexData();
  37146. var positions32 = new Float32Array(positions);
  37147. var normals32 = new Float32Array(normals);
  37148. var uvs32 = new Float32Array(uvs);
  37149. vertexData.indices = indices;
  37150. vertexData.positions = positions32;
  37151. vertexData.normals = normals32;
  37152. vertexData.uvs = uvs32;
  37153. if (colors) {
  37154. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37155. }
  37156. if (closePath) {
  37157. vertexData._idx = idx;
  37158. }
  37159. return vertexData;
  37160. };
  37161. /**
  37162. * Creates the VertexData for a box
  37163. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37164. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37165. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37166. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37167. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37168. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37169. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37170. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37171. * * 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)
  37172. * * 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)
  37173. * @returns the VertexData of the box
  37174. */
  37175. VertexData.CreateBox = function (options) {
  37176. var normalsSource = [
  37177. new BABYLON.Vector3(0, 0, 1),
  37178. new BABYLON.Vector3(0, 0, -1),
  37179. new BABYLON.Vector3(1, 0, 0),
  37180. new BABYLON.Vector3(-1, 0, 0),
  37181. new BABYLON.Vector3(0, 1, 0),
  37182. new BABYLON.Vector3(0, -1, 0)
  37183. ];
  37184. var indices = [];
  37185. var positions = [];
  37186. var normals = [];
  37187. var uvs = [];
  37188. var width = options.width || options.size || 1;
  37189. var height = options.height || options.size || 1;
  37190. var depth = options.depth || options.size || 1;
  37191. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37192. var faceUV = options.faceUV || new Array(6);
  37193. var faceColors = options.faceColors;
  37194. var colors = [];
  37195. // default face colors and UV if undefined
  37196. for (var f = 0; f < 6; f++) {
  37197. if (faceUV[f] === undefined) {
  37198. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37199. }
  37200. if (faceColors && faceColors[f] === undefined) {
  37201. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37202. }
  37203. }
  37204. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37205. // Create each face in turn.
  37206. for (var index = 0; index < normalsSource.length; index++) {
  37207. var normal = normalsSource[index];
  37208. // Get two vectors perpendicular to the face normal and to each other.
  37209. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37210. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37211. // Six indices (two triangles) per face.
  37212. var verticesLength = positions.length / 3;
  37213. indices.push(verticesLength);
  37214. indices.push(verticesLength + 1);
  37215. indices.push(verticesLength + 2);
  37216. indices.push(verticesLength);
  37217. indices.push(verticesLength + 2);
  37218. indices.push(verticesLength + 3);
  37219. // Four vertices per face.
  37220. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37221. positions.push(vertex.x, vertex.y, vertex.z);
  37222. normals.push(normal.x, normal.y, normal.z);
  37223. uvs.push(faceUV[index].z, faceUV[index].w);
  37224. if (faceColors) {
  37225. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37226. }
  37227. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37228. positions.push(vertex.x, vertex.y, vertex.z);
  37229. normals.push(normal.x, normal.y, normal.z);
  37230. uvs.push(faceUV[index].x, faceUV[index].w);
  37231. if (faceColors) {
  37232. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37233. }
  37234. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37235. positions.push(vertex.x, vertex.y, vertex.z);
  37236. normals.push(normal.x, normal.y, normal.z);
  37237. uvs.push(faceUV[index].x, faceUV[index].y);
  37238. if (faceColors) {
  37239. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37240. }
  37241. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37242. positions.push(vertex.x, vertex.y, vertex.z);
  37243. normals.push(normal.x, normal.y, normal.z);
  37244. uvs.push(faceUV[index].z, faceUV[index].y);
  37245. if (faceColors) {
  37246. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37247. }
  37248. }
  37249. // sides
  37250. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37251. // Result
  37252. var vertexData = new VertexData();
  37253. vertexData.indices = indices;
  37254. vertexData.positions = positions;
  37255. vertexData.normals = normals;
  37256. vertexData.uvs = uvs;
  37257. if (faceColors) {
  37258. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37259. vertexData.colors = totalColors;
  37260. }
  37261. return vertexData;
  37262. };
  37263. /**
  37264. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37265. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37266. * * segments sets the number of horizontal strips optional, default 32
  37267. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37268. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37269. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37270. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37271. * * 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
  37272. * * 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
  37273. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37274. * * 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)
  37275. * * 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)
  37276. * @returns the VertexData of the ellipsoid
  37277. */
  37278. VertexData.CreateSphere = function (options) {
  37279. var segments = options.segments || 32;
  37280. var diameterX = options.diameterX || options.diameter || 1;
  37281. var diameterY = options.diameterY || options.diameter || 1;
  37282. var diameterZ = options.diameterZ || options.diameter || 1;
  37283. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37284. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37285. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37286. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37287. var totalZRotationSteps = 2 + segments;
  37288. var totalYRotationSteps = 2 * totalZRotationSteps;
  37289. var indices = [];
  37290. var positions = [];
  37291. var normals = [];
  37292. var uvs = [];
  37293. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37294. var normalizedZ = zRotationStep / totalZRotationSteps;
  37295. var angleZ = normalizedZ * Math.PI * slice;
  37296. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37297. var normalizedY = yRotationStep / totalYRotationSteps;
  37298. var angleY = normalizedY * Math.PI * 2 * arc;
  37299. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37300. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37301. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37302. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37303. var vertex = complete.multiply(radius);
  37304. var normal = complete.divide(radius).normalize();
  37305. positions.push(vertex.x, vertex.y, vertex.z);
  37306. normals.push(normal.x, normal.y, normal.z);
  37307. uvs.push(normalizedY, normalizedZ);
  37308. }
  37309. if (zRotationStep > 0) {
  37310. var verticesCount = positions.length / 3;
  37311. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37312. indices.push((firstIndex));
  37313. indices.push((firstIndex + 1));
  37314. indices.push(firstIndex + totalYRotationSteps + 1);
  37315. indices.push((firstIndex + totalYRotationSteps + 1));
  37316. indices.push((firstIndex + 1));
  37317. indices.push((firstIndex + totalYRotationSteps + 2));
  37318. }
  37319. }
  37320. }
  37321. // Sides
  37322. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37323. // Result
  37324. var vertexData = new VertexData();
  37325. vertexData.indices = indices;
  37326. vertexData.positions = positions;
  37327. vertexData.normals = normals;
  37328. vertexData.uvs = uvs;
  37329. return vertexData;
  37330. };
  37331. /**
  37332. * Creates the VertexData for a cylinder, cone or prism
  37333. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37334. * * height sets the height (y direction) of the cylinder, optional, default 2
  37335. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37336. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37337. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37338. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37339. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37340. * * 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
  37341. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37342. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37343. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37344. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37345. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37346. * * 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)
  37347. * * 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)
  37348. * @returns the VertexData of the cylinder, cone or prism
  37349. */
  37350. VertexData.CreateCylinder = function (options) {
  37351. var height = options.height || 2;
  37352. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37353. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37354. var tessellation = options.tessellation || 24;
  37355. var subdivisions = options.subdivisions || 1;
  37356. var hasRings = options.hasRings ? true : false;
  37357. var enclose = options.enclose ? true : false;
  37358. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37359. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37360. var faceUV = options.faceUV || new Array(3);
  37361. var faceColors = options.faceColors;
  37362. // default face colors and UV if undefined
  37363. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37364. var ringNb = (hasRings) ? subdivisions : 1;
  37365. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37366. var f;
  37367. for (f = 0; f < surfaceNb; f++) {
  37368. if (faceColors && faceColors[f] === undefined) {
  37369. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37370. }
  37371. }
  37372. for (f = 0; f < surfaceNb; f++) {
  37373. if (faceUV && faceUV[f] === undefined) {
  37374. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37375. }
  37376. }
  37377. var indices = new Array();
  37378. var positions = new Array();
  37379. var normals = new Array();
  37380. var uvs = new Array();
  37381. var colors = new Array();
  37382. var angle_step = Math.PI * 2 * arc / tessellation;
  37383. var angle;
  37384. var h;
  37385. var radius;
  37386. var tan = (diameterBottom - diameterTop) / 2 / height;
  37387. var ringVertex = BABYLON.Vector3.Zero();
  37388. var ringNormal = BABYLON.Vector3.Zero();
  37389. var ringFirstVertex = BABYLON.Vector3.Zero();
  37390. var ringFirstNormal = BABYLON.Vector3.Zero();
  37391. var quadNormal = BABYLON.Vector3.Zero();
  37392. var Y = BABYLON.Axis.Y;
  37393. // positions, normals, uvs
  37394. var i;
  37395. var j;
  37396. var r;
  37397. var ringIdx = 1;
  37398. var s = 1; // surface index
  37399. var cs = 0;
  37400. var v = 0;
  37401. for (i = 0; i <= subdivisions; i++) {
  37402. h = i / subdivisions;
  37403. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37404. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37405. for (r = 0; r < ringIdx; r++) {
  37406. if (hasRings) {
  37407. s += r;
  37408. }
  37409. if (enclose) {
  37410. s += 2 * r;
  37411. }
  37412. for (j = 0; j <= tessellation; j++) {
  37413. angle = j * angle_step;
  37414. // position
  37415. ringVertex.x = Math.cos(-angle) * radius;
  37416. ringVertex.y = -height / 2 + h * height;
  37417. ringVertex.z = Math.sin(-angle) * radius;
  37418. // normal
  37419. if (diameterTop === 0 && i === subdivisions) {
  37420. // if no top cap, reuse former normals
  37421. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37422. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37423. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37424. }
  37425. else {
  37426. ringNormal.x = ringVertex.x;
  37427. ringNormal.z = ringVertex.z;
  37428. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37429. ringNormal.normalize();
  37430. }
  37431. // keep first ring vertex values for enclose
  37432. if (j === 0) {
  37433. ringFirstVertex.copyFrom(ringVertex);
  37434. ringFirstNormal.copyFrom(ringNormal);
  37435. }
  37436. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37437. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37438. if (hasRings) {
  37439. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37440. }
  37441. else {
  37442. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37443. }
  37444. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37445. if (faceColors) {
  37446. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37447. }
  37448. }
  37449. // if enclose, add four vertices and their dedicated normals
  37450. if (arc !== 1 && enclose) {
  37451. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37452. positions.push(0, ringVertex.y, 0);
  37453. positions.push(0, ringVertex.y, 0);
  37454. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37455. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37456. quadNormal.normalize();
  37457. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37458. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37459. quadNormal.normalize();
  37460. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37461. if (hasRings) {
  37462. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37463. }
  37464. else {
  37465. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37466. }
  37467. uvs.push(faceUV[s + 1].x, v);
  37468. uvs.push(faceUV[s + 1].z, v);
  37469. if (hasRings) {
  37470. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37471. }
  37472. else {
  37473. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37474. }
  37475. uvs.push(faceUV[s + 2].x, v);
  37476. uvs.push(faceUV[s + 2].z, v);
  37477. if (faceColors) {
  37478. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37479. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37480. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37481. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37482. }
  37483. }
  37484. if (cs !== s) {
  37485. cs = s;
  37486. }
  37487. }
  37488. }
  37489. // indices
  37490. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37491. var s;
  37492. i = 0;
  37493. for (s = 0; s < subdivisions; s++) {
  37494. var i0 = 0;
  37495. var i1 = 0;
  37496. var i2 = 0;
  37497. var i3 = 0;
  37498. for (j = 0; j < tessellation; j++) {
  37499. i0 = i * (e + 1) + j;
  37500. i1 = (i + 1) * (e + 1) + j;
  37501. i2 = i * (e + 1) + (j + 1);
  37502. i3 = (i + 1) * (e + 1) + (j + 1);
  37503. indices.push(i0, i1, i2);
  37504. indices.push(i3, i2, i1);
  37505. }
  37506. if (arc !== 1 && enclose) { // if enclose, add two quads
  37507. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37508. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37509. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37510. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37511. }
  37512. i = (hasRings) ? (i + 2) : (i + 1);
  37513. }
  37514. // Caps
  37515. var createCylinderCap = function (isTop) {
  37516. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37517. if (radius === 0) {
  37518. return;
  37519. }
  37520. // Cap positions, normals & uvs
  37521. var angle;
  37522. var circleVector;
  37523. var i;
  37524. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37525. var c = null;
  37526. if (faceColors) {
  37527. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37528. }
  37529. // cap center
  37530. var vbase = positions.length / 3;
  37531. var offset = isTop ? height / 2 : -height / 2;
  37532. var center = new BABYLON.Vector3(0, offset, 0);
  37533. positions.push(center.x, center.y, center.z);
  37534. normals.push(0, isTop ? 1 : -1, 0);
  37535. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37536. if (c) {
  37537. colors.push(c.r, c.g, c.b, c.a);
  37538. }
  37539. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37540. for (i = 0; i <= tessellation; i++) {
  37541. angle = Math.PI * 2 * i * arc / tessellation;
  37542. var cos = Math.cos(-angle);
  37543. var sin = Math.sin(-angle);
  37544. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37545. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37546. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37547. normals.push(0, isTop ? 1 : -1, 0);
  37548. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37549. if (c) {
  37550. colors.push(c.r, c.g, c.b, c.a);
  37551. }
  37552. }
  37553. // Cap indices
  37554. for (i = 0; i < tessellation; i++) {
  37555. if (!isTop) {
  37556. indices.push(vbase);
  37557. indices.push(vbase + (i + 1));
  37558. indices.push(vbase + (i + 2));
  37559. }
  37560. else {
  37561. indices.push(vbase);
  37562. indices.push(vbase + (i + 2));
  37563. indices.push(vbase + (i + 1));
  37564. }
  37565. }
  37566. };
  37567. // add caps to geometry
  37568. createCylinderCap(false);
  37569. createCylinderCap(true);
  37570. // Sides
  37571. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37572. var vertexData = new VertexData();
  37573. vertexData.indices = indices;
  37574. vertexData.positions = positions;
  37575. vertexData.normals = normals;
  37576. vertexData.uvs = uvs;
  37577. if (faceColors) {
  37578. vertexData.colors = colors;
  37579. }
  37580. return vertexData;
  37581. };
  37582. /**
  37583. * Creates the VertexData for a torus
  37584. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37585. * * diameter the diameter of the torus, optional default 1
  37586. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37587. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37588. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37589. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37590. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37591. * @returns the VertexData of the torus
  37592. */
  37593. VertexData.CreateTorus = function (options) {
  37594. var indices = [];
  37595. var positions = [];
  37596. var normals = [];
  37597. var uvs = [];
  37598. var diameter = options.diameter || 1;
  37599. var thickness = options.thickness || 0.5;
  37600. var tessellation = options.tessellation || 16;
  37601. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37602. var stride = tessellation + 1;
  37603. for (var i = 0; i <= tessellation; i++) {
  37604. var u = i / tessellation;
  37605. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37606. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37607. for (var j = 0; j <= tessellation; j++) {
  37608. var v = 1 - j / tessellation;
  37609. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37610. var dx = Math.cos(innerAngle);
  37611. var dy = Math.sin(innerAngle);
  37612. // Create a vertex.
  37613. var normal = new BABYLON.Vector3(dx, dy, 0);
  37614. var position = normal.scale(thickness / 2);
  37615. var textureCoordinate = new BABYLON.Vector2(u, v);
  37616. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37617. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37618. positions.push(position.x, position.y, position.z);
  37619. normals.push(normal.x, normal.y, normal.z);
  37620. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37621. // And create indices for two triangles.
  37622. var nextI = (i + 1) % stride;
  37623. var nextJ = (j + 1) % stride;
  37624. indices.push(i * stride + j);
  37625. indices.push(i * stride + nextJ);
  37626. indices.push(nextI * stride + j);
  37627. indices.push(i * stride + nextJ);
  37628. indices.push(nextI * stride + nextJ);
  37629. indices.push(nextI * stride + j);
  37630. }
  37631. }
  37632. // Sides
  37633. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37634. // Result
  37635. var vertexData = new VertexData();
  37636. vertexData.indices = indices;
  37637. vertexData.positions = positions;
  37638. vertexData.normals = normals;
  37639. vertexData.uvs = uvs;
  37640. return vertexData;
  37641. };
  37642. /**
  37643. * Creates the VertexData of the LineSystem
  37644. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37645. * - lines an array of lines, each line being an array of successive Vector3
  37646. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37647. * @returns the VertexData of the LineSystem
  37648. */
  37649. VertexData.CreateLineSystem = function (options) {
  37650. var indices = [];
  37651. var positions = [];
  37652. var lines = options.lines;
  37653. var colors = options.colors;
  37654. var vertexColors = [];
  37655. var idx = 0;
  37656. for (var l = 0; l < lines.length; l++) {
  37657. var points = lines[l];
  37658. for (var index = 0; index < points.length; index++) {
  37659. positions.push(points[index].x, points[index].y, points[index].z);
  37660. if (colors) {
  37661. var color = colors[l];
  37662. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37663. }
  37664. if (index > 0) {
  37665. indices.push(idx - 1);
  37666. indices.push(idx);
  37667. }
  37668. idx++;
  37669. }
  37670. }
  37671. var vertexData = new VertexData();
  37672. vertexData.indices = indices;
  37673. vertexData.positions = positions;
  37674. if (colors) {
  37675. vertexData.colors = vertexColors;
  37676. }
  37677. return vertexData;
  37678. };
  37679. /**
  37680. * Create the VertexData for a DashedLines
  37681. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37682. * - points an array successive Vector3
  37683. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37684. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37685. * - dashNb the intended total number of dashes, optional, default 200
  37686. * @returns the VertexData for the DashedLines
  37687. */
  37688. VertexData.CreateDashedLines = function (options) {
  37689. var dashSize = options.dashSize || 3;
  37690. var gapSize = options.gapSize || 1;
  37691. var dashNb = options.dashNb || 200;
  37692. var points = options.points;
  37693. var positions = new Array();
  37694. var indices = new Array();
  37695. var curvect = BABYLON.Vector3.Zero();
  37696. var lg = 0;
  37697. var nb = 0;
  37698. var shft = 0;
  37699. var dashshft = 0;
  37700. var curshft = 0;
  37701. var idx = 0;
  37702. var i = 0;
  37703. for (i = 0; i < points.length - 1; i++) {
  37704. points[i + 1].subtractToRef(points[i], curvect);
  37705. lg += curvect.length();
  37706. }
  37707. shft = lg / dashNb;
  37708. dashshft = dashSize * shft / (dashSize + gapSize);
  37709. for (i = 0; i < points.length - 1; i++) {
  37710. points[i + 1].subtractToRef(points[i], curvect);
  37711. nb = Math.floor(curvect.length() / shft);
  37712. curvect.normalize();
  37713. for (var j = 0; j < nb; j++) {
  37714. curshft = shft * j;
  37715. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37716. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37717. indices.push(idx, idx + 1);
  37718. idx += 2;
  37719. }
  37720. }
  37721. // Result
  37722. var vertexData = new VertexData();
  37723. vertexData.positions = positions;
  37724. vertexData.indices = indices;
  37725. return vertexData;
  37726. };
  37727. /**
  37728. * Creates the VertexData for a Ground
  37729. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37730. * - width the width (x direction) of the ground, optional, default 1
  37731. * - height the height (z direction) of the ground, optional, default 1
  37732. * - subdivisions the number of subdivisions per side, optional, default 1
  37733. * @returns the VertexData of the Ground
  37734. */
  37735. VertexData.CreateGround = function (options) {
  37736. var indices = [];
  37737. var positions = [];
  37738. var normals = [];
  37739. var uvs = [];
  37740. var row, col;
  37741. var width = options.width || 1;
  37742. var height = options.height || 1;
  37743. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37744. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37745. for (row = 0; row <= subdivisionsY; row++) {
  37746. for (col = 0; col <= subdivisionsX; col++) {
  37747. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37748. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37749. positions.push(position.x, position.y, position.z);
  37750. normals.push(normal.x, normal.y, normal.z);
  37751. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37752. }
  37753. }
  37754. for (row = 0; row < subdivisionsY; row++) {
  37755. for (col = 0; col < subdivisionsX; col++) {
  37756. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37757. indices.push(col + 1 + row * (subdivisionsX + 1));
  37758. indices.push(col + row * (subdivisionsX + 1));
  37759. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37760. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37761. indices.push(col + row * (subdivisionsX + 1));
  37762. }
  37763. }
  37764. // Result
  37765. var vertexData = new VertexData();
  37766. vertexData.indices = indices;
  37767. vertexData.positions = positions;
  37768. vertexData.normals = normals;
  37769. vertexData.uvs = uvs;
  37770. return vertexData;
  37771. };
  37772. /**
  37773. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37774. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37775. * * xmin the ground minimum X coordinate, optional, default -1
  37776. * * zmin the ground minimum Z coordinate, optional, default -1
  37777. * * xmax the ground maximum X coordinate, optional, default 1
  37778. * * zmax the ground maximum Z coordinate, optional, default 1
  37779. * * 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}
  37780. * * 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}
  37781. * @returns the VertexData of the TiledGround
  37782. */
  37783. VertexData.CreateTiledGround = function (options) {
  37784. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37785. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37786. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37787. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37788. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37789. var precision = options.precision || { w: 1, h: 1 };
  37790. var indices = new Array();
  37791. var positions = new Array();
  37792. var normals = new Array();
  37793. var uvs = new Array();
  37794. var row, col, tileRow, tileCol;
  37795. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37796. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37797. precision.w = (precision.w < 1) ? 1 : precision.w;
  37798. precision.h = (precision.h < 1) ? 1 : precision.h;
  37799. var tileSize = {
  37800. 'w': (xmax - xmin) / subdivisions.w,
  37801. 'h': (zmax - zmin) / subdivisions.h
  37802. };
  37803. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37804. // Indices
  37805. var base = positions.length / 3;
  37806. var rowLength = precision.w + 1;
  37807. for (row = 0; row < precision.h; row++) {
  37808. for (col = 0; col < precision.w; col++) {
  37809. var square = [
  37810. base + col + row * rowLength,
  37811. base + (col + 1) + row * rowLength,
  37812. base + (col + 1) + (row + 1) * rowLength,
  37813. base + col + (row + 1) * rowLength
  37814. ];
  37815. indices.push(square[1]);
  37816. indices.push(square[2]);
  37817. indices.push(square[3]);
  37818. indices.push(square[0]);
  37819. indices.push(square[1]);
  37820. indices.push(square[3]);
  37821. }
  37822. }
  37823. // Position, normals and uvs
  37824. var position = BABYLON.Vector3.Zero();
  37825. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37826. for (row = 0; row <= precision.h; row++) {
  37827. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37828. for (col = 0; col <= precision.w; col++) {
  37829. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37830. position.y = 0;
  37831. positions.push(position.x, position.y, position.z);
  37832. normals.push(normal.x, normal.y, normal.z);
  37833. uvs.push(col / precision.w, row / precision.h);
  37834. }
  37835. }
  37836. }
  37837. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37838. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37839. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37840. }
  37841. }
  37842. // Result
  37843. var vertexData = new VertexData();
  37844. vertexData.indices = indices;
  37845. vertexData.positions = positions;
  37846. vertexData.normals = normals;
  37847. vertexData.uvs = uvs;
  37848. return vertexData;
  37849. };
  37850. /**
  37851. * Creates the VertexData of the Ground designed from a heightmap
  37852. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37853. * * width the width (x direction) of the ground
  37854. * * height the height (z direction) of the ground
  37855. * * subdivisions the number of subdivisions per side
  37856. * * minHeight the minimum altitude on the ground, optional, default 0
  37857. * * maxHeight the maximum altitude on the ground, optional default 1
  37858. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37859. * * buffer the array holding the image color data
  37860. * * bufferWidth the width of image
  37861. * * bufferHeight the height of image
  37862. * @returns the VertexData of the Ground designed from a heightmap
  37863. */
  37864. VertexData.CreateGroundFromHeightMap = function (options) {
  37865. var indices = [];
  37866. var positions = [];
  37867. var normals = [];
  37868. var uvs = [];
  37869. var row, col;
  37870. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37871. // Vertices
  37872. for (row = 0; row <= options.subdivisions; row++) {
  37873. for (col = 0; col <= options.subdivisions; col++) {
  37874. 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));
  37875. // Compute height
  37876. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37877. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37878. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37879. var r = options.buffer[pos] / 255.0;
  37880. var g = options.buffer[pos + 1] / 255.0;
  37881. var b = options.buffer[pos + 2] / 255.0;
  37882. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37883. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37884. // Add vertex
  37885. positions.push(position.x, position.y, position.z);
  37886. normals.push(0, 0, 0);
  37887. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37888. }
  37889. }
  37890. // Indices
  37891. for (row = 0; row < options.subdivisions; row++) {
  37892. for (col = 0; col < options.subdivisions; col++) {
  37893. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37894. indices.push(col + 1 + row * (options.subdivisions + 1));
  37895. indices.push(col + row * (options.subdivisions + 1));
  37896. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37897. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37898. indices.push(col + row * (options.subdivisions + 1));
  37899. }
  37900. }
  37901. // Normals
  37902. VertexData.ComputeNormals(positions, indices, normals);
  37903. // Result
  37904. var vertexData = new VertexData();
  37905. vertexData.indices = indices;
  37906. vertexData.positions = positions;
  37907. vertexData.normals = normals;
  37908. vertexData.uvs = uvs;
  37909. return vertexData;
  37910. };
  37911. /**
  37912. * Creates the VertexData for a Plane
  37913. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37914. * * size sets the width and height of the plane to the value of size, optional default 1
  37915. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37916. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37917. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37918. * * 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)
  37919. * * 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)
  37920. * @returns the VertexData of the box
  37921. */
  37922. VertexData.CreatePlane = function (options) {
  37923. var indices = [];
  37924. var positions = [];
  37925. var normals = [];
  37926. var uvs = [];
  37927. var width = options.width || options.size || 1;
  37928. var height = options.height || options.size || 1;
  37929. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37930. // Vertices
  37931. var halfWidth = width / 2.0;
  37932. var halfHeight = height / 2.0;
  37933. positions.push(-halfWidth, -halfHeight, 0);
  37934. normals.push(0, 0, -1.0);
  37935. uvs.push(0.0, 0.0);
  37936. positions.push(halfWidth, -halfHeight, 0);
  37937. normals.push(0, 0, -1.0);
  37938. uvs.push(1.0, 0.0);
  37939. positions.push(halfWidth, halfHeight, 0);
  37940. normals.push(0, 0, -1.0);
  37941. uvs.push(1.0, 1.0);
  37942. positions.push(-halfWidth, halfHeight, 0);
  37943. normals.push(0, 0, -1.0);
  37944. uvs.push(0.0, 1.0);
  37945. // Indices
  37946. indices.push(0);
  37947. indices.push(1);
  37948. indices.push(2);
  37949. indices.push(0);
  37950. indices.push(2);
  37951. indices.push(3);
  37952. // Sides
  37953. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37954. // Result
  37955. var vertexData = new VertexData();
  37956. vertexData.indices = indices;
  37957. vertexData.positions = positions;
  37958. vertexData.normals = normals;
  37959. vertexData.uvs = uvs;
  37960. return vertexData;
  37961. };
  37962. /**
  37963. * Creates the VertexData of the Disc or regular Polygon
  37964. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37965. * * radius the radius of the disc, optional default 0.5
  37966. * * tessellation the number of polygon sides, optional, default 64
  37967. * * 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
  37968. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37969. * * 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)
  37970. * * 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)
  37971. * @returns the VertexData of the box
  37972. */
  37973. VertexData.CreateDisc = function (options) {
  37974. var positions = new Array();
  37975. var indices = new Array();
  37976. var normals = new Array();
  37977. var uvs = new Array();
  37978. var radius = options.radius || 0.5;
  37979. var tessellation = options.tessellation || 64;
  37980. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37981. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37982. // positions and uvs
  37983. positions.push(0, 0, 0); // disc center first
  37984. uvs.push(0.5, 0.5);
  37985. var theta = Math.PI * 2 * arc;
  37986. var step = theta / tessellation;
  37987. for (var a = 0; a < theta; a += step) {
  37988. var x = Math.cos(a);
  37989. var y = Math.sin(a);
  37990. var u = (x + 1) / 2;
  37991. var v = (1 - y) / 2;
  37992. positions.push(radius * x, radius * y, 0);
  37993. uvs.push(u, v);
  37994. }
  37995. if (arc === 1) {
  37996. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37997. uvs.push(uvs[2], uvs[3]);
  37998. }
  37999. //indices
  38000. var vertexNb = positions.length / 3;
  38001. for (var i = 1; i < vertexNb - 1; i++) {
  38002. indices.push(i + 1, 0, i);
  38003. }
  38004. // result
  38005. VertexData.ComputeNormals(positions, indices, normals);
  38006. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38007. var vertexData = new VertexData();
  38008. vertexData.indices = indices;
  38009. vertexData.positions = positions;
  38010. vertexData.normals = normals;
  38011. vertexData.uvs = uvs;
  38012. return vertexData;
  38013. };
  38014. /**
  38015. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38016. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38017. * @param polygon a mesh built from polygonTriangulation.build()
  38018. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38019. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38020. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38021. * @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)
  38022. * @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)
  38023. * @returns the VertexData of the Polygon
  38024. */
  38025. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38026. var faceUV = fUV || new Array(3);
  38027. var faceColors = fColors;
  38028. var colors = [];
  38029. // default face colors and UV if undefined
  38030. for (var f = 0; f < 3; f++) {
  38031. if (faceUV[f] === undefined) {
  38032. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38033. }
  38034. if (faceColors && faceColors[f] === undefined) {
  38035. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38036. }
  38037. }
  38038. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38039. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38040. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38041. var indices = polygon.getIndices();
  38042. // set face colours and textures
  38043. var idx = 0;
  38044. var face = 0;
  38045. for (var index = 0; index < normals.length; index += 3) {
  38046. //Edge Face no. 1
  38047. if (Math.abs(normals[index + 1]) < 0.001) {
  38048. face = 1;
  38049. }
  38050. //Top Face no. 0
  38051. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38052. face = 0;
  38053. }
  38054. //Bottom Face no. 2
  38055. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38056. face = 2;
  38057. }
  38058. idx = index / 3;
  38059. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38060. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38061. if (faceColors) {
  38062. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38063. }
  38064. }
  38065. // sides
  38066. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38067. // Result
  38068. var vertexData = new VertexData();
  38069. vertexData.indices = indices;
  38070. vertexData.positions = positions;
  38071. vertexData.normals = normals;
  38072. vertexData.uvs = uvs;
  38073. if (faceColors) {
  38074. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38075. vertexData.colors = totalColors;
  38076. }
  38077. return vertexData;
  38078. };
  38079. /**
  38080. * Creates the VertexData of the IcoSphere
  38081. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38082. * * radius the radius of the IcoSphere, optional default 1
  38083. * * radiusX allows stretching in the x direction, optional, default radius
  38084. * * radiusY allows stretching in the y direction, optional, default radius
  38085. * * radiusZ allows stretching in the z direction, optional, default radius
  38086. * * flat when true creates a flat shaded mesh, optional, default true
  38087. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38088. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38089. * * 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)
  38090. * * 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)
  38091. * @returns the VertexData of the IcoSphere
  38092. */
  38093. VertexData.CreateIcoSphere = function (options) {
  38094. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38095. var radius = options.radius || 1;
  38096. var flat = (options.flat === undefined) ? true : options.flat;
  38097. var subdivisions = options.subdivisions || 4;
  38098. var radiusX = options.radiusX || radius;
  38099. var radiusY = options.radiusY || radius;
  38100. var radiusZ = options.radiusZ || radius;
  38101. var t = (1 + Math.sqrt(5)) / 2;
  38102. // 12 vertex x,y,z
  38103. var ico_vertices = [
  38104. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38105. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38106. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38107. ];
  38108. // index of 3 vertex makes a face of icopshere
  38109. var ico_indices = [
  38110. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38111. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38112. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38113. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38114. ];
  38115. // vertex for uv have aliased position, not for UV
  38116. var vertices_unalias_id = [
  38117. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38118. // vertex alias
  38119. 0,
  38120. 2,
  38121. 3,
  38122. 3,
  38123. 3,
  38124. 4,
  38125. 7,
  38126. 8,
  38127. 9,
  38128. 9,
  38129. 10,
  38130. 11 // 23: B + 12
  38131. ];
  38132. // uv as integer step (not pixels !)
  38133. var ico_vertexuv = [
  38134. 5, 1, 3, 1, 6, 4, 0, 0,
  38135. 5, 3, 4, 2, 2, 2, 4, 0,
  38136. 2, 0, 1, 1, 6, 0, 6, 2,
  38137. // vertex alias (for same vertex on different faces)
  38138. 0, 4,
  38139. 3, 3,
  38140. 4, 4,
  38141. 3, 1,
  38142. 4, 2,
  38143. 4, 4,
  38144. 0, 2,
  38145. 1, 1,
  38146. 2, 2,
  38147. 3, 3,
  38148. 1, 3,
  38149. 2, 4 // 23: B + 12
  38150. ];
  38151. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38152. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38153. // First island of uv mapping
  38154. // v = 4h 3+ 2
  38155. // v = 3h 9+ 4
  38156. // v = 2h 9+ 5 B
  38157. // v = 1h 9 1 0
  38158. // v = 0h 3 8 7 A
  38159. // u = 0 1 2 3 4 5 6 *a
  38160. // Second island of uv mapping
  38161. // v = 4h 0+ B+ 4+
  38162. // v = 3h A+ 2+
  38163. // v = 2h 7+ 6 3+
  38164. // v = 1h 8+ 3+
  38165. // v = 0h
  38166. // u = 0 1 2 3 4 5 6 *a
  38167. // Face layout on texture UV mapping
  38168. // ============
  38169. // \ 4 /\ 16 / ======
  38170. // \ / \ / /\ 11 /
  38171. // \/ 7 \/ / \ /
  38172. // ======= / 10 \/
  38173. // /\ 17 /\ =======
  38174. // / \ / \ \ 15 /\
  38175. // / 8 \/ 12 \ \ / \
  38176. // ============ \/ 6 \
  38177. // \ 18 /\ ============
  38178. // \ / \ \ 5 /\ 0 /
  38179. // \/ 13 \ \ / \ /
  38180. // ======= \/ 1 \/
  38181. // =============
  38182. // /\ 19 /\ 2 /\
  38183. // / \ / \ / \
  38184. // / 14 \/ 9 \/ 3 \
  38185. // ===================
  38186. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38187. var ustep = 138 / 1024;
  38188. var vstep = 239 / 1024;
  38189. var uoffset = 60 / 1024;
  38190. var voffset = 26 / 1024;
  38191. // Second island should have margin, not to touch the first island
  38192. // avoid any borderline artefact in pixel rounding
  38193. var island_u_offset = -40 / 1024;
  38194. var island_v_offset = +20 / 1024;
  38195. // face is either island 0 or 1 :
  38196. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38197. var island = [
  38198. 0, 0, 0, 0, 1,
  38199. 0, 0, 1, 1, 0,
  38200. 0, 0, 1, 1, 0,
  38201. 0, 1, 1, 1, 0 // 15 - 19
  38202. ];
  38203. var indices = new Array();
  38204. var positions = new Array();
  38205. var normals = new Array();
  38206. var uvs = new Array();
  38207. var current_indice = 0;
  38208. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38209. var face_vertex_pos = new Array(3);
  38210. var face_vertex_uv = new Array(3);
  38211. var v012;
  38212. for (v012 = 0; v012 < 3; v012++) {
  38213. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38214. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38215. }
  38216. // create all with normals
  38217. for (var face = 0; face < 20; face++) {
  38218. // 3 vertex per face
  38219. for (v012 = 0; v012 < 3; v012++) {
  38220. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38221. var v_id = ico_indices[3 * face + v012];
  38222. // vertex have 3D position (x,y,z)
  38223. 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]);
  38224. // Normalize to get normal, then scale to radius
  38225. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38226. // uv Coordinates from vertex ID
  38227. 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);
  38228. }
  38229. // Subdivide the face (interpolate pos, norm, uv)
  38230. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38231. // - norm is linear interpolation of vertex corner normal
  38232. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38233. // - uv is linear interpolation
  38234. //
  38235. // Topology is as below for sub-divide by 2
  38236. // vertex shown as v0,v1,v2
  38237. // interp index is i1 to progress in range [v0,v1[
  38238. // interp index is i2 to progress in range [v0,v2[
  38239. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38240. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38241. //
  38242. //
  38243. // i2 v2
  38244. // ^ ^
  38245. // / / \
  38246. // / / \
  38247. // / / \
  38248. // / / (0,1) \
  38249. // / #---------\
  38250. // / / \ (0,0)'/ \
  38251. // / / \ / \
  38252. // / / \ / \
  38253. // / / (0,0) \ / (1,0) \
  38254. // / #---------#---------\
  38255. // v0 v1
  38256. //
  38257. // --------------------> i1
  38258. //
  38259. // interp of (i1,i2):
  38260. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38261. // along i1 : lerp(x0,x1, i1/(S-i2))
  38262. //
  38263. // centroid of triangle is needed to get help normal computation
  38264. // (c1,c2) are used for centroid location
  38265. var interp_vertex = function (i1, i2, c1, c2) {
  38266. // vertex is interpolated from
  38267. // - face_vertex_pos[0..2]
  38268. // - face_vertex_uv[0..2]
  38269. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38270. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38271. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38272. pos_interp.normalize();
  38273. var vertex_normal;
  38274. if (flat) {
  38275. // in flat mode, recalculate normal as face centroid normal
  38276. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38277. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38278. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38279. }
  38280. else {
  38281. // in smooth mode, recalculate normal from each single vertex position
  38282. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38283. }
  38284. // Vertex normal need correction due to X,Y,Z radius scaling
  38285. vertex_normal.x /= radiusX;
  38286. vertex_normal.y /= radiusY;
  38287. vertex_normal.z /= radiusZ;
  38288. vertex_normal.normalize();
  38289. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38290. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38291. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38292. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38293. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38294. uvs.push(uv_interp.x, uv_interp.y);
  38295. // push each vertex has member of a face
  38296. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38297. indices.push(current_indice);
  38298. current_indice++;
  38299. };
  38300. for (var i2 = 0; i2 < subdivisions; i2++) {
  38301. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38302. // face : (i1,i2) for /\ :
  38303. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38304. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38305. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38306. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38307. if (i1 + i2 + 1 < subdivisions) {
  38308. // face : (i1,i2)' for \/ :
  38309. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38310. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38311. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38312. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38313. }
  38314. }
  38315. }
  38316. }
  38317. // Sides
  38318. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38319. // Result
  38320. var vertexData = new VertexData();
  38321. vertexData.indices = indices;
  38322. vertexData.positions = positions;
  38323. vertexData.normals = normals;
  38324. vertexData.uvs = uvs;
  38325. return vertexData;
  38326. };
  38327. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38328. /**
  38329. * Creates the VertexData for a Polyhedron
  38330. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38331. * * type provided types are:
  38332. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38333. * * 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)
  38334. * * size the size of the IcoSphere, optional default 1
  38335. * * sizeX allows stretching in the x direction, optional, default size
  38336. * * sizeY allows stretching in the y direction, optional, default size
  38337. * * sizeZ allows stretching in the z direction, optional, default size
  38338. * * 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
  38339. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38340. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38341. * * flat when true creates a flat shaded mesh, optional, default true
  38342. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38343. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38344. * * 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)
  38345. * * 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)
  38346. * @returns the VertexData of the Polyhedron
  38347. */
  38348. VertexData.CreatePolyhedron = function (options) {
  38349. // provided polyhedron types :
  38350. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38351. // 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)
  38352. var polyhedra = [];
  38353. 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]] };
  38354. 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]] };
  38355. polyhedra[2] = {
  38356. 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]],
  38357. 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]]
  38358. };
  38359. polyhedra[3] = {
  38360. 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]],
  38361. 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]]
  38362. };
  38363. polyhedra[4] = {
  38364. 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]],
  38365. 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]]
  38366. };
  38367. 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]] };
  38368. 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]] };
  38369. 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]] };
  38370. 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]] };
  38371. 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]] };
  38372. 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]] };
  38373. 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]] };
  38374. 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]] };
  38375. 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]] };
  38376. polyhedra[14] = {
  38377. 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]],
  38378. 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]]
  38379. };
  38380. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38381. var size = options.size;
  38382. var sizeX = options.sizeX || size || 1;
  38383. var sizeY = options.sizeY || size || 1;
  38384. var sizeZ = options.sizeZ || size || 1;
  38385. var data = options.custom || polyhedra[type];
  38386. var nbfaces = data.face.length;
  38387. var faceUV = options.faceUV || new Array(nbfaces);
  38388. var faceColors = options.faceColors;
  38389. var flat = (options.flat === undefined) ? true : options.flat;
  38390. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38391. var positions = new Array();
  38392. var indices = new Array();
  38393. var normals = new Array();
  38394. var uvs = new Array();
  38395. var colors = new Array();
  38396. var index = 0;
  38397. var faceIdx = 0; // face cursor in the array "indexes"
  38398. var indexes = new Array();
  38399. var i = 0;
  38400. var f = 0;
  38401. var u, v, ang, x, y, tmp;
  38402. // default face colors and UV if undefined
  38403. if (flat) {
  38404. for (f = 0; f < nbfaces; f++) {
  38405. if (faceColors && faceColors[f] === undefined) {
  38406. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38407. }
  38408. if (faceUV && faceUV[f] === undefined) {
  38409. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38410. }
  38411. }
  38412. }
  38413. if (!flat) {
  38414. for (i = 0; i < data.vertex.length; i++) {
  38415. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38416. uvs.push(0, 0);
  38417. }
  38418. for (f = 0; f < nbfaces; f++) {
  38419. for (i = 0; i < data.face[f].length - 2; i++) {
  38420. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38421. }
  38422. }
  38423. }
  38424. else {
  38425. for (f = 0; f < nbfaces; f++) {
  38426. var fl = data.face[f].length; // number of vertices of the current face
  38427. ang = 2 * Math.PI / fl;
  38428. x = 0.5 * Math.tan(ang / 2);
  38429. y = 0.5;
  38430. // positions, uvs, colors
  38431. for (i = 0; i < fl; i++) {
  38432. // positions
  38433. 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);
  38434. indexes.push(index);
  38435. index++;
  38436. // uvs
  38437. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38438. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38439. uvs.push(u, v);
  38440. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38441. y = x * Math.sin(ang) + y * Math.cos(ang);
  38442. x = tmp;
  38443. // colors
  38444. if (faceColors) {
  38445. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38446. }
  38447. }
  38448. // indices from indexes
  38449. for (i = 0; i < fl - 2; i++) {
  38450. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38451. }
  38452. faceIdx += fl;
  38453. }
  38454. }
  38455. VertexData.ComputeNormals(positions, indices, normals);
  38456. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38457. var vertexData = new VertexData();
  38458. vertexData.positions = positions;
  38459. vertexData.indices = indices;
  38460. vertexData.normals = normals;
  38461. vertexData.uvs = uvs;
  38462. if (faceColors && flat) {
  38463. vertexData.colors = colors;
  38464. }
  38465. return vertexData;
  38466. };
  38467. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38468. /**
  38469. * Creates the VertexData for a TorusKnot
  38470. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38471. * * radius the radius of the torus knot, optional, default 2
  38472. * * tube the thickness of the tube, optional, default 0.5
  38473. * * radialSegments the number of sides on each tube segments, optional, default 32
  38474. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38475. * * p the number of windings around the z axis, optional, default 2
  38476. * * q the number of windings around the x axis, optional, default 3
  38477. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38478. * * 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)
  38479. * * 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)
  38480. * @returns the VertexData of the Torus Knot
  38481. */
  38482. VertexData.CreateTorusKnot = function (options) {
  38483. var indices = new Array();
  38484. var positions = new Array();
  38485. var normals = new Array();
  38486. var uvs = new Array();
  38487. var radius = options.radius || 2;
  38488. var tube = options.tube || 0.5;
  38489. var radialSegments = options.radialSegments || 32;
  38490. var tubularSegments = options.tubularSegments || 32;
  38491. var p = options.p || 2;
  38492. var q = options.q || 3;
  38493. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38494. // Helper
  38495. var getPos = function (angle) {
  38496. var cu = Math.cos(angle);
  38497. var su = Math.sin(angle);
  38498. var quOverP = q / p * angle;
  38499. var cs = Math.cos(quOverP);
  38500. var tx = radius * (2 + cs) * 0.5 * cu;
  38501. var ty = radius * (2 + cs) * su * 0.5;
  38502. var tz = radius * Math.sin(quOverP) * 0.5;
  38503. return new BABYLON.Vector3(tx, ty, tz);
  38504. };
  38505. // Vertices
  38506. var i;
  38507. var j;
  38508. for (i = 0; i <= radialSegments; i++) {
  38509. var modI = i % radialSegments;
  38510. var u = modI / radialSegments * 2 * p * Math.PI;
  38511. var p1 = getPos(u);
  38512. var p2 = getPos(u + 0.01);
  38513. var tang = p2.subtract(p1);
  38514. var n = p2.add(p1);
  38515. var bitan = BABYLON.Vector3.Cross(tang, n);
  38516. n = BABYLON.Vector3.Cross(bitan, tang);
  38517. bitan.normalize();
  38518. n.normalize();
  38519. for (j = 0; j < tubularSegments; j++) {
  38520. var modJ = j % tubularSegments;
  38521. var v = modJ / tubularSegments * 2 * Math.PI;
  38522. var cx = -tube * Math.cos(v);
  38523. var cy = tube * Math.sin(v);
  38524. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38525. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38526. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38527. uvs.push(i / radialSegments);
  38528. uvs.push(j / tubularSegments);
  38529. }
  38530. }
  38531. for (i = 0; i < radialSegments; i++) {
  38532. for (j = 0; j < tubularSegments; j++) {
  38533. var jNext = (j + 1) % tubularSegments;
  38534. var a = i * tubularSegments + j;
  38535. var b = (i + 1) * tubularSegments + j;
  38536. var c = (i + 1) * tubularSegments + jNext;
  38537. var d = i * tubularSegments + jNext;
  38538. indices.push(d);
  38539. indices.push(b);
  38540. indices.push(a);
  38541. indices.push(d);
  38542. indices.push(c);
  38543. indices.push(b);
  38544. }
  38545. }
  38546. // Normals
  38547. VertexData.ComputeNormals(positions, indices, normals);
  38548. // Sides
  38549. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38550. // Result
  38551. var vertexData = new VertexData();
  38552. vertexData.indices = indices;
  38553. vertexData.positions = positions;
  38554. vertexData.normals = normals;
  38555. vertexData.uvs = uvs;
  38556. return vertexData;
  38557. };
  38558. // Tools
  38559. /**
  38560. * Compute normals for given positions and indices
  38561. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38562. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38563. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38564. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38565. * * facetNormals : optional array of facet normals (vector3)
  38566. * * facetPositions : optional array of facet positions (vector3)
  38567. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38568. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38569. * * bInfo : optional bounding info, required for facetPartitioning computation
  38570. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38571. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38572. * * useRightHandedSystem: optional boolean to for right handed system computation
  38573. * * depthSort : optional boolean to enable the facet depth sort computation
  38574. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38575. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38576. */
  38577. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38578. // temporary scalar variables
  38579. var index = 0; // facet index
  38580. var p1p2x = 0.0; // p1p2 vector x coordinate
  38581. var p1p2y = 0.0; // p1p2 vector y coordinate
  38582. var p1p2z = 0.0; // p1p2 vector z coordinate
  38583. var p3p2x = 0.0; // p3p2 vector x coordinate
  38584. var p3p2y = 0.0; // p3p2 vector y coordinate
  38585. var p3p2z = 0.0; // p3p2 vector z coordinate
  38586. var faceNormalx = 0.0; // facet normal x coordinate
  38587. var faceNormaly = 0.0; // facet normal y coordinate
  38588. var faceNormalz = 0.0; // facet normal z coordinate
  38589. var length = 0.0; // facet normal length before normalization
  38590. var v1x = 0; // vector1 x index in the positions array
  38591. var v1y = 0; // vector1 y index in the positions array
  38592. var v1z = 0; // vector1 z index in the positions array
  38593. var v2x = 0; // vector2 x index in the positions array
  38594. var v2y = 0; // vector2 y index in the positions array
  38595. var v2z = 0; // vector2 z index in the positions array
  38596. var v3x = 0; // vector3 x index in the positions array
  38597. var v3y = 0; // vector3 y index in the positions array
  38598. var v3z = 0; // vector3 z index in the positions array
  38599. var computeFacetNormals = false;
  38600. var computeFacetPositions = false;
  38601. var computeFacetPartitioning = false;
  38602. var computeDepthSort = false;
  38603. var faceNormalSign = 1;
  38604. var ratio = 0;
  38605. var distanceTo = null;
  38606. if (options) {
  38607. computeFacetNormals = (options.facetNormals) ? true : false;
  38608. computeFacetPositions = (options.facetPositions) ? true : false;
  38609. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38610. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38611. ratio = options.ratio || 0;
  38612. computeDepthSort = (options.depthSort) ? true : false;
  38613. distanceTo = (options.distanceTo);
  38614. if (computeDepthSort) {
  38615. if (distanceTo === undefined) {
  38616. distanceTo = BABYLON.Vector3.Zero();
  38617. }
  38618. var depthSortedFacets = options.depthSortedFacets;
  38619. }
  38620. }
  38621. // facetPartitioning reinit if needed
  38622. var xSubRatio = 0;
  38623. var ySubRatio = 0;
  38624. var zSubRatio = 0;
  38625. var subSq = 0;
  38626. if (computeFacetPartitioning && options && options.bbSize) {
  38627. var ox = 0; // X partitioning index for facet position
  38628. var oy = 0; // Y partinioning index for facet position
  38629. var oz = 0; // Z partinioning index for facet position
  38630. var b1x = 0; // X partitioning index for facet v1 vertex
  38631. var b1y = 0; // Y partitioning index for facet v1 vertex
  38632. var b1z = 0; // z partitioning index for facet v1 vertex
  38633. var b2x = 0; // X partitioning index for facet v2 vertex
  38634. var b2y = 0; // Y partitioning index for facet v2 vertex
  38635. var b2z = 0; // Z partitioning index for facet v2 vertex
  38636. var b3x = 0; // X partitioning index for facet v3 vertex
  38637. var b3y = 0; // Y partitioning index for facet v3 vertex
  38638. var b3z = 0; // Z partitioning index for facet v3 vertex
  38639. var block_idx_o = 0; // facet barycenter block index
  38640. var block_idx_v1 = 0; // v1 vertex block index
  38641. var block_idx_v2 = 0; // v2 vertex block index
  38642. var block_idx_v3 = 0; // v3 vertex block index
  38643. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38644. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38645. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38646. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38647. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38648. subSq = options.subDiv.max * options.subDiv.max;
  38649. options.facetPartitioning.length = 0;
  38650. }
  38651. // reset the normals
  38652. for (index = 0; index < positions.length; index++) {
  38653. normals[index] = 0.0;
  38654. }
  38655. // Loop : 1 indice triplet = 1 facet
  38656. var nbFaces = (indices.length / 3) | 0;
  38657. for (index = 0; index < nbFaces; index++) {
  38658. // get the indexes of the coordinates of each vertex of the facet
  38659. v1x = indices[index * 3] * 3;
  38660. v1y = v1x + 1;
  38661. v1z = v1x + 2;
  38662. v2x = indices[index * 3 + 1] * 3;
  38663. v2y = v2x + 1;
  38664. v2z = v2x + 2;
  38665. v3x = indices[index * 3 + 2] * 3;
  38666. v3y = v3x + 1;
  38667. v3z = v3x + 2;
  38668. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38669. p1p2y = positions[v1y] - positions[v2y];
  38670. p1p2z = positions[v1z] - positions[v2z];
  38671. p3p2x = positions[v3x] - positions[v2x];
  38672. p3p2y = positions[v3y] - positions[v2y];
  38673. p3p2z = positions[v3z] - positions[v2z];
  38674. // compute the face normal with the cross product
  38675. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38676. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38677. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38678. // normalize this normal and store it in the array facetData
  38679. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38680. length = (length === 0) ? 1.0 : length;
  38681. faceNormalx /= length;
  38682. faceNormaly /= length;
  38683. faceNormalz /= length;
  38684. if (computeFacetNormals && options) {
  38685. options.facetNormals[index].x = faceNormalx;
  38686. options.facetNormals[index].y = faceNormaly;
  38687. options.facetNormals[index].z = faceNormalz;
  38688. }
  38689. if (computeFacetPositions && options) {
  38690. // compute and the facet barycenter coordinates in the array facetPositions
  38691. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38692. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38693. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38694. }
  38695. if (computeFacetPartitioning && options) {
  38696. // store the facet indexes in arrays in the main facetPartitioning array :
  38697. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38698. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38699. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38700. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38701. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38702. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38703. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38704. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38705. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38706. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38707. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38708. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38709. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38710. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38711. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38712. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38713. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38714. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38715. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38716. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38717. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38718. // push each facet index in each block containing the vertex
  38719. options.facetPartitioning[block_idx_v1].push(index);
  38720. if (block_idx_v2 != block_idx_v1) {
  38721. options.facetPartitioning[block_idx_v2].push(index);
  38722. }
  38723. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38724. options.facetPartitioning[block_idx_v3].push(index);
  38725. }
  38726. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38727. options.facetPartitioning[block_idx_o].push(index);
  38728. }
  38729. }
  38730. if (computeDepthSort && options && options.facetPositions) {
  38731. var dsf = depthSortedFacets[index];
  38732. dsf.ind = index * 3;
  38733. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38734. }
  38735. // compute the normals anyway
  38736. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38737. normals[v1y] += faceNormaly;
  38738. normals[v1z] += faceNormalz;
  38739. normals[v2x] += faceNormalx;
  38740. normals[v2y] += faceNormaly;
  38741. normals[v2z] += faceNormalz;
  38742. normals[v3x] += faceNormalx;
  38743. normals[v3y] += faceNormaly;
  38744. normals[v3z] += faceNormalz;
  38745. }
  38746. // last normalization of each normal
  38747. for (index = 0; index < normals.length / 3; index++) {
  38748. faceNormalx = normals[index * 3];
  38749. faceNormaly = normals[index * 3 + 1];
  38750. faceNormalz = normals[index * 3 + 2];
  38751. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38752. length = (length === 0) ? 1.0 : length;
  38753. faceNormalx /= length;
  38754. faceNormaly /= length;
  38755. faceNormalz /= length;
  38756. normals[index * 3] = faceNormalx;
  38757. normals[index * 3 + 1] = faceNormaly;
  38758. normals[index * 3 + 2] = faceNormalz;
  38759. }
  38760. };
  38761. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38762. var li = indices.length;
  38763. var ln = normals.length;
  38764. var i;
  38765. var n;
  38766. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38767. switch (sideOrientation) {
  38768. case BABYLON.Mesh.FRONTSIDE:
  38769. // nothing changed
  38770. break;
  38771. case BABYLON.Mesh.BACKSIDE:
  38772. var tmp;
  38773. // indices
  38774. for (i = 0; i < li; i += 3) {
  38775. tmp = indices[i];
  38776. indices[i] = indices[i + 2];
  38777. indices[i + 2] = tmp;
  38778. }
  38779. // normals
  38780. for (n = 0; n < ln; n++) {
  38781. normals[n] = -normals[n];
  38782. }
  38783. break;
  38784. case BABYLON.Mesh.DOUBLESIDE:
  38785. // positions
  38786. var lp = positions.length;
  38787. var l = lp / 3;
  38788. for (var p = 0; p < lp; p++) {
  38789. positions[lp + p] = positions[p];
  38790. }
  38791. // indices
  38792. for (i = 0; i < li; i += 3) {
  38793. indices[i + li] = indices[i + 2] + l;
  38794. indices[i + 1 + li] = indices[i + 1] + l;
  38795. indices[i + 2 + li] = indices[i] + l;
  38796. }
  38797. // normals
  38798. for (n = 0; n < ln; n++) {
  38799. normals[ln + n] = -normals[n];
  38800. }
  38801. // uvs
  38802. var lu = uvs.length;
  38803. var u = 0;
  38804. for (u = 0; u < lu; u++) {
  38805. uvs[u + lu] = uvs[u];
  38806. }
  38807. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38808. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38809. u = 0;
  38810. for (i = 0; i < lu / 2; i++) {
  38811. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38812. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38813. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38814. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38815. u += 2;
  38816. }
  38817. break;
  38818. }
  38819. };
  38820. /**
  38821. * Applies VertexData created from the imported parameters to the geometry
  38822. * @param parsedVertexData the parsed data from an imported file
  38823. * @param geometry the geometry to apply the VertexData to
  38824. */
  38825. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38826. var vertexData = new VertexData();
  38827. // positions
  38828. var positions = parsedVertexData.positions;
  38829. if (positions) {
  38830. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38831. }
  38832. // normals
  38833. var normals = parsedVertexData.normals;
  38834. if (normals) {
  38835. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38836. }
  38837. // tangents
  38838. var tangents = parsedVertexData.tangents;
  38839. if (tangents) {
  38840. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38841. }
  38842. // uvs
  38843. var uvs = parsedVertexData.uvs;
  38844. if (uvs) {
  38845. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38846. }
  38847. // uv2s
  38848. var uv2s = parsedVertexData.uv2s;
  38849. if (uv2s) {
  38850. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38851. }
  38852. // uv3s
  38853. var uv3s = parsedVertexData.uv3s;
  38854. if (uv3s) {
  38855. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38856. }
  38857. // uv4s
  38858. var uv4s = parsedVertexData.uv4s;
  38859. if (uv4s) {
  38860. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38861. }
  38862. // uv5s
  38863. var uv5s = parsedVertexData.uv5s;
  38864. if (uv5s) {
  38865. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38866. }
  38867. // uv6s
  38868. var uv6s = parsedVertexData.uv6s;
  38869. if (uv6s) {
  38870. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38871. }
  38872. // colors
  38873. var colors = parsedVertexData.colors;
  38874. if (colors) {
  38875. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38876. }
  38877. // matricesIndices
  38878. var matricesIndices = parsedVertexData.matricesIndices;
  38879. if (matricesIndices) {
  38880. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38881. }
  38882. // matricesWeights
  38883. var matricesWeights = parsedVertexData.matricesWeights;
  38884. if (matricesWeights) {
  38885. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38886. }
  38887. // indices
  38888. var indices = parsedVertexData.indices;
  38889. if (indices) {
  38890. vertexData.indices = indices;
  38891. }
  38892. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38893. };
  38894. return VertexData;
  38895. }());
  38896. BABYLON.VertexData = VertexData;
  38897. })(BABYLON || (BABYLON = {}));
  38898. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38899. var BABYLON;
  38900. (function (BABYLON) {
  38901. /**
  38902. * Class used to store geometry data (vertex buffers + index buffer)
  38903. */
  38904. var Geometry = /** @class */ (function () {
  38905. /**
  38906. * Creates a new geometry
  38907. * @param id defines the unique ID
  38908. * @param scene defines the hosting scene
  38909. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38910. * @param updatable defines if geometry must be updatable (false by default)
  38911. * @param mesh defines the mesh that will be associated with the geometry
  38912. */
  38913. function Geometry(id, scene, vertexData, updatable, mesh) {
  38914. if (updatable === void 0) { updatable = false; }
  38915. if (mesh === void 0) { mesh = null; }
  38916. /**
  38917. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38918. */
  38919. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38920. this._totalVertices = 0;
  38921. this._isDisposed = false;
  38922. this._indexBufferIsUpdatable = false;
  38923. this.id = id;
  38924. this._engine = scene.getEngine();
  38925. this._meshes = [];
  38926. this._scene = scene;
  38927. //Init vertex buffer cache
  38928. this._vertexBuffers = {};
  38929. this._indices = [];
  38930. this._updatable = updatable;
  38931. // vertexData
  38932. if (vertexData) {
  38933. this.setAllVerticesData(vertexData, updatable);
  38934. }
  38935. else {
  38936. this._totalVertices = 0;
  38937. this._indices = [];
  38938. }
  38939. if (this._engine.getCaps().vertexArrayObject) {
  38940. this._vertexArrayObjects = {};
  38941. }
  38942. // applyToMesh
  38943. if (mesh) {
  38944. if (mesh.getClassName() === "LinesMesh") {
  38945. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38946. this._updateExtend();
  38947. }
  38948. this.applyToMesh(mesh);
  38949. mesh.computeWorldMatrix(true);
  38950. }
  38951. }
  38952. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38953. /**
  38954. * 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
  38955. */
  38956. get: function () {
  38957. return this._boundingBias;
  38958. },
  38959. /**
  38960. * 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
  38961. */
  38962. set: function (value) {
  38963. if (this._boundingBias && this._boundingBias.equals(value)) {
  38964. return;
  38965. }
  38966. this._boundingBias = value.clone();
  38967. this._updateBoundingInfo(true, null);
  38968. },
  38969. enumerable: true,
  38970. configurable: true
  38971. });
  38972. /**
  38973. * Static function used to attach a new empty geometry to a mesh
  38974. * @param mesh defines the mesh to attach the geometry to
  38975. * @returns the new {BABYLON.Geometry}
  38976. */
  38977. Geometry.CreateGeometryForMesh = function (mesh) {
  38978. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38979. geometry.applyToMesh(mesh);
  38980. return geometry;
  38981. };
  38982. Object.defineProperty(Geometry.prototype, "extend", {
  38983. /**
  38984. * Gets the current extend of the geometry
  38985. */
  38986. get: function () {
  38987. return this._extend;
  38988. },
  38989. enumerable: true,
  38990. configurable: true
  38991. });
  38992. /**
  38993. * Gets the hosting scene
  38994. * @returns the hosting {BABYLON.Scene}
  38995. */
  38996. Geometry.prototype.getScene = function () {
  38997. return this._scene;
  38998. };
  38999. /**
  39000. * Gets the hosting engine
  39001. * @returns the hosting {BABYLON.Engine}
  39002. */
  39003. Geometry.prototype.getEngine = function () {
  39004. return this._engine;
  39005. };
  39006. /**
  39007. * Defines if the geometry is ready to use
  39008. * @returns true if the geometry is ready to be used
  39009. */
  39010. Geometry.prototype.isReady = function () {
  39011. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39012. };
  39013. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39014. /**
  39015. * Gets a value indicating that the geometry should not be serialized
  39016. */
  39017. get: function () {
  39018. for (var index = 0; index < this._meshes.length; index++) {
  39019. if (!this._meshes[index].doNotSerialize) {
  39020. return false;
  39021. }
  39022. }
  39023. return true;
  39024. },
  39025. enumerable: true,
  39026. configurable: true
  39027. });
  39028. /** @hidden */
  39029. Geometry.prototype._rebuild = function () {
  39030. if (this._vertexArrayObjects) {
  39031. this._vertexArrayObjects = {};
  39032. }
  39033. // Index buffer
  39034. if (this._meshes.length !== 0 && this._indices) {
  39035. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39036. }
  39037. // Vertex buffers
  39038. for (var key in this._vertexBuffers) {
  39039. var vertexBuffer = this._vertexBuffers[key];
  39040. vertexBuffer._rebuild();
  39041. }
  39042. };
  39043. /**
  39044. * Affects all geometry data in one call
  39045. * @param vertexData defines the geometry data
  39046. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39047. */
  39048. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39049. vertexData.applyToGeometry(this, updatable);
  39050. this.notifyUpdate();
  39051. };
  39052. /**
  39053. * Set specific vertex data
  39054. * @param kind defines the data kind (Position, normal, etc...)
  39055. * @param data defines the vertex data to use
  39056. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39057. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39058. */
  39059. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39060. if (updatable === void 0) { updatable = false; }
  39061. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39062. this.setVerticesBuffer(buffer);
  39063. };
  39064. /**
  39065. * Removes a specific vertex data
  39066. * @param kind defines the data kind (Position, normal, etc...)
  39067. */
  39068. Geometry.prototype.removeVerticesData = function (kind) {
  39069. if (this._vertexBuffers[kind]) {
  39070. this._vertexBuffers[kind].dispose();
  39071. delete this._vertexBuffers[kind];
  39072. }
  39073. };
  39074. /**
  39075. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39076. * @param buffer defines the vertex buffer to use
  39077. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39078. */
  39079. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39080. if (totalVertices === void 0) { totalVertices = null; }
  39081. var kind = buffer.getKind();
  39082. if (this._vertexBuffers[kind]) {
  39083. this._vertexBuffers[kind].dispose();
  39084. }
  39085. this._vertexBuffers[kind] = buffer;
  39086. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39087. var data = buffer.getData();
  39088. if (totalVertices != null) {
  39089. this._totalVertices = totalVertices;
  39090. }
  39091. else {
  39092. if (data != null) {
  39093. this._totalVertices = data.length / (buffer.byteStride / 4);
  39094. }
  39095. }
  39096. this._updateExtend(data);
  39097. this._resetPointsArrayCache();
  39098. var meshes = this._meshes;
  39099. var numOfMeshes = meshes.length;
  39100. for (var index = 0; index < numOfMeshes; index++) {
  39101. var mesh = meshes[index];
  39102. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39103. mesh._createGlobalSubMesh(false);
  39104. mesh.computeWorldMatrix(true);
  39105. }
  39106. }
  39107. this.notifyUpdate(kind);
  39108. if (this._vertexArrayObjects) {
  39109. this._disposeVertexArrayObjects();
  39110. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39111. }
  39112. };
  39113. /**
  39114. * Update a specific vertex buffer
  39115. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39116. * It will do nothing if the buffer is not updatable
  39117. * @param kind defines the data kind (Position, normal, etc...)
  39118. * @param data defines the data to use
  39119. * @param offset defines the offset in the target buffer where to store the data
  39120. * @param useBytes set to true if the offset is in bytes
  39121. */
  39122. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39123. if (useBytes === void 0) { useBytes = false; }
  39124. var vertexBuffer = this.getVertexBuffer(kind);
  39125. if (!vertexBuffer) {
  39126. return;
  39127. }
  39128. vertexBuffer.updateDirectly(data, offset, useBytes);
  39129. this.notifyUpdate(kind);
  39130. };
  39131. /**
  39132. * Update a specific vertex buffer
  39133. * This function will create a new buffer if the current one is not updatable
  39134. * @param kind defines the data kind (Position, normal, etc...)
  39135. * @param data defines the data to use
  39136. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39137. */
  39138. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39139. if (updateExtends === void 0) { updateExtends = false; }
  39140. var vertexBuffer = this.getVertexBuffer(kind);
  39141. if (!vertexBuffer) {
  39142. return;
  39143. }
  39144. vertexBuffer.update(data);
  39145. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39146. this._updateBoundingInfo(updateExtends, data);
  39147. }
  39148. this.notifyUpdate(kind);
  39149. };
  39150. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39151. if (updateExtends) {
  39152. this._updateExtend(data);
  39153. }
  39154. var meshes = this._meshes;
  39155. var numOfMeshes = meshes.length;
  39156. this._resetPointsArrayCache();
  39157. for (var index = 0; index < numOfMeshes; index++) {
  39158. var mesh = meshes[index];
  39159. if (updateExtends) {
  39160. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39161. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39162. var subMesh = mesh.subMeshes[subIndex];
  39163. subMesh.refreshBoundingInfo();
  39164. }
  39165. }
  39166. }
  39167. };
  39168. /** @hidden */
  39169. Geometry.prototype._bind = function (effect, indexToBind) {
  39170. if (!effect) {
  39171. return;
  39172. }
  39173. if (indexToBind === undefined) {
  39174. indexToBind = this._indexBuffer;
  39175. }
  39176. var vbs = this.getVertexBuffers();
  39177. if (!vbs) {
  39178. return;
  39179. }
  39180. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39181. this._engine.bindBuffers(vbs, indexToBind, effect);
  39182. return;
  39183. }
  39184. // Using VAO
  39185. if (!this._vertexArrayObjects[effect.key]) {
  39186. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39187. }
  39188. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39189. };
  39190. /**
  39191. * Gets total number of vertices
  39192. * @returns the total number of vertices
  39193. */
  39194. Geometry.prototype.getTotalVertices = function () {
  39195. if (!this.isReady()) {
  39196. return 0;
  39197. }
  39198. return this._totalVertices;
  39199. };
  39200. /**
  39201. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39202. * @param kind defines the data kind (Position, normal, etc...)
  39203. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39204. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39205. * @returns a float array containing vertex data
  39206. */
  39207. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39208. var vertexBuffer = this.getVertexBuffer(kind);
  39209. if (!vertexBuffer) {
  39210. return null;
  39211. }
  39212. var data = vertexBuffer.getData();
  39213. if (!data) {
  39214. return null;
  39215. }
  39216. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39217. var count = this._totalVertices * vertexBuffer.getSize();
  39218. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39219. var copy_1 = new Array(count);
  39220. vertexBuffer.forEach(count, function (value, index) {
  39221. copy_1[index] = value;
  39222. });
  39223. return copy_1;
  39224. }
  39225. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39226. if (data instanceof Array) {
  39227. var offset = vertexBuffer.byteOffset / 4;
  39228. return BABYLON.Tools.Slice(data, offset, offset + count);
  39229. }
  39230. else if (data instanceof ArrayBuffer) {
  39231. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39232. }
  39233. else {
  39234. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39235. }
  39236. }
  39237. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39238. return BABYLON.Tools.Slice(data);
  39239. }
  39240. return data;
  39241. };
  39242. /**
  39243. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39244. * @param kind defines the data kind (Position, normal, etc...)
  39245. * @returns true if the vertex buffer with the specified kind is updatable
  39246. */
  39247. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39248. var vb = this._vertexBuffers[kind];
  39249. if (!vb) {
  39250. return false;
  39251. }
  39252. return vb.isUpdatable();
  39253. };
  39254. /**
  39255. * Gets a specific vertex buffer
  39256. * @param kind defines the data kind (Position, normal, etc...)
  39257. * @returns a {BABYLON.VertexBuffer}
  39258. */
  39259. Geometry.prototype.getVertexBuffer = function (kind) {
  39260. if (!this.isReady()) {
  39261. return null;
  39262. }
  39263. return this._vertexBuffers[kind];
  39264. };
  39265. /**
  39266. * Returns all vertex buffers
  39267. * @return an object holding all vertex buffers indexed by kind
  39268. */
  39269. Geometry.prototype.getVertexBuffers = function () {
  39270. if (!this.isReady()) {
  39271. return null;
  39272. }
  39273. return this._vertexBuffers;
  39274. };
  39275. /**
  39276. * Gets a boolean indicating if specific vertex buffer is present
  39277. * @param kind defines the data kind (Position, normal, etc...)
  39278. * @returns true if data is present
  39279. */
  39280. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39281. if (!this._vertexBuffers) {
  39282. if (this._delayInfo) {
  39283. return this._delayInfo.indexOf(kind) !== -1;
  39284. }
  39285. return false;
  39286. }
  39287. return this._vertexBuffers[kind] !== undefined;
  39288. };
  39289. /**
  39290. * Gets a list of all attached data kinds (Position, normal, etc...)
  39291. * @returns a list of string containing all kinds
  39292. */
  39293. Geometry.prototype.getVerticesDataKinds = function () {
  39294. var result = [];
  39295. var kind;
  39296. if (!this._vertexBuffers && this._delayInfo) {
  39297. for (kind in this._delayInfo) {
  39298. result.push(kind);
  39299. }
  39300. }
  39301. else {
  39302. for (kind in this._vertexBuffers) {
  39303. result.push(kind);
  39304. }
  39305. }
  39306. return result;
  39307. };
  39308. /**
  39309. * Update index buffer
  39310. * @param indices defines the indices to store in the index buffer
  39311. * @param offset defines the offset in the target buffer where to store the data
  39312. */
  39313. Geometry.prototype.updateIndices = function (indices, offset) {
  39314. if (!this._indexBuffer) {
  39315. return;
  39316. }
  39317. if (!this._indexBufferIsUpdatable) {
  39318. this.setIndices(indices, null, true);
  39319. }
  39320. else {
  39321. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39322. }
  39323. };
  39324. /**
  39325. * Creates a new index buffer
  39326. * @param indices defines the indices to store in the index buffer
  39327. * @param totalVertices defines the total number of vertices (could be null)
  39328. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39329. */
  39330. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39331. if (totalVertices === void 0) { totalVertices = null; }
  39332. if (updatable === void 0) { updatable = false; }
  39333. if (this._indexBuffer) {
  39334. this._engine._releaseBuffer(this._indexBuffer);
  39335. }
  39336. this._disposeVertexArrayObjects();
  39337. this._indices = indices;
  39338. this._indexBufferIsUpdatable = updatable;
  39339. if (this._meshes.length !== 0 && this._indices) {
  39340. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39341. }
  39342. if (totalVertices != undefined) { // including null and undefined
  39343. this._totalVertices = totalVertices;
  39344. }
  39345. var meshes = this._meshes;
  39346. var numOfMeshes = meshes.length;
  39347. for (var index = 0; index < numOfMeshes; index++) {
  39348. meshes[index]._createGlobalSubMesh(true);
  39349. }
  39350. this.notifyUpdate();
  39351. };
  39352. /**
  39353. * Return the total number of indices
  39354. * @returns the total number of indices
  39355. */
  39356. Geometry.prototype.getTotalIndices = function () {
  39357. if (!this.isReady()) {
  39358. return 0;
  39359. }
  39360. return this._indices.length;
  39361. };
  39362. /**
  39363. * Gets the index buffer array
  39364. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39365. * @returns the index buffer array
  39366. */
  39367. Geometry.prototype.getIndices = function (copyWhenShared) {
  39368. if (!this.isReady()) {
  39369. return null;
  39370. }
  39371. var orig = this._indices;
  39372. if (!copyWhenShared || this._meshes.length === 1) {
  39373. return orig;
  39374. }
  39375. else {
  39376. var len = orig.length;
  39377. var copy = [];
  39378. for (var i = 0; i < len; i++) {
  39379. copy.push(orig[i]);
  39380. }
  39381. return copy;
  39382. }
  39383. };
  39384. /**
  39385. * Gets the index buffer
  39386. * @return the index buffer
  39387. */
  39388. Geometry.prototype.getIndexBuffer = function () {
  39389. if (!this.isReady()) {
  39390. return null;
  39391. }
  39392. return this._indexBuffer;
  39393. };
  39394. /** @hidden */
  39395. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39396. if (effect === void 0) { effect = null; }
  39397. if (!effect || !this._vertexArrayObjects) {
  39398. return;
  39399. }
  39400. if (this._vertexArrayObjects[effect.key]) {
  39401. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39402. delete this._vertexArrayObjects[effect.key];
  39403. }
  39404. };
  39405. /**
  39406. * Release the associated resources for a specific mesh
  39407. * @param mesh defines the source mesh
  39408. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39409. */
  39410. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39411. var meshes = this._meshes;
  39412. var index = meshes.indexOf(mesh);
  39413. if (index === -1) {
  39414. return;
  39415. }
  39416. meshes.splice(index, 1);
  39417. mesh._geometry = null;
  39418. if (meshes.length === 0 && shouldDispose) {
  39419. this.dispose();
  39420. }
  39421. };
  39422. /**
  39423. * Apply current geometry to a given mesh
  39424. * @param mesh defines the mesh to apply geometry to
  39425. */
  39426. Geometry.prototype.applyToMesh = function (mesh) {
  39427. if (mesh._geometry === this) {
  39428. return;
  39429. }
  39430. var previousGeometry = mesh._geometry;
  39431. if (previousGeometry) {
  39432. previousGeometry.releaseForMesh(mesh);
  39433. }
  39434. var meshes = this._meshes;
  39435. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39436. mesh._geometry = this;
  39437. this._scene.pushGeometry(this);
  39438. meshes.push(mesh);
  39439. if (this.isReady()) {
  39440. this._applyToMesh(mesh);
  39441. }
  39442. else {
  39443. mesh._boundingInfo = this._boundingInfo;
  39444. }
  39445. };
  39446. Geometry.prototype._updateExtend = function (data) {
  39447. if (data === void 0) { data = null; }
  39448. if (!data) {
  39449. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39450. }
  39451. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39452. };
  39453. Geometry.prototype._applyToMesh = function (mesh) {
  39454. var numOfMeshes = this._meshes.length;
  39455. // vertexBuffers
  39456. for (var kind in this._vertexBuffers) {
  39457. if (numOfMeshes === 1) {
  39458. this._vertexBuffers[kind].create();
  39459. }
  39460. var buffer = this._vertexBuffers[kind].getBuffer();
  39461. if (buffer)
  39462. buffer.references = numOfMeshes;
  39463. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39464. if (!this._extend) {
  39465. this._updateExtend();
  39466. }
  39467. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39468. mesh._createGlobalSubMesh(false);
  39469. //bounding info was just created again, world matrix should be applied again.
  39470. mesh._updateBoundingInfo();
  39471. }
  39472. }
  39473. // indexBuffer
  39474. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39475. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39476. }
  39477. if (this._indexBuffer) {
  39478. this._indexBuffer.references = numOfMeshes;
  39479. }
  39480. };
  39481. Geometry.prototype.notifyUpdate = function (kind) {
  39482. if (this.onGeometryUpdated) {
  39483. this.onGeometryUpdated(this, kind);
  39484. }
  39485. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39486. var mesh = _a[_i];
  39487. mesh._markSubMeshesAsAttributesDirty();
  39488. }
  39489. };
  39490. /**
  39491. * Load the geometry if it was flagged as delay loaded
  39492. * @param scene defines the hosting scene
  39493. * @param onLoaded defines a callback called when the geometry is loaded
  39494. */
  39495. Geometry.prototype.load = function (scene, onLoaded) {
  39496. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39497. return;
  39498. }
  39499. if (this.isReady()) {
  39500. if (onLoaded) {
  39501. onLoaded();
  39502. }
  39503. return;
  39504. }
  39505. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39506. this._queueLoad(scene, onLoaded);
  39507. };
  39508. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39509. var _this = this;
  39510. if (!this.delayLoadingFile) {
  39511. return;
  39512. }
  39513. scene._addPendingData(this);
  39514. scene._loadFile(this.delayLoadingFile, function (data) {
  39515. if (!_this._delayLoadingFunction) {
  39516. return;
  39517. }
  39518. _this._delayLoadingFunction(JSON.parse(data), _this);
  39519. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39520. _this._delayInfo = [];
  39521. scene._removePendingData(_this);
  39522. var meshes = _this._meshes;
  39523. var numOfMeshes = meshes.length;
  39524. for (var index = 0; index < numOfMeshes; index++) {
  39525. _this._applyToMesh(meshes[index]);
  39526. }
  39527. if (onLoaded) {
  39528. onLoaded();
  39529. }
  39530. }, undefined, true);
  39531. };
  39532. /**
  39533. * Invert the geometry to move from a right handed system to a left handed one.
  39534. */
  39535. Geometry.prototype.toLeftHanded = function () {
  39536. // Flip faces
  39537. var tIndices = this.getIndices(false);
  39538. if (tIndices != null && tIndices.length > 0) {
  39539. for (var i = 0; i < tIndices.length; i += 3) {
  39540. var tTemp = tIndices[i + 0];
  39541. tIndices[i + 0] = tIndices[i + 2];
  39542. tIndices[i + 2] = tTemp;
  39543. }
  39544. this.setIndices(tIndices);
  39545. }
  39546. // Negate position.z
  39547. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39548. if (tPositions != null && tPositions.length > 0) {
  39549. for (var i = 0; i < tPositions.length; i += 3) {
  39550. tPositions[i + 2] = -tPositions[i + 2];
  39551. }
  39552. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39553. }
  39554. // Negate normal.z
  39555. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39556. if (tNormals != null && tNormals.length > 0) {
  39557. for (var i = 0; i < tNormals.length; i += 3) {
  39558. tNormals[i + 2] = -tNormals[i + 2];
  39559. }
  39560. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39561. }
  39562. };
  39563. // Cache
  39564. /** @hidden */
  39565. Geometry.prototype._resetPointsArrayCache = function () {
  39566. this._positions = null;
  39567. };
  39568. /** @hidden */
  39569. Geometry.prototype._generatePointsArray = function () {
  39570. if (this._positions)
  39571. return true;
  39572. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39573. if (!data || data.length === 0) {
  39574. return false;
  39575. }
  39576. this._positions = [];
  39577. for (var index = 0; index < data.length; index += 3) {
  39578. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39579. }
  39580. return true;
  39581. };
  39582. /**
  39583. * Gets a value indicating if the geometry is disposed
  39584. * @returns true if the geometry was disposed
  39585. */
  39586. Geometry.prototype.isDisposed = function () {
  39587. return this._isDisposed;
  39588. };
  39589. Geometry.prototype._disposeVertexArrayObjects = function () {
  39590. if (this._vertexArrayObjects) {
  39591. for (var kind in this._vertexArrayObjects) {
  39592. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39593. }
  39594. this._vertexArrayObjects = {};
  39595. }
  39596. };
  39597. /**
  39598. * Free all associated resources
  39599. */
  39600. Geometry.prototype.dispose = function () {
  39601. var meshes = this._meshes;
  39602. var numOfMeshes = meshes.length;
  39603. var index;
  39604. for (index = 0; index < numOfMeshes; index++) {
  39605. this.releaseForMesh(meshes[index]);
  39606. }
  39607. this._meshes = [];
  39608. this._disposeVertexArrayObjects();
  39609. for (var kind in this._vertexBuffers) {
  39610. this._vertexBuffers[kind].dispose();
  39611. }
  39612. this._vertexBuffers = {};
  39613. this._totalVertices = 0;
  39614. if (this._indexBuffer) {
  39615. this._engine._releaseBuffer(this._indexBuffer);
  39616. }
  39617. this._indexBuffer = null;
  39618. this._indices = [];
  39619. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39620. this.delayLoadingFile = null;
  39621. this._delayLoadingFunction = null;
  39622. this._delayInfo = [];
  39623. this._boundingInfo = null;
  39624. this._scene.removeGeometry(this);
  39625. this._isDisposed = true;
  39626. };
  39627. /**
  39628. * Clone the current geometry into a new geometry
  39629. * @param id defines the unique ID of the new geometry
  39630. * @returns a new geometry object
  39631. */
  39632. Geometry.prototype.copy = function (id) {
  39633. var vertexData = new BABYLON.VertexData();
  39634. vertexData.indices = [];
  39635. var indices = this.getIndices();
  39636. if (indices) {
  39637. for (var index = 0; index < indices.length; index++) {
  39638. vertexData.indices.push(indices[index]);
  39639. }
  39640. }
  39641. var updatable = false;
  39642. var stopChecking = false;
  39643. var kind;
  39644. for (kind in this._vertexBuffers) {
  39645. // using slice() to make a copy of the array and not just reference it
  39646. var data = this.getVerticesData(kind);
  39647. if (data instanceof Float32Array) {
  39648. vertexData.set(new Float32Array(data), kind);
  39649. }
  39650. else {
  39651. vertexData.set(data.slice(0), kind);
  39652. }
  39653. if (!stopChecking) {
  39654. var vb = this.getVertexBuffer(kind);
  39655. if (vb) {
  39656. updatable = vb.isUpdatable();
  39657. stopChecking = !updatable;
  39658. }
  39659. }
  39660. }
  39661. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39662. geometry.delayLoadState = this.delayLoadState;
  39663. geometry.delayLoadingFile = this.delayLoadingFile;
  39664. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39665. for (kind in this._delayInfo) {
  39666. geometry._delayInfo = geometry._delayInfo || [];
  39667. geometry._delayInfo.push(kind);
  39668. }
  39669. // Bounding info
  39670. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39671. return geometry;
  39672. };
  39673. /**
  39674. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39675. * @return a JSON representation of the current geometry data (without the vertices data)
  39676. */
  39677. Geometry.prototype.serialize = function () {
  39678. var serializationObject = {};
  39679. serializationObject.id = this.id;
  39680. serializationObject.updatable = this._updatable;
  39681. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39682. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39683. }
  39684. return serializationObject;
  39685. };
  39686. Geometry.prototype.toNumberArray = function (origin) {
  39687. if (Array.isArray(origin)) {
  39688. return origin;
  39689. }
  39690. else {
  39691. return Array.prototype.slice.call(origin);
  39692. }
  39693. };
  39694. /**
  39695. * Serialize all vertices data into a JSON oject
  39696. * @returns a JSON representation of the current geometry data
  39697. */
  39698. Geometry.prototype.serializeVerticeData = function () {
  39699. var serializationObject = this.serialize();
  39700. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39701. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39702. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39703. serializationObject.positions._updatable = true;
  39704. }
  39705. }
  39706. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39707. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39708. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39709. serializationObject.normals._updatable = true;
  39710. }
  39711. }
  39712. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39713. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39714. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39715. serializationObject.tangets._updatable = true;
  39716. }
  39717. }
  39718. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39719. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39720. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39721. serializationObject.uvs._updatable = true;
  39722. }
  39723. }
  39724. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39725. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39726. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39727. serializationObject.uv2s._updatable = true;
  39728. }
  39729. }
  39730. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39731. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39732. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39733. serializationObject.uv3s._updatable = true;
  39734. }
  39735. }
  39736. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39737. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39738. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39739. serializationObject.uv4s._updatable = true;
  39740. }
  39741. }
  39742. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39743. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39744. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39745. serializationObject.uv5s._updatable = true;
  39746. }
  39747. }
  39748. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39749. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39750. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39751. serializationObject.uv6s._updatable = true;
  39752. }
  39753. }
  39754. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39755. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39756. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39757. serializationObject.colors._updatable = true;
  39758. }
  39759. }
  39760. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39761. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39762. serializationObject.matricesIndices._isExpanded = true;
  39763. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39764. serializationObject.matricesIndices._updatable = true;
  39765. }
  39766. }
  39767. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39768. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39769. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39770. serializationObject.matricesWeights._updatable = true;
  39771. }
  39772. }
  39773. serializationObject.indices = this.toNumberArray(this.getIndices());
  39774. return serializationObject;
  39775. };
  39776. // Statics
  39777. /**
  39778. * Extracts a clone of a mesh geometry
  39779. * @param mesh defines the source mesh
  39780. * @param id defines the unique ID of the new geometry object
  39781. * @returns the new geometry object
  39782. */
  39783. Geometry.ExtractFromMesh = function (mesh, id) {
  39784. var geometry = mesh._geometry;
  39785. if (!geometry) {
  39786. return null;
  39787. }
  39788. return geometry.copy(id);
  39789. };
  39790. /**
  39791. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39792. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39793. * Be aware Math.random() could cause collisions, but:
  39794. * "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"
  39795. * @returns a string containing a new GUID
  39796. */
  39797. Geometry.RandomId = function () {
  39798. return BABYLON.Tools.RandomId();
  39799. };
  39800. /** @hidden */
  39801. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39802. var scene = mesh.getScene();
  39803. // Geometry
  39804. var geometryId = parsedGeometry.geometryId;
  39805. if (geometryId) {
  39806. var geometry = scene.getGeometryByID(geometryId);
  39807. if (geometry) {
  39808. geometry.applyToMesh(mesh);
  39809. }
  39810. }
  39811. else if (parsedGeometry instanceof ArrayBuffer) {
  39812. var binaryInfo = mesh._binaryInfo;
  39813. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39814. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39815. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39816. }
  39817. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39818. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39819. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39820. }
  39821. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39822. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39823. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39824. }
  39825. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39826. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39827. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39828. }
  39829. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39830. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39831. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39832. }
  39833. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39834. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39835. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39836. }
  39837. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39838. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39839. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39840. }
  39841. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39842. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39843. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39844. }
  39845. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39846. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39847. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39848. }
  39849. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39850. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39851. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39852. }
  39853. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39854. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39855. var floatIndices = [];
  39856. for (var i = 0; i < matricesIndicesData.length; i++) {
  39857. var index = matricesIndicesData[i];
  39858. floatIndices.push(index & 0x000000FF);
  39859. floatIndices.push((index & 0x0000FF00) >> 8);
  39860. floatIndices.push((index & 0x00FF0000) >> 16);
  39861. floatIndices.push(index >> 24);
  39862. }
  39863. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39864. }
  39865. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39866. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39867. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39868. }
  39869. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39870. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39871. mesh.setIndices(indicesData, null);
  39872. }
  39873. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39874. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39875. mesh.subMeshes = [];
  39876. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39877. var materialIndex = subMeshesData[(i * 5) + 0];
  39878. var verticesStart = subMeshesData[(i * 5) + 1];
  39879. var verticesCount = subMeshesData[(i * 5) + 2];
  39880. var indexStart = subMeshesData[(i * 5) + 3];
  39881. var indexCount = subMeshesData[(i * 5) + 4];
  39882. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39883. }
  39884. }
  39885. }
  39886. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39887. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39888. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39889. if (parsedGeometry.tangents) {
  39890. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39891. }
  39892. if (parsedGeometry.uvs) {
  39893. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39894. }
  39895. if (parsedGeometry.uvs2) {
  39896. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39897. }
  39898. if (parsedGeometry.uvs3) {
  39899. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39900. }
  39901. if (parsedGeometry.uvs4) {
  39902. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39903. }
  39904. if (parsedGeometry.uvs5) {
  39905. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39906. }
  39907. if (parsedGeometry.uvs6) {
  39908. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39909. }
  39910. if (parsedGeometry.colors) {
  39911. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39912. }
  39913. if (parsedGeometry.matricesIndices) {
  39914. if (!parsedGeometry.matricesIndices._isExpanded) {
  39915. var floatIndices = [];
  39916. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39917. var matricesIndex = parsedGeometry.matricesIndices[i];
  39918. floatIndices.push(matricesIndex & 0x000000FF);
  39919. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39920. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39921. floatIndices.push(matricesIndex >> 24);
  39922. }
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39924. }
  39925. else {
  39926. delete parsedGeometry.matricesIndices._isExpanded;
  39927. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39928. }
  39929. }
  39930. if (parsedGeometry.matricesIndicesExtra) {
  39931. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39932. var floatIndices = [];
  39933. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39934. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39935. floatIndices.push(matricesIndex & 0x000000FF);
  39936. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39937. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39938. floatIndices.push(matricesIndex >> 24);
  39939. }
  39940. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39941. }
  39942. else {
  39943. delete parsedGeometry.matricesIndices._isExpanded;
  39944. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39945. }
  39946. }
  39947. if (parsedGeometry.matricesWeights) {
  39948. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39949. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39950. }
  39951. if (parsedGeometry.matricesWeightsExtra) {
  39952. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39953. }
  39954. mesh.setIndices(parsedGeometry.indices, null);
  39955. }
  39956. // SubMeshes
  39957. if (parsedGeometry.subMeshes) {
  39958. mesh.subMeshes = [];
  39959. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39960. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39961. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39962. }
  39963. }
  39964. // Flat shading
  39965. if (mesh._shouldGenerateFlatShading) {
  39966. mesh.convertToFlatShadedMesh();
  39967. delete mesh._shouldGenerateFlatShading;
  39968. }
  39969. // Update
  39970. mesh.computeWorldMatrix(true);
  39971. // Octree
  39972. var sceneOctree = scene.selectionOctree;
  39973. if (sceneOctree !== undefined && sceneOctree !== null) {
  39974. sceneOctree.addMesh(mesh);
  39975. }
  39976. };
  39977. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39978. var epsilon = 1e-3;
  39979. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39980. return;
  39981. }
  39982. var noInfluenceBoneIndex = 0.0;
  39983. if (parsedGeometry.skeletonId > -1) {
  39984. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39985. if (!skeleton) {
  39986. return;
  39987. }
  39988. noInfluenceBoneIndex = skeleton.bones.length;
  39989. }
  39990. else {
  39991. return;
  39992. }
  39993. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39994. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39995. var matricesWeights = parsedGeometry.matricesWeights;
  39996. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39997. var influencers = parsedGeometry.numBoneInfluencer;
  39998. var size = matricesWeights.length;
  39999. for (var i = 0; i < size; i += 4) {
  40000. var weight = 0.0;
  40001. var firstZeroWeight = -1;
  40002. for (var j = 0; j < 4; j++) {
  40003. var w = matricesWeights[i + j];
  40004. weight += w;
  40005. if (w < epsilon && firstZeroWeight < 0) {
  40006. firstZeroWeight = j;
  40007. }
  40008. }
  40009. if (matricesWeightsExtra) {
  40010. for (var j = 0; j < 4; j++) {
  40011. var w = matricesWeightsExtra[i + j];
  40012. weight += w;
  40013. if (w < epsilon && firstZeroWeight < 0) {
  40014. firstZeroWeight = j + 4;
  40015. }
  40016. }
  40017. }
  40018. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40019. firstZeroWeight = influencers - 1;
  40020. }
  40021. if (weight > epsilon) {
  40022. var mweight = 1.0 / weight;
  40023. for (var j = 0; j < 4; j++) {
  40024. matricesWeights[i + j] *= mweight;
  40025. }
  40026. if (matricesWeightsExtra) {
  40027. for (var j = 0; j < 4; j++) {
  40028. matricesWeightsExtra[i + j] *= mweight;
  40029. }
  40030. }
  40031. }
  40032. else {
  40033. if (firstZeroWeight >= 4) {
  40034. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40035. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40036. }
  40037. else {
  40038. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40039. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40040. }
  40041. }
  40042. }
  40043. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40044. if (parsedGeometry.matricesWeightsExtra) {
  40045. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40046. }
  40047. };
  40048. /**
  40049. * Create a new geometry from persisted data (Using .babylon file format)
  40050. * @param parsedVertexData defines the persisted data
  40051. * @param scene defines the hosting scene
  40052. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40053. * @returns the new geometry object
  40054. */
  40055. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40056. if (scene.getGeometryByID(parsedVertexData.id)) {
  40057. return null; // null since geometry could be something else than a box...
  40058. }
  40059. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40060. if (BABYLON.Tags) {
  40061. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40062. }
  40063. if (parsedVertexData.delayLoadingFile) {
  40064. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40065. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40066. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40067. geometry._delayInfo = [];
  40068. if (parsedVertexData.hasUVs) {
  40069. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40070. }
  40071. if (parsedVertexData.hasUVs2) {
  40072. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40073. }
  40074. if (parsedVertexData.hasUVs3) {
  40075. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40076. }
  40077. if (parsedVertexData.hasUVs4) {
  40078. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40079. }
  40080. if (parsedVertexData.hasUVs5) {
  40081. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40082. }
  40083. if (parsedVertexData.hasUVs6) {
  40084. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40085. }
  40086. if (parsedVertexData.hasColors) {
  40087. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40088. }
  40089. if (parsedVertexData.hasMatricesIndices) {
  40090. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40091. }
  40092. if (parsedVertexData.hasMatricesWeights) {
  40093. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40094. }
  40095. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40096. }
  40097. else {
  40098. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40099. }
  40100. scene.pushGeometry(geometry, true);
  40101. return geometry;
  40102. };
  40103. return Geometry;
  40104. }());
  40105. BABYLON.Geometry = Geometry;
  40106. // Primitives
  40107. /// Abstract class
  40108. /**
  40109. * Abstract class used to provide common services for all typed geometries
  40110. * @hidden
  40111. */
  40112. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40113. __extends(_PrimitiveGeometry, _super);
  40114. /**
  40115. * Creates a new typed geometry
  40116. * @param id defines the unique ID of the geometry
  40117. * @param scene defines the hosting scene
  40118. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40119. * @param mesh defines the hosting mesh (can be null)
  40120. */
  40121. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40122. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40123. if (mesh === void 0) { mesh = null; }
  40124. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40125. _this._canBeRegenerated = _canBeRegenerated;
  40126. _this._beingRegenerated = true;
  40127. _this.regenerate();
  40128. _this._beingRegenerated = false;
  40129. return _this;
  40130. }
  40131. /**
  40132. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40133. * @returns true if the geometry can be regenerated
  40134. */
  40135. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40136. return this._canBeRegenerated;
  40137. };
  40138. /**
  40139. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40140. */
  40141. _PrimitiveGeometry.prototype.regenerate = function () {
  40142. if (!this._canBeRegenerated) {
  40143. return;
  40144. }
  40145. this._beingRegenerated = true;
  40146. this.setAllVerticesData(this._regenerateVertexData(), false);
  40147. this._beingRegenerated = false;
  40148. };
  40149. /**
  40150. * Clone the geometry
  40151. * @param id defines the unique ID of the new geometry
  40152. * @returns the new geometry
  40153. */
  40154. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40155. return _super.prototype.copy.call(this, id);
  40156. };
  40157. // overrides
  40158. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40159. if (!this._beingRegenerated) {
  40160. return;
  40161. }
  40162. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40163. };
  40164. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40165. if (!this._beingRegenerated) {
  40166. return;
  40167. }
  40168. _super.prototype.setVerticesData.call(this, kind, data, false);
  40169. };
  40170. // to override
  40171. /** @hidden */
  40172. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40173. throw new Error("Abstract method");
  40174. };
  40175. _PrimitiveGeometry.prototype.copy = function (id) {
  40176. throw new Error("Must be overriden in sub-classes.");
  40177. };
  40178. _PrimitiveGeometry.prototype.serialize = function () {
  40179. var serializationObject = _super.prototype.serialize.call(this);
  40180. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40181. return serializationObject;
  40182. };
  40183. return _PrimitiveGeometry;
  40184. }(Geometry));
  40185. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40186. /**
  40187. * Creates a ribbon geometry
  40188. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40189. */
  40190. var RibbonGeometry = /** @class */ (function (_super) {
  40191. __extends(RibbonGeometry, _super);
  40192. /**
  40193. * Creates a ribbon geometry
  40194. * @param id defines the unique ID of the geometry
  40195. * @param scene defines the hosting scene
  40196. * @param pathArray defines the array of paths to use
  40197. * @param closeArray defines if the last path and the first path must be joined
  40198. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40199. * @param offset defines the offset between points
  40200. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40201. * @param mesh defines the hosting mesh (can be null)
  40202. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40203. */
  40204. function RibbonGeometry(id, scene,
  40205. /**
  40206. * Defines the array of paths to use
  40207. */
  40208. pathArray,
  40209. /**
  40210. * Defines if the last and first points of each path in your pathArray must be joined
  40211. */
  40212. closeArray,
  40213. /**
  40214. * Defines if the last and first points of each path in your pathArray must be joined
  40215. */
  40216. closePath,
  40217. /**
  40218. * Defines the offset between points
  40219. */
  40220. offset, canBeRegenerated, mesh,
  40221. /**
  40222. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40223. */
  40224. side) {
  40225. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40226. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40227. _this.pathArray = pathArray;
  40228. _this.closeArray = closeArray;
  40229. _this.closePath = closePath;
  40230. _this.offset = offset;
  40231. _this.side = side;
  40232. return _this;
  40233. }
  40234. /** @hidden */
  40235. RibbonGeometry.prototype._regenerateVertexData = function () {
  40236. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40237. };
  40238. RibbonGeometry.prototype.copy = function (id) {
  40239. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40240. };
  40241. return RibbonGeometry;
  40242. }(_PrimitiveGeometry));
  40243. BABYLON.RibbonGeometry = RibbonGeometry;
  40244. /**
  40245. * Creates a box geometry
  40246. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40247. */
  40248. var BoxGeometry = /** @class */ (function (_super) {
  40249. __extends(BoxGeometry, _super);
  40250. /**
  40251. * Creates a box geometry
  40252. * @param id defines the unique ID of the geometry
  40253. * @param scene defines the hosting scene
  40254. * @param size defines the zise of the box (width, height and depth are the same)
  40255. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40256. * @param mesh defines the hosting mesh (can be null)
  40257. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40258. */
  40259. function BoxGeometry(id, scene,
  40260. /**
  40261. * Defines the zise of the box (width, height and depth are the same)
  40262. */
  40263. size, canBeRegenerated, mesh,
  40264. /**
  40265. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40266. */
  40267. side) {
  40268. if (mesh === void 0) { mesh = null; }
  40269. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40270. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40271. _this.size = size;
  40272. _this.side = side;
  40273. return _this;
  40274. }
  40275. BoxGeometry.prototype._regenerateVertexData = function () {
  40276. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40277. };
  40278. BoxGeometry.prototype.copy = function (id) {
  40279. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40280. };
  40281. BoxGeometry.prototype.serialize = function () {
  40282. var serializationObject = _super.prototype.serialize.call(this);
  40283. serializationObject.size = this.size;
  40284. return serializationObject;
  40285. };
  40286. BoxGeometry.Parse = function (parsedBox, scene) {
  40287. if (scene.getGeometryByID(parsedBox.id)) {
  40288. return null; // null since geometry could be something else than a box...
  40289. }
  40290. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40291. if (BABYLON.Tags) {
  40292. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40293. }
  40294. scene.pushGeometry(box, true);
  40295. return box;
  40296. };
  40297. return BoxGeometry;
  40298. }(_PrimitiveGeometry));
  40299. BABYLON.BoxGeometry = BoxGeometry;
  40300. /**
  40301. * Creates a sphere geometry
  40302. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40303. */
  40304. var SphereGeometry = /** @class */ (function (_super) {
  40305. __extends(SphereGeometry, _super);
  40306. /**
  40307. * Create a new sphere geometry
  40308. * @param id defines the unique ID of the geometry
  40309. * @param scene defines the hosting scene
  40310. * @param segments defines the number of segments to use to create the sphere
  40311. * @param diameter defines the diameter of the sphere
  40312. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40313. * @param mesh defines the hosting mesh (can be null)
  40314. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40315. */
  40316. function SphereGeometry(id, scene,
  40317. /**
  40318. * Defines the number of segments to use to create the sphere
  40319. */
  40320. segments,
  40321. /**
  40322. * Defines the diameter of the sphere
  40323. */
  40324. diameter, canBeRegenerated, mesh,
  40325. /**
  40326. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40327. */
  40328. side) {
  40329. if (mesh === void 0) { mesh = null; }
  40330. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40331. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40332. _this.segments = segments;
  40333. _this.diameter = diameter;
  40334. _this.side = side;
  40335. return _this;
  40336. }
  40337. SphereGeometry.prototype._regenerateVertexData = function () {
  40338. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40339. };
  40340. SphereGeometry.prototype.copy = function (id) {
  40341. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40342. };
  40343. SphereGeometry.prototype.serialize = function () {
  40344. var serializationObject = _super.prototype.serialize.call(this);
  40345. serializationObject.segments = this.segments;
  40346. serializationObject.diameter = this.diameter;
  40347. return serializationObject;
  40348. };
  40349. SphereGeometry.Parse = function (parsedSphere, scene) {
  40350. if (scene.getGeometryByID(parsedSphere.id)) {
  40351. return null; // null since geometry could be something else than a sphere...
  40352. }
  40353. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40354. if (BABYLON.Tags) {
  40355. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40356. }
  40357. scene.pushGeometry(sphere, true);
  40358. return sphere;
  40359. };
  40360. return SphereGeometry;
  40361. }(_PrimitiveGeometry));
  40362. BABYLON.SphereGeometry = SphereGeometry;
  40363. /**
  40364. * Creates a disc geometry
  40365. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40366. */
  40367. var DiscGeometry = /** @class */ (function (_super) {
  40368. __extends(DiscGeometry, _super);
  40369. /**
  40370. * Creates a new disc geometry
  40371. * @param id defines the unique ID of the geometry
  40372. * @param scene defines the hosting scene
  40373. * @param radius defines the radius of the disc
  40374. * @param tessellation defines the tesselation factor to apply to the disc
  40375. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40376. * @param mesh defines the hosting mesh (can be null)
  40377. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40378. */
  40379. function DiscGeometry(id, scene,
  40380. /**
  40381. * Defines the radius of the disc
  40382. */
  40383. radius,
  40384. /**
  40385. * Defines the tesselation factor to apply to the disc
  40386. */
  40387. tessellation, canBeRegenerated, mesh,
  40388. /**
  40389. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40390. */
  40391. side) {
  40392. if (mesh === void 0) { mesh = null; }
  40393. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40394. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40395. _this.radius = radius;
  40396. _this.tessellation = tessellation;
  40397. _this.side = side;
  40398. return _this;
  40399. }
  40400. DiscGeometry.prototype._regenerateVertexData = function () {
  40401. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40402. };
  40403. DiscGeometry.prototype.copy = function (id) {
  40404. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40405. };
  40406. return DiscGeometry;
  40407. }(_PrimitiveGeometry));
  40408. BABYLON.DiscGeometry = DiscGeometry;
  40409. /**
  40410. * Creates a new cylinder geometry
  40411. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40412. */
  40413. var CylinderGeometry = /** @class */ (function (_super) {
  40414. __extends(CylinderGeometry, _super);
  40415. /**
  40416. * Creates a new cylinder geometry
  40417. * @param id defines the unique ID of the geometry
  40418. * @param scene defines the hosting scene
  40419. * @param height defines the height of the cylinder
  40420. * @param diameterTop defines the diameter of the cylinder's top cap
  40421. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40422. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40423. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40424. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40425. * @param mesh defines the hosting mesh (can be null)
  40426. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40427. */
  40428. function CylinderGeometry(id, scene,
  40429. /**
  40430. * Defines the height of the cylinder
  40431. */
  40432. height,
  40433. /**
  40434. * Defines the diameter of the cylinder's top cap
  40435. */
  40436. diameterTop,
  40437. /**
  40438. * Defines the diameter of the cylinder's bottom cap
  40439. */
  40440. diameterBottom,
  40441. /**
  40442. * Defines the tessellation factor to apply to the cylinder
  40443. */
  40444. tessellation,
  40445. /**
  40446. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40447. */
  40448. subdivisions, canBeRegenerated, mesh,
  40449. /**
  40450. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40451. */
  40452. side) {
  40453. if (subdivisions === void 0) { subdivisions = 1; }
  40454. if (mesh === void 0) { mesh = null; }
  40455. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40456. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40457. _this.height = height;
  40458. _this.diameterTop = diameterTop;
  40459. _this.diameterBottom = diameterBottom;
  40460. _this.tessellation = tessellation;
  40461. _this.subdivisions = subdivisions;
  40462. _this.side = side;
  40463. return _this;
  40464. }
  40465. CylinderGeometry.prototype._regenerateVertexData = function () {
  40466. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40467. };
  40468. CylinderGeometry.prototype.copy = function (id) {
  40469. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40470. };
  40471. CylinderGeometry.prototype.serialize = function () {
  40472. var serializationObject = _super.prototype.serialize.call(this);
  40473. serializationObject.height = this.height;
  40474. serializationObject.diameterTop = this.diameterTop;
  40475. serializationObject.diameterBottom = this.diameterBottom;
  40476. serializationObject.tessellation = this.tessellation;
  40477. return serializationObject;
  40478. };
  40479. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40480. if (scene.getGeometryByID(parsedCylinder.id)) {
  40481. return null; // null since geometry could be something else than a cylinder...
  40482. }
  40483. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40484. if (BABYLON.Tags) {
  40485. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40486. }
  40487. scene.pushGeometry(cylinder, true);
  40488. return cylinder;
  40489. };
  40490. return CylinderGeometry;
  40491. }(_PrimitiveGeometry));
  40492. BABYLON.CylinderGeometry = CylinderGeometry;
  40493. /**
  40494. * Creates a new torus geometry
  40495. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40496. */
  40497. var TorusGeometry = /** @class */ (function (_super) {
  40498. __extends(TorusGeometry, _super);
  40499. /**
  40500. * Creates a new torus geometry
  40501. * @param id defines the unique ID of the geometry
  40502. * @param scene defines the hosting scene
  40503. * @param diameter defines the diameter of the torus
  40504. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40505. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40506. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40507. * @param mesh defines the hosting mesh (can be null)
  40508. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40509. */
  40510. function TorusGeometry(id, scene,
  40511. /**
  40512. * Defines the diameter of the torus
  40513. */
  40514. diameter,
  40515. /**
  40516. * Defines the thickness of the torus (ie. internal diameter)
  40517. */
  40518. thickness,
  40519. /**
  40520. * Defines the tesselation factor to apply to the torus
  40521. */
  40522. tessellation, canBeRegenerated, mesh,
  40523. /**
  40524. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40525. */
  40526. side) {
  40527. if (mesh === void 0) { mesh = null; }
  40528. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40529. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40530. _this.diameter = diameter;
  40531. _this.thickness = thickness;
  40532. _this.tessellation = tessellation;
  40533. _this.side = side;
  40534. return _this;
  40535. }
  40536. TorusGeometry.prototype._regenerateVertexData = function () {
  40537. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40538. };
  40539. TorusGeometry.prototype.copy = function (id) {
  40540. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40541. };
  40542. TorusGeometry.prototype.serialize = function () {
  40543. var serializationObject = _super.prototype.serialize.call(this);
  40544. serializationObject.diameter = this.diameter;
  40545. serializationObject.thickness = this.thickness;
  40546. serializationObject.tessellation = this.tessellation;
  40547. return serializationObject;
  40548. };
  40549. TorusGeometry.Parse = function (parsedTorus, scene) {
  40550. if (scene.getGeometryByID(parsedTorus.id)) {
  40551. return null; // null since geometry could be something else than a torus...
  40552. }
  40553. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40554. if (BABYLON.Tags) {
  40555. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40556. }
  40557. scene.pushGeometry(torus, true);
  40558. return torus;
  40559. };
  40560. return TorusGeometry;
  40561. }(_PrimitiveGeometry));
  40562. BABYLON.TorusGeometry = TorusGeometry;
  40563. /**
  40564. * Creates a new ground geometry
  40565. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40566. */
  40567. var GroundGeometry = /** @class */ (function (_super) {
  40568. __extends(GroundGeometry, _super);
  40569. /**
  40570. * Creates a new ground geometry
  40571. * @param id defines the unique ID of the geometry
  40572. * @param scene defines the hosting scene
  40573. * @param width defines the width of the ground
  40574. * @param height defines the height of the ground
  40575. * @param subdivisions defines the subdivisions to apply to the ground
  40576. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40577. * @param mesh defines the hosting mesh (can be null)
  40578. */
  40579. function GroundGeometry(id, scene,
  40580. /**
  40581. * Defines the width of the ground
  40582. */
  40583. width,
  40584. /**
  40585. * Defines the height of the ground
  40586. */
  40587. height,
  40588. /**
  40589. * Defines the subdivisions to apply to the ground
  40590. */
  40591. subdivisions, canBeRegenerated, mesh) {
  40592. if (mesh === void 0) { mesh = null; }
  40593. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40594. _this.width = width;
  40595. _this.height = height;
  40596. _this.subdivisions = subdivisions;
  40597. return _this;
  40598. }
  40599. GroundGeometry.prototype._regenerateVertexData = function () {
  40600. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40601. };
  40602. GroundGeometry.prototype.copy = function (id) {
  40603. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40604. };
  40605. GroundGeometry.prototype.serialize = function () {
  40606. var serializationObject = _super.prototype.serialize.call(this);
  40607. serializationObject.width = this.width;
  40608. serializationObject.height = this.height;
  40609. serializationObject.subdivisions = this.subdivisions;
  40610. return serializationObject;
  40611. };
  40612. GroundGeometry.Parse = function (parsedGround, scene) {
  40613. if (scene.getGeometryByID(parsedGround.id)) {
  40614. return null; // null since geometry could be something else than a ground...
  40615. }
  40616. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40617. if (BABYLON.Tags) {
  40618. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40619. }
  40620. scene.pushGeometry(ground, true);
  40621. return ground;
  40622. };
  40623. return GroundGeometry;
  40624. }(_PrimitiveGeometry));
  40625. BABYLON.GroundGeometry = GroundGeometry;
  40626. /**
  40627. * Creates a tiled ground geometry
  40628. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40629. */
  40630. var TiledGroundGeometry = /** @class */ (function (_super) {
  40631. __extends(TiledGroundGeometry, _super);
  40632. /**
  40633. * Creates a tiled ground geometry
  40634. * @param id defines the unique ID of the geometry
  40635. * @param scene defines the hosting scene
  40636. * @param xmin defines the minimum value on X axis
  40637. * @param zmin defines the minimum value on Z axis
  40638. * @param xmax defines the maximum value on X axis
  40639. * @param zmax defines the maximum value on Z axis
  40640. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40641. * @param precision defines the precision to use when computing the tiles
  40642. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40643. * @param mesh defines the hosting mesh (can be null)
  40644. */
  40645. function TiledGroundGeometry(id, scene,
  40646. /**
  40647. * Defines the minimum value on X axis
  40648. */
  40649. xmin,
  40650. /**
  40651. * Defines the minimum value on Z axis
  40652. */
  40653. zmin,
  40654. /**
  40655. * Defines the maximum value on X axis
  40656. */
  40657. xmax,
  40658. /**
  40659. * Defines the maximum value on Z axis
  40660. */
  40661. zmax,
  40662. /**
  40663. * Defines the subdivisions to apply to the ground
  40664. */
  40665. subdivisions,
  40666. /**
  40667. * Defines the precision to use when computing the tiles
  40668. */
  40669. precision, canBeRegenerated, mesh) {
  40670. if (mesh === void 0) { mesh = null; }
  40671. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40672. _this.xmin = xmin;
  40673. _this.zmin = zmin;
  40674. _this.xmax = xmax;
  40675. _this.zmax = zmax;
  40676. _this.subdivisions = subdivisions;
  40677. _this.precision = precision;
  40678. return _this;
  40679. }
  40680. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40681. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40682. };
  40683. TiledGroundGeometry.prototype.copy = function (id) {
  40684. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40685. };
  40686. return TiledGroundGeometry;
  40687. }(_PrimitiveGeometry));
  40688. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40689. /**
  40690. * Creates a plane geometry
  40691. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40692. */
  40693. var PlaneGeometry = /** @class */ (function (_super) {
  40694. __extends(PlaneGeometry, _super);
  40695. /**
  40696. * Creates a plane geometry
  40697. * @param id defines the unique ID of the geometry
  40698. * @param scene defines the hosting scene
  40699. * @param size defines the size of the plane (width === height)
  40700. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40701. * @param mesh defines the hosting mesh (can be null)
  40702. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40703. */
  40704. function PlaneGeometry(id, scene,
  40705. /**
  40706. * Defines the size of the plane (width === height)
  40707. */
  40708. size, canBeRegenerated, mesh,
  40709. /**
  40710. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40711. */
  40712. side) {
  40713. if (mesh === void 0) { mesh = null; }
  40714. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40715. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40716. _this.size = size;
  40717. _this.side = side;
  40718. return _this;
  40719. }
  40720. PlaneGeometry.prototype._regenerateVertexData = function () {
  40721. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40722. };
  40723. PlaneGeometry.prototype.copy = function (id) {
  40724. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40725. };
  40726. PlaneGeometry.prototype.serialize = function () {
  40727. var serializationObject = _super.prototype.serialize.call(this);
  40728. serializationObject.size = this.size;
  40729. return serializationObject;
  40730. };
  40731. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40732. if (scene.getGeometryByID(parsedPlane.id)) {
  40733. return null; // null since geometry could be something else than a ground...
  40734. }
  40735. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40736. if (BABYLON.Tags) {
  40737. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40738. }
  40739. scene.pushGeometry(plane, true);
  40740. return plane;
  40741. };
  40742. return PlaneGeometry;
  40743. }(_PrimitiveGeometry));
  40744. BABYLON.PlaneGeometry = PlaneGeometry;
  40745. /**
  40746. * Creates a torus knot geometry
  40747. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40748. */
  40749. var TorusKnotGeometry = /** @class */ (function (_super) {
  40750. __extends(TorusKnotGeometry, _super);
  40751. /**
  40752. * Creates a torus knot geometry
  40753. * @param id defines the unique ID of the geometry
  40754. * @param scene defines the hosting scene
  40755. * @param radius defines the radius of the torus knot
  40756. * @param tube defines the thickness of the torus knot tube
  40757. * @param radialSegments defines the number of radial segments
  40758. * @param tubularSegments defines the number of tubular segments
  40759. * @param p defines the first number of windings
  40760. * @param q defines the second number of windings
  40761. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40762. * @param mesh defines the hosting mesh (can be null)
  40763. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40764. */
  40765. function TorusKnotGeometry(id, scene,
  40766. /**
  40767. * Defines the radius of the torus knot
  40768. */
  40769. radius,
  40770. /**
  40771. * Defines the thickness of the torus knot tube
  40772. */
  40773. tube,
  40774. /**
  40775. * Defines the number of radial segments
  40776. */
  40777. radialSegments,
  40778. /**
  40779. * Defines the number of tubular segments
  40780. */
  40781. tubularSegments,
  40782. /**
  40783. * Defines the first number of windings
  40784. */
  40785. p,
  40786. /**
  40787. * Defines the second number of windings
  40788. */
  40789. q, canBeRegenerated, mesh,
  40790. /**
  40791. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40792. */
  40793. side) {
  40794. if (mesh === void 0) { mesh = null; }
  40795. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40796. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40797. _this.radius = radius;
  40798. _this.tube = tube;
  40799. _this.radialSegments = radialSegments;
  40800. _this.tubularSegments = tubularSegments;
  40801. _this.p = p;
  40802. _this.q = q;
  40803. _this.side = side;
  40804. return _this;
  40805. }
  40806. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40807. 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 });
  40808. };
  40809. TorusKnotGeometry.prototype.copy = function (id) {
  40810. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40811. };
  40812. TorusKnotGeometry.prototype.serialize = function () {
  40813. var serializationObject = _super.prototype.serialize.call(this);
  40814. serializationObject.radius = this.radius;
  40815. serializationObject.tube = this.tube;
  40816. serializationObject.radialSegments = this.radialSegments;
  40817. serializationObject.tubularSegments = this.tubularSegments;
  40818. serializationObject.p = this.p;
  40819. serializationObject.q = this.q;
  40820. return serializationObject;
  40821. };
  40822. ;
  40823. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40824. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40825. return null; // null since geometry could be something else than a ground...
  40826. }
  40827. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40828. if (BABYLON.Tags) {
  40829. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40830. }
  40831. scene.pushGeometry(torusKnot, true);
  40832. return torusKnot;
  40833. };
  40834. return TorusKnotGeometry;
  40835. }(_PrimitiveGeometry));
  40836. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40837. //}
  40838. })(BABYLON || (BABYLON = {}));
  40839. //# sourceMappingURL=babylon.geometry.js.map
  40840. var BABYLON;
  40841. (function (BABYLON) {
  40842. /**
  40843. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40844. */
  40845. var PerformanceMonitor = /** @class */ (function () {
  40846. /**
  40847. * constructor
  40848. * @param frameSampleSize The number of samples required to saturate the sliding window
  40849. */
  40850. function PerformanceMonitor(frameSampleSize) {
  40851. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40852. this._enabled = true;
  40853. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40854. }
  40855. /**
  40856. * Samples current frame
  40857. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40858. */
  40859. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40860. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40861. if (!this._enabled)
  40862. return;
  40863. if (this._lastFrameTimeMs != null) {
  40864. var dt = timeMs - this._lastFrameTimeMs;
  40865. this._rollingFrameTime.add(dt);
  40866. }
  40867. this._lastFrameTimeMs = timeMs;
  40868. };
  40869. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40870. /**
  40871. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40872. * @return Average frame time in milliseconds
  40873. */
  40874. get: function () {
  40875. return this._rollingFrameTime.average;
  40876. },
  40877. enumerable: true,
  40878. configurable: true
  40879. });
  40880. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40881. /**
  40882. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40883. * @return Frame time variance in milliseconds squared
  40884. */
  40885. get: function () {
  40886. return this._rollingFrameTime.variance;
  40887. },
  40888. enumerable: true,
  40889. configurable: true
  40890. });
  40891. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40892. /**
  40893. * Returns the frame time of the most recent frame
  40894. * @return Frame time in milliseconds
  40895. */
  40896. get: function () {
  40897. return this._rollingFrameTime.history(0);
  40898. },
  40899. enumerable: true,
  40900. configurable: true
  40901. });
  40902. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40903. /**
  40904. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40905. * @return Framerate in frames per second
  40906. */
  40907. get: function () {
  40908. return 1000.0 / this._rollingFrameTime.average;
  40909. },
  40910. enumerable: true,
  40911. configurable: true
  40912. });
  40913. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40914. /**
  40915. * Returns the average framerate in frames per second using the most recent frame time
  40916. * @return Framerate in frames per second
  40917. */
  40918. get: function () {
  40919. var history = this._rollingFrameTime.history(0);
  40920. if (history === 0) {
  40921. return 0;
  40922. }
  40923. return 1000.0 / history;
  40924. },
  40925. enumerable: true,
  40926. configurable: true
  40927. });
  40928. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40929. /**
  40930. * Returns true if enough samples have been taken to completely fill the sliding window
  40931. * @return true if saturated
  40932. */
  40933. get: function () {
  40934. return this._rollingFrameTime.isSaturated();
  40935. },
  40936. enumerable: true,
  40937. configurable: true
  40938. });
  40939. /**
  40940. * Enables contributions to the sliding window sample set
  40941. */
  40942. PerformanceMonitor.prototype.enable = function () {
  40943. this._enabled = true;
  40944. };
  40945. /**
  40946. * Disables contributions to the sliding window sample set
  40947. * Samples will not be interpolated over the disabled period
  40948. */
  40949. PerformanceMonitor.prototype.disable = function () {
  40950. this._enabled = false;
  40951. //clear last sample to avoid interpolating over the disabled period when next enabled
  40952. this._lastFrameTimeMs = null;
  40953. };
  40954. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40955. /**
  40956. * Returns true if sampling is enabled
  40957. * @return true if enabled
  40958. */
  40959. get: function () {
  40960. return this._enabled;
  40961. },
  40962. enumerable: true,
  40963. configurable: true
  40964. });
  40965. /**
  40966. * Resets performance monitor
  40967. */
  40968. PerformanceMonitor.prototype.reset = function () {
  40969. //clear last sample to avoid interpolating over the disabled period when next enabled
  40970. this._lastFrameTimeMs = null;
  40971. //wipe record
  40972. this._rollingFrameTime.reset();
  40973. };
  40974. return PerformanceMonitor;
  40975. }());
  40976. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40977. /**
  40978. * RollingAverage
  40979. *
  40980. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40981. */
  40982. var RollingAverage = /** @class */ (function () {
  40983. /**
  40984. * constructor
  40985. * @param length The number of samples required to saturate the sliding window
  40986. */
  40987. function RollingAverage(length) {
  40988. this._samples = new Array(length);
  40989. this.reset();
  40990. }
  40991. /**
  40992. * Adds a sample to the sample set
  40993. * @param v The sample value
  40994. */
  40995. RollingAverage.prototype.add = function (v) {
  40996. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40997. var delta;
  40998. //we need to check if we've already wrapped round
  40999. if (this.isSaturated()) {
  41000. //remove bottom of stack from mean
  41001. var bottomValue = this._samples[this._pos];
  41002. delta = bottomValue - this.average;
  41003. this.average -= delta / (this._sampleCount - 1);
  41004. this._m2 -= delta * (bottomValue - this.average);
  41005. }
  41006. else {
  41007. this._sampleCount++;
  41008. }
  41009. //add new value to mean
  41010. delta = v - this.average;
  41011. this.average += delta / (this._sampleCount);
  41012. this._m2 += delta * (v - this.average);
  41013. //set the new variance
  41014. this.variance = this._m2 / (this._sampleCount - 1);
  41015. this._samples[this._pos] = v;
  41016. this._pos++;
  41017. this._pos %= this._samples.length; //positive wrap around
  41018. };
  41019. /**
  41020. * Returns previously added values or null if outside of history or outside the sliding window domain
  41021. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41022. * @return Value previously recorded with add() or null if outside of range
  41023. */
  41024. RollingAverage.prototype.history = function (i) {
  41025. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41026. return 0;
  41027. }
  41028. var i0 = this._wrapPosition(this._pos - 1.0);
  41029. return this._samples[this._wrapPosition(i0 - i)];
  41030. };
  41031. /**
  41032. * Returns true if enough samples have been taken to completely fill the sliding window
  41033. * @return true if sample-set saturated
  41034. */
  41035. RollingAverage.prototype.isSaturated = function () {
  41036. return this._sampleCount >= this._samples.length;
  41037. };
  41038. /**
  41039. * Resets the rolling average (equivalent to 0 samples taken so far)
  41040. */
  41041. RollingAverage.prototype.reset = function () {
  41042. this.average = 0;
  41043. this.variance = 0;
  41044. this._sampleCount = 0;
  41045. this._pos = 0;
  41046. this._m2 = 0;
  41047. };
  41048. /**
  41049. * Wraps a value around the sample range boundaries
  41050. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41051. * @return Wrapped position in sample range
  41052. */
  41053. RollingAverage.prototype._wrapPosition = function (i) {
  41054. var max = this._samples.length;
  41055. return ((i % max) + max) % max;
  41056. };
  41057. return RollingAverage;
  41058. }());
  41059. BABYLON.RollingAverage = RollingAverage;
  41060. })(BABYLON || (BABYLON = {}));
  41061. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41062. var BABYLON;
  41063. (function (BABYLON) {
  41064. /**
  41065. * "Static Class" containing the most commonly used helper while dealing with material for
  41066. * rendering purpose.
  41067. *
  41068. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41069. *
  41070. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41071. */
  41072. var MaterialHelper = /** @class */ (function () {
  41073. function MaterialHelper() {
  41074. }
  41075. /**
  41076. * Bind the current view position to an effect.
  41077. * @param effect The effect to be bound
  41078. * @param scene The scene the eyes position is used from
  41079. */
  41080. MaterialHelper.BindEyePosition = function (effect, scene) {
  41081. if (scene._forcedViewPosition) {
  41082. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41083. return;
  41084. }
  41085. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41086. };
  41087. /**
  41088. * Helps preparing the defines values about the UVs in used in the effect.
  41089. * UVs are shared as much as we can accross chanels in the shaders.
  41090. * @param texture The texture we are preparing the UVs for
  41091. * @param defines The defines to update
  41092. * @param key The chanel key "diffuse", "specular"... used in the shader
  41093. */
  41094. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41095. defines._needUVs = true;
  41096. defines[key] = true;
  41097. if (texture.getTextureMatrix().isIdentity(true)) {
  41098. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41099. if (texture.coordinatesIndex === 0) {
  41100. defines["MAINUV1"] = true;
  41101. }
  41102. else {
  41103. defines["MAINUV2"] = true;
  41104. }
  41105. }
  41106. else {
  41107. defines[key + "DIRECTUV"] = 0;
  41108. }
  41109. };
  41110. /**
  41111. * Binds a texture matrix value to its corrsponding uniform
  41112. * @param texture The texture to bind the matrix for
  41113. * @param uniformBuffer The uniform buffer receivin the data
  41114. * @param key The chanel key "diffuse", "specular"... used in the shader
  41115. */
  41116. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41117. var matrix = texture.getTextureMatrix();
  41118. if (!matrix.isIdentity(true)) {
  41119. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41120. }
  41121. };
  41122. /**
  41123. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41124. * @param mesh defines the current mesh
  41125. * @param scene defines the current scene
  41126. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41127. * @param pointsCloud defines if point cloud rendering has to be turned on
  41128. * @param fogEnabled defines if fog has to be turned on
  41129. * @param alphaTest defines if alpha testing has to be turned on
  41130. * @param defines defines the current list of defines
  41131. */
  41132. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41133. if (defines._areMiscDirty) {
  41134. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41135. defines["POINTSIZE"] = pointsCloud;
  41136. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41137. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41138. defines["ALPHATEST"] = alphaTest;
  41139. }
  41140. };
  41141. /**
  41142. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41143. * @param scene defines the current scene
  41144. * @param engine defines the current engine
  41145. * @param defines specifies the list of active defines
  41146. * @param useInstances defines if instances have to be turned on
  41147. * @param useClipPlane defines if clip plane have to be turned on
  41148. */
  41149. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41150. if (useClipPlane === void 0) { useClipPlane = null; }
  41151. var changed = false;
  41152. if (useClipPlane == null) {
  41153. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41154. }
  41155. if (defines["CLIPPLANE"] !== useClipPlane) {
  41156. defines["CLIPPLANE"] = useClipPlane;
  41157. changed = true;
  41158. }
  41159. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41160. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41161. changed = true;
  41162. }
  41163. if (defines["INSTANCES"] !== useInstances) {
  41164. defines["INSTANCES"] = useInstances;
  41165. changed = true;
  41166. }
  41167. if (changed) {
  41168. defines.markAsUnprocessed();
  41169. }
  41170. };
  41171. /**
  41172. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41173. * @param mesh The mesh containing the geometry data we will draw
  41174. * @param defines The defines to update
  41175. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41176. * @param useBones Precise whether bones should be used or not (override mesh info)
  41177. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41178. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41179. * @returns false if defines are considered not dirty and have not been checked
  41180. */
  41181. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41182. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41183. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41184. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41185. return false;
  41186. }
  41187. defines._normals = defines._needNormals;
  41188. defines._uvs = defines._needUVs;
  41189. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41190. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41191. defines["TANGENT"] = true;
  41192. }
  41193. if (defines._needUVs) {
  41194. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41195. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41196. }
  41197. else {
  41198. defines["UV1"] = false;
  41199. defines["UV2"] = false;
  41200. }
  41201. if (useVertexColor) {
  41202. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41203. defines["VERTEXCOLOR"] = hasVertexColors;
  41204. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41205. }
  41206. if (useBones) {
  41207. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41208. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41209. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41210. }
  41211. else {
  41212. defines["NUM_BONE_INFLUENCERS"] = 0;
  41213. defines["BonesPerMesh"] = 0;
  41214. }
  41215. }
  41216. if (useMorphTargets) {
  41217. var manager = mesh.morphTargetManager;
  41218. if (manager) {
  41219. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41220. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41221. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41222. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41223. }
  41224. else {
  41225. defines["MORPHTARGETS_TANGENT"] = false;
  41226. defines["MORPHTARGETS_NORMAL"] = false;
  41227. defines["MORPHTARGETS"] = false;
  41228. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41229. }
  41230. }
  41231. return true;
  41232. };
  41233. /**
  41234. * Prepares the defines related to the light information passed in parameter
  41235. * @param scene The scene we are intending to draw
  41236. * @param mesh The mesh the effect is compiling for
  41237. * @param defines The defines to update
  41238. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41239. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41240. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41241. * @returns true if normals will be required for the rest of the effect
  41242. */
  41243. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41244. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41245. if (disableLighting === void 0) { disableLighting = false; }
  41246. if (!defines._areLightsDirty) {
  41247. return defines._needNormals;
  41248. }
  41249. var lightIndex = 0;
  41250. var needNormals = false;
  41251. var needRebuild = false;
  41252. var lightmapMode = false;
  41253. var shadowEnabled = false;
  41254. var specularEnabled = false;
  41255. if (scene.lightsEnabled && !disableLighting) {
  41256. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41257. var light = _a[_i];
  41258. needNormals = true;
  41259. if (defines["LIGHT" + lightIndex] === undefined) {
  41260. needRebuild = true;
  41261. }
  41262. defines["LIGHT" + lightIndex] = true;
  41263. defines["SPOTLIGHT" + lightIndex] = false;
  41264. defines["HEMILIGHT" + lightIndex] = false;
  41265. defines["POINTLIGHT" + lightIndex] = false;
  41266. defines["DIRLIGHT" + lightIndex] = false;
  41267. var type;
  41268. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41269. type = "SPOTLIGHT" + lightIndex;
  41270. var spotLight = light;
  41271. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41272. }
  41273. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41274. type = "HEMILIGHT" + lightIndex;
  41275. }
  41276. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41277. type = "POINTLIGHT" + lightIndex;
  41278. }
  41279. else {
  41280. type = "DIRLIGHT" + lightIndex;
  41281. }
  41282. defines[type] = true;
  41283. // Specular
  41284. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41285. specularEnabled = true;
  41286. }
  41287. // Shadows
  41288. defines["SHADOW" + lightIndex] = false;
  41289. defines["SHADOWPCF" + lightIndex] = false;
  41290. defines["SHADOWPCSS" + lightIndex] = false;
  41291. defines["SHADOWPOISSON" + lightIndex] = false;
  41292. defines["SHADOWESM" + lightIndex] = false;
  41293. defines["SHADOWCUBE" + lightIndex] = false;
  41294. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41295. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41296. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41297. var shadowGenerator = light.getShadowGenerator();
  41298. if (shadowGenerator) {
  41299. shadowEnabled = true;
  41300. shadowGenerator.prepareDefines(defines, lightIndex);
  41301. }
  41302. }
  41303. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41304. lightmapMode = true;
  41305. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41306. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41307. }
  41308. else {
  41309. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41310. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41311. }
  41312. lightIndex++;
  41313. if (lightIndex === maxSimultaneousLights)
  41314. break;
  41315. }
  41316. }
  41317. defines["SPECULARTERM"] = specularEnabled;
  41318. defines["SHADOWS"] = shadowEnabled;
  41319. // Resetting all other lights if any
  41320. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41321. if (defines["LIGHT" + index] !== undefined) {
  41322. defines["LIGHT" + index] = false;
  41323. defines["HEMILIGHT" + lightIndex] = false;
  41324. defines["POINTLIGHT" + lightIndex] = false;
  41325. defines["DIRLIGHT" + lightIndex] = false;
  41326. defines["SPOTLIGHT" + lightIndex] = false;
  41327. defines["SHADOW" + lightIndex] = false;
  41328. }
  41329. }
  41330. var caps = scene.getEngine().getCaps();
  41331. if (defines["SHADOWFLOAT"] === undefined) {
  41332. needRebuild = true;
  41333. }
  41334. defines["SHADOWFLOAT"] = shadowEnabled &&
  41335. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41336. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41337. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41338. if (needRebuild) {
  41339. defines.rebuild();
  41340. }
  41341. return needNormals;
  41342. };
  41343. /**
  41344. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41345. * that won t be acctive due to defines being turned off.
  41346. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41347. * @param samplersList The samplers list
  41348. * @param defines The defines helping in the list generation
  41349. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41350. */
  41351. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41352. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41353. var uniformsList;
  41354. var uniformBuffersList = null;
  41355. if (uniformsListOrOptions.uniformsNames) {
  41356. var options = uniformsListOrOptions;
  41357. uniformsList = options.uniformsNames;
  41358. uniformBuffersList = options.uniformBuffersNames;
  41359. samplersList = options.samplers;
  41360. defines = options.defines;
  41361. maxSimultaneousLights = options.maxSimultaneousLights;
  41362. }
  41363. else {
  41364. uniformsList = uniformsListOrOptions;
  41365. if (!samplersList) {
  41366. samplersList = [];
  41367. }
  41368. }
  41369. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41370. if (!defines["LIGHT" + lightIndex]) {
  41371. break;
  41372. }
  41373. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41374. if (uniformBuffersList) {
  41375. uniformBuffersList.push("Light" + lightIndex);
  41376. }
  41377. samplersList.push("shadowSampler" + lightIndex);
  41378. samplersList.push("depthSampler" + lightIndex);
  41379. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41380. samplersList.push("projectionLightSampler" + lightIndex);
  41381. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41382. }
  41383. }
  41384. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41385. uniformsList.push("morphTargetInfluences");
  41386. }
  41387. };
  41388. /**
  41389. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41390. * @param defines The defines to update while falling back
  41391. * @param fallbacks The authorized effect fallbacks
  41392. * @param maxSimultaneousLights The maximum number of lights allowed
  41393. * @param rank the current rank of the Effect
  41394. * @returns The newly affected rank
  41395. */
  41396. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41397. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41398. if (rank === void 0) { rank = 0; }
  41399. var lightFallbackRank = 0;
  41400. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41401. if (!defines["LIGHT" + lightIndex]) {
  41402. break;
  41403. }
  41404. if (lightIndex > 0) {
  41405. lightFallbackRank = rank + lightIndex;
  41406. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41407. }
  41408. if (!defines["SHADOWS"]) {
  41409. if (defines["SHADOW" + lightIndex]) {
  41410. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41411. }
  41412. if (defines["SHADOWPCF" + lightIndex]) {
  41413. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41414. }
  41415. if (defines["SHADOWPCSS" + lightIndex]) {
  41416. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41417. }
  41418. if (defines["SHADOWPOISSON" + lightIndex]) {
  41419. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41420. }
  41421. if (defines["SHADOWESM" + lightIndex]) {
  41422. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41423. }
  41424. }
  41425. }
  41426. return lightFallbackRank++;
  41427. };
  41428. /**
  41429. * Prepares the list of attributes required for morph targets according to the effect defines.
  41430. * @param attribs The current list of supported attribs
  41431. * @param mesh The mesh to prepare the morph targets attributes for
  41432. * @param defines The current Defines of the effect
  41433. */
  41434. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41435. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41436. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41437. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41438. var manager = mesh.morphTargetManager;
  41439. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41440. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41441. for (var index = 0; index < influencers; index++) {
  41442. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41443. if (normal) {
  41444. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41445. }
  41446. if (tangent) {
  41447. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41448. }
  41449. if (attribs.length > maxAttributesCount) {
  41450. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41451. }
  41452. }
  41453. }
  41454. };
  41455. /**
  41456. * Prepares the list of attributes required for bones according to the effect defines.
  41457. * @param attribs The current list of supported attribs
  41458. * @param mesh The mesh to prepare the bones attributes for
  41459. * @param defines The current Defines of the effect
  41460. * @param fallbacks The current efffect fallback strategy
  41461. */
  41462. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41463. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41464. fallbacks.addCPUSkinningFallback(0, mesh);
  41465. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41466. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41467. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41468. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41469. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41470. }
  41471. }
  41472. };
  41473. /**
  41474. * Prepares the list of attributes required for instances according to the effect defines.
  41475. * @param attribs The current list of supported attribs
  41476. * @param defines The current Defines of the effect
  41477. */
  41478. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41479. if (defines["INSTANCES"]) {
  41480. attribs.push("world0");
  41481. attribs.push("world1");
  41482. attribs.push("world2");
  41483. attribs.push("world3");
  41484. }
  41485. };
  41486. /**
  41487. * Binds the light shadow information to the effect for the given mesh.
  41488. * @param light The light containing the generator
  41489. * @param scene The scene the lights belongs to
  41490. * @param mesh The mesh we are binding the information to render
  41491. * @param lightIndex The light index in the effect used to render the mesh
  41492. * @param effect The effect we are binding the data to
  41493. */
  41494. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41495. if (light.shadowEnabled && mesh.receiveShadows) {
  41496. var shadowGenerator = light.getShadowGenerator();
  41497. if (shadowGenerator) {
  41498. shadowGenerator.bindShadowLight(lightIndex, effect);
  41499. }
  41500. }
  41501. };
  41502. /**
  41503. * Binds the light information to the effect.
  41504. * @param light The light containing the generator
  41505. * @param effect The effect we are binding the data to
  41506. * @param lightIndex The light index in the effect used to render
  41507. */
  41508. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41509. light.transferToEffect(effect, lightIndex + "");
  41510. };
  41511. /**
  41512. * Binds the lights information from the scene to the effect for the given mesh.
  41513. * @param scene The scene the lights belongs to
  41514. * @param mesh The mesh we are binding the information to render
  41515. * @param effect The effect we are binding the data to
  41516. * @param defines The generated defines for the effect
  41517. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41518. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41519. */
  41520. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41521. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41522. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41523. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41524. for (var i = 0; i < len; i++) {
  41525. var light = mesh._lightSources[i];
  41526. var iAsString = i.toString();
  41527. var scaledIntensity = light.getScaledIntensity();
  41528. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41529. MaterialHelper.BindLightProperties(light, effect, i);
  41530. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41531. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41532. if (defines["SPECULARTERM"]) {
  41533. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41534. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41535. }
  41536. // Shadows
  41537. if (scene.shadowsEnabled) {
  41538. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41539. }
  41540. light._uniformBuffer.update();
  41541. }
  41542. };
  41543. /**
  41544. * Binds the fog information from the scene to the effect for the given mesh.
  41545. * @param scene The scene the lights belongs to
  41546. * @param mesh The mesh we are binding the information to render
  41547. * @param effect The effect we are binding the data to
  41548. */
  41549. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41550. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41551. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41552. effect.setColor3("vFogColor", scene.fogColor);
  41553. }
  41554. };
  41555. /**
  41556. * Binds the bones information from the mesh to the effect.
  41557. * @param mesh The mesh we are binding the information to render
  41558. * @param effect The effect we are binding the data to
  41559. */
  41560. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41561. if (!effect || !mesh) {
  41562. return;
  41563. }
  41564. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41565. mesh.computeBonesUsingShaders = false;
  41566. }
  41567. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41568. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41569. if (matrices) {
  41570. effect.setMatrices("mBones", matrices);
  41571. }
  41572. }
  41573. };
  41574. /**
  41575. * Binds the morph targets information from the mesh to the effect.
  41576. * @param abstractMesh The mesh we are binding the information to render
  41577. * @param effect The effect we are binding the data to
  41578. */
  41579. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41580. var manager = abstractMesh.morphTargetManager;
  41581. if (!abstractMesh || !manager) {
  41582. return;
  41583. }
  41584. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41585. };
  41586. /**
  41587. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41588. * @param defines The generated defines used in the effect
  41589. * @param effect The effect we are binding the data to
  41590. * @param scene The scene we are willing to render with logarithmic scale for
  41591. */
  41592. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41593. if (defines["LOGARITHMICDEPTH"]) {
  41594. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41595. }
  41596. };
  41597. /**
  41598. * Binds the clip plane information from the scene to the effect.
  41599. * @param scene The scene the clip plane information are extracted from
  41600. * @param effect The effect we are binding the data to
  41601. */
  41602. MaterialHelper.BindClipPlane = function (effect, scene) {
  41603. if (scene.clipPlane) {
  41604. var clipPlane = scene.clipPlane;
  41605. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41606. }
  41607. };
  41608. return MaterialHelper;
  41609. }());
  41610. BABYLON.MaterialHelper = MaterialHelper;
  41611. })(BABYLON || (BABYLON = {}));
  41612. //# sourceMappingURL=babylon.materialHelper.js.map
  41613. var BABYLON;
  41614. (function (BABYLON) {
  41615. var PushMaterial = /** @class */ (function (_super) {
  41616. __extends(PushMaterial, _super);
  41617. function PushMaterial(name, scene) {
  41618. var _this = _super.call(this, name, scene) || this;
  41619. _this._normalMatrix = new BABYLON.Matrix();
  41620. _this.storeEffectOnSubMeshes = true;
  41621. return _this;
  41622. }
  41623. PushMaterial.prototype.getEffect = function () {
  41624. return this._activeEffect;
  41625. };
  41626. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41627. if (!mesh) {
  41628. return false;
  41629. }
  41630. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41631. return true;
  41632. }
  41633. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41634. };
  41635. /**
  41636. * Binds the given world matrix to the active effect
  41637. *
  41638. * @param world the matrix to bind
  41639. */
  41640. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41641. this._activeEffect.setMatrix("world", world);
  41642. };
  41643. /**
  41644. * Binds the given normal matrix to the active effect
  41645. *
  41646. * @param normalMatrix the matrix to bind
  41647. */
  41648. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41649. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41650. };
  41651. PushMaterial.prototype.bind = function (world, mesh) {
  41652. if (!mesh) {
  41653. return;
  41654. }
  41655. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41656. };
  41657. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41658. if (effect === void 0) { effect = null; }
  41659. _super.prototype._afterBind.call(this, mesh);
  41660. this.getScene()._cachedEffect = effect;
  41661. };
  41662. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41663. if (visibility === void 0) { visibility = 1; }
  41664. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41665. };
  41666. return PushMaterial;
  41667. }(BABYLON.Material));
  41668. BABYLON.PushMaterial = PushMaterial;
  41669. })(BABYLON || (BABYLON = {}));
  41670. //# sourceMappingURL=babylon.pushMaterial.js.map
  41671. var BABYLON;
  41672. (function (BABYLON) {
  41673. /** @hidden */
  41674. var StandardMaterialDefines = /** @class */ (function (_super) {
  41675. __extends(StandardMaterialDefines, _super);
  41676. function StandardMaterialDefines() {
  41677. var _this = _super.call(this) || this;
  41678. _this.MAINUV1 = false;
  41679. _this.MAINUV2 = false;
  41680. _this.DIFFUSE = false;
  41681. _this.DIFFUSEDIRECTUV = 0;
  41682. _this.AMBIENT = false;
  41683. _this.AMBIENTDIRECTUV = 0;
  41684. _this.OPACITY = false;
  41685. _this.OPACITYDIRECTUV = 0;
  41686. _this.OPACITYRGB = false;
  41687. _this.REFLECTION = false;
  41688. _this.EMISSIVE = false;
  41689. _this.EMISSIVEDIRECTUV = 0;
  41690. _this.SPECULAR = false;
  41691. _this.SPECULARDIRECTUV = 0;
  41692. _this.BUMP = false;
  41693. _this.BUMPDIRECTUV = 0;
  41694. _this.PARALLAX = false;
  41695. _this.PARALLAXOCCLUSION = false;
  41696. _this.SPECULAROVERALPHA = false;
  41697. _this.CLIPPLANE = false;
  41698. _this.ALPHATEST = false;
  41699. _this.DEPTHPREPASS = false;
  41700. _this.ALPHAFROMDIFFUSE = false;
  41701. _this.POINTSIZE = false;
  41702. _this.FOG = false;
  41703. _this.SPECULARTERM = false;
  41704. _this.DIFFUSEFRESNEL = false;
  41705. _this.OPACITYFRESNEL = false;
  41706. _this.REFLECTIONFRESNEL = false;
  41707. _this.REFRACTIONFRESNEL = false;
  41708. _this.EMISSIVEFRESNEL = false;
  41709. _this.FRESNEL = false;
  41710. _this.NORMAL = false;
  41711. _this.UV1 = false;
  41712. _this.UV2 = false;
  41713. _this.VERTEXCOLOR = false;
  41714. _this.VERTEXALPHA = false;
  41715. _this.NUM_BONE_INFLUENCERS = 0;
  41716. _this.BonesPerMesh = 0;
  41717. _this.INSTANCES = false;
  41718. _this.GLOSSINESS = false;
  41719. _this.ROUGHNESS = false;
  41720. _this.EMISSIVEASILLUMINATION = false;
  41721. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41722. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41723. _this.LIGHTMAP = false;
  41724. _this.LIGHTMAPDIRECTUV = 0;
  41725. _this.OBJECTSPACE_NORMALMAP = false;
  41726. _this.USELIGHTMAPASSHADOWMAP = false;
  41727. _this.REFLECTIONMAP_3D = false;
  41728. _this.REFLECTIONMAP_SPHERICAL = false;
  41729. _this.REFLECTIONMAP_PLANAR = false;
  41730. _this.REFLECTIONMAP_CUBIC = false;
  41731. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41732. _this.REFLECTIONMAP_PROJECTION = false;
  41733. _this.REFLECTIONMAP_SKYBOX = false;
  41734. _this.REFLECTIONMAP_EXPLICIT = false;
  41735. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41736. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41737. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41738. _this.INVERTCUBICMAP = false;
  41739. _this.LOGARITHMICDEPTH = false;
  41740. _this.REFRACTION = false;
  41741. _this.REFRACTIONMAP_3D = false;
  41742. _this.REFLECTIONOVERALPHA = false;
  41743. _this.TWOSIDEDLIGHTING = false;
  41744. _this.SHADOWFLOAT = false;
  41745. _this.MORPHTARGETS = false;
  41746. _this.MORPHTARGETS_NORMAL = false;
  41747. _this.MORPHTARGETS_TANGENT = false;
  41748. _this.NUM_MORPH_INFLUENCERS = 0;
  41749. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41750. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41751. _this.IMAGEPROCESSING = false;
  41752. _this.VIGNETTE = false;
  41753. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41754. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41755. _this.TONEMAPPING = false;
  41756. _this.CONTRAST = false;
  41757. _this.COLORCURVES = false;
  41758. _this.COLORGRADING = false;
  41759. _this.COLORGRADING3D = false;
  41760. _this.SAMPLER3DGREENDEPTH = false;
  41761. _this.SAMPLER3DBGRMAP = false;
  41762. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41763. /**
  41764. * If the reflection texture on this material is in linear color space
  41765. * @hidden
  41766. */
  41767. _this.IS_REFLECTION_LINEAR = false;
  41768. /**
  41769. * If the refraction texture on this material is in linear color space
  41770. * @hidden
  41771. */
  41772. _this.IS_REFRACTION_LINEAR = false;
  41773. _this.EXPOSURE = false;
  41774. _this.rebuild();
  41775. return _this;
  41776. }
  41777. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41778. var modes = [
  41779. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41780. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41781. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41782. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41783. ];
  41784. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41785. var mode = modes_1[_i];
  41786. this[mode] = (mode === modeToEnable);
  41787. }
  41788. };
  41789. return StandardMaterialDefines;
  41790. }(BABYLON.MaterialDefines));
  41791. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41792. var StandardMaterial = /** @class */ (function (_super) {
  41793. __extends(StandardMaterial, _super);
  41794. function StandardMaterial(name, scene) {
  41795. var _this = _super.call(this, name, scene) || this;
  41796. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41797. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41798. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41799. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41800. _this.specularPower = 64;
  41801. _this._useAlphaFromDiffuseTexture = false;
  41802. _this._useEmissiveAsIllumination = false;
  41803. _this._linkEmissiveWithDiffuse = false;
  41804. _this._useSpecularOverAlpha = false;
  41805. _this._useReflectionOverAlpha = false;
  41806. _this._disableLighting = false;
  41807. _this._useObjectSpaceNormalMap = false;
  41808. _this._useParallax = false;
  41809. _this._useParallaxOcclusion = false;
  41810. _this.parallaxScaleBias = 0.05;
  41811. _this._roughness = 0;
  41812. _this.indexOfRefraction = 0.98;
  41813. _this.invertRefractionY = true;
  41814. /**
  41815. * Defines the alpha limits in alpha test mode
  41816. */
  41817. _this.alphaCutOff = 0.4;
  41818. _this._useLightmapAsShadowmap = false;
  41819. _this._useReflectionFresnelFromSpecular = false;
  41820. _this._useGlossinessFromSpecularMapAlpha = false;
  41821. _this._maxSimultaneousLights = 4;
  41822. /**
  41823. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41824. */
  41825. _this._invertNormalMapX = false;
  41826. /**
  41827. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41828. */
  41829. _this._invertNormalMapY = false;
  41830. /**
  41831. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41832. */
  41833. _this._twoSidedLighting = false;
  41834. _this._renderTargets = new BABYLON.SmartArray(16);
  41835. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41836. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41837. // Setup the default processing configuration to the scene.
  41838. _this._attachImageProcessingConfiguration(null);
  41839. _this.getRenderTargetTextures = function () {
  41840. _this._renderTargets.reset();
  41841. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41842. _this._renderTargets.push(_this._reflectionTexture);
  41843. }
  41844. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41845. _this._renderTargets.push(_this._refractionTexture);
  41846. }
  41847. return _this._renderTargets;
  41848. };
  41849. return _this;
  41850. }
  41851. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41852. /**
  41853. * Gets the image processing configuration used either in this material.
  41854. */
  41855. get: function () {
  41856. return this._imageProcessingConfiguration;
  41857. },
  41858. /**
  41859. * Sets the Default image processing configuration used either in the this material.
  41860. *
  41861. * If sets to null, the scene one is in use.
  41862. */
  41863. set: function (value) {
  41864. this._attachImageProcessingConfiguration(value);
  41865. // Ensure the effect will be rebuilt.
  41866. this._markAllSubMeshesAsTexturesDirty();
  41867. },
  41868. enumerable: true,
  41869. configurable: true
  41870. });
  41871. /**
  41872. * Attaches a new image processing configuration to the Standard Material.
  41873. * @param configuration
  41874. */
  41875. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41876. var _this = this;
  41877. if (configuration === this._imageProcessingConfiguration) {
  41878. return;
  41879. }
  41880. // Detaches observer.
  41881. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41882. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41883. }
  41884. // Pick the scene configuration if needed.
  41885. if (!configuration) {
  41886. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41887. }
  41888. else {
  41889. this._imageProcessingConfiguration = configuration;
  41890. }
  41891. // Attaches observer.
  41892. if (this._imageProcessingConfiguration) {
  41893. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41894. _this._markAllSubMeshesAsImageProcessingDirty();
  41895. });
  41896. }
  41897. };
  41898. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41899. /**
  41900. * Gets wether the color curves effect is enabled.
  41901. */
  41902. get: function () {
  41903. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41904. },
  41905. /**
  41906. * Sets wether the color curves effect is enabled.
  41907. */
  41908. set: function (value) {
  41909. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41910. },
  41911. enumerable: true,
  41912. configurable: true
  41913. });
  41914. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41915. /**
  41916. * Gets wether the color grading effect is enabled.
  41917. */
  41918. get: function () {
  41919. return this.imageProcessingConfiguration.colorGradingEnabled;
  41920. },
  41921. /**
  41922. * Gets wether the color grading effect is enabled.
  41923. */
  41924. set: function (value) {
  41925. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41926. },
  41927. enumerable: true,
  41928. configurable: true
  41929. });
  41930. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41931. /**
  41932. * Gets wether tonemapping is enabled or not.
  41933. */
  41934. get: function () {
  41935. return this._imageProcessingConfiguration.toneMappingEnabled;
  41936. },
  41937. /**
  41938. * Sets wether tonemapping is enabled or not
  41939. */
  41940. set: function (value) {
  41941. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41942. },
  41943. enumerable: true,
  41944. configurable: true
  41945. });
  41946. ;
  41947. ;
  41948. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41949. /**
  41950. * The camera exposure used on this material.
  41951. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41952. * This corresponds to a photographic exposure.
  41953. */
  41954. get: function () {
  41955. return this._imageProcessingConfiguration.exposure;
  41956. },
  41957. /**
  41958. * The camera exposure used on this material.
  41959. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41960. * This corresponds to a photographic exposure.
  41961. */
  41962. set: function (value) {
  41963. this._imageProcessingConfiguration.exposure = value;
  41964. },
  41965. enumerable: true,
  41966. configurable: true
  41967. });
  41968. ;
  41969. ;
  41970. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41971. /**
  41972. * Gets The camera contrast used on this material.
  41973. */
  41974. get: function () {
  41975. return this._imageProcessingConfiguration.contrast;
  41976. },
  41977. /**
  41978. * Sets The camera contrast used on this material.
  41979. */
  41980. set: function (value) {
  41981. this._imageProcessingConfiguration.contrast = value;
  41982. },
  41983. enumerable: true,
  41984. configurable: true
  41985. });
  41986. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41987. /**
  41988. * Gets the Color Grading 2D Lookup Texture.
  41989. */
  41990. get: function () {
  41991. return this._imageProcessingConfiguration.colorGradingTexture;
  41992. },
  41993. /**
  41994. * Sets the Color Grading 2D Lookup Texture.
  41995. */
  41996. set: function (value) {
  41997. this._imageProcessingConfiguration.colorGradingTexture = value;
  41998. },
  41999. enumerable: true,
  42000. configurable: true
  42001. });
  42002. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42003. /**
  42004. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42005. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42006. * 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;
  42007. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42008. */
  42009. get: function () {
  42010. return this._imageProcessingConfiguration.colorCurves;
  42011. },
  42012. /**
  42013. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42014. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42015. * 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;
  42016. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42017. */
  42018. set: function (value) {
  42019. this._imageProcessingConfiguration.colorCurves = value;
  42020. },
  42021. enumerable: true,
  42022. configurable: true
  42023. });
  42024. StandardMaterial.prototype.getClassName = function () {
  42025. return "StandardMaterial";
  42026. };
  42027. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42028. get: function () {
  42029. return this._useLogarithmicDepth;
  42030. },
  42031. set: function (value) {
  42032. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42033. this._markAllSubMeshesAsMiscDirty();
  42034. },
  42035. enumerable: true,
  42036. configurable: true
  42037. });
  42038. StandardMaterial.prototype.needAlphaBlending = function () {
  42039. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42040. };
  42041. StandardMaterial.prototype.needAlphaTesting = function () {
  42042. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42043. };
  42044. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42045. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42046. };
  42047. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42048. return this._diffuseTexture;
  42049. };
  42050. /**
  42051. * Child classes can use it to update shaders
  42052. */
  42053. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42054. if (useInstances === void 0) { useInstances = false; }
  42055. if (subMesh.effect && this.isFrozen) {
  42056. if (this._wasPreviouslyReady && subMesh.effect) {
  42057. return true;
  42058. }
  42059. }
  42060. if (!subMesh._materialDefines) {
  42061. subMesh._materialDefines = new StandardMaterialDefines();
  42062. }
  42063. var scene = this.getScene();
  42064. var defines = subMesh._materialDefines;
  42065. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42066. if (defines._renderId === scene.getRenderId()) {
  42067. return true;
  42068. }
  42069. }
  42070. var engine = scene.getEngine();
  42071. // Lights
  42072. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42073. // Textures
  42074. if (defines._areTexturesDirty) {
  42075. defines._needUVs = false;
  42076. defines.MAINUV1 = false;
  42077. defines.MAINUV2 = false;
  42078. if (scene.texturesEnabled) {
  42079. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42080. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42081. return false;
  42082. }
  42083. else {
  42084. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42085. }
  42086. }
  42087. else {
  42088. defines.DIFFUSE = false;
  42089. }
  42090. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42091. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42092. return false;
  42093. }
  42094. else {
  42095. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42096. }
  42097. }
  42098. else {
  42099. defines.AMBIENT = false;
  42100. }
  42101. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42102. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42103. return false;
  42104. }
  42105. else {
  42106. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42107. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42108. }
  42109. }
  42110. else {
  42111. defines.OPACITY = false;
  42112. }
  42113. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42114. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42115. return false;
  42116. }
  42117. else {
  42118. defines._needNormals = true;
  42119. defines.REFLECTION = true;
  42120. defines.ROUGHNESS = (this._roughness > 0);
  42121. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42122. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42123. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42124. switch (this._reflectionTexture.coordinatesMode) {
  42125. case BABYLON.Texture.EXPLICIT_MODE:
  42126. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42127. break;
  42128. case BABYLON.Texture.PLANAR_MODE:
  42129. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42130. break;
  42131. case BABYLON.Texture.PROJECTION_MODE:
  42132. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42133. break;
  42134. case BABYLON.Texture.SKYBOX_MODE:
  42135. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42136. break;
  42137. case BABYLON.Texture.SPHERICAL_MODE:
  42138. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42139. break;
  42140. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42141. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42142. break;
  42143. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42144. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42145. break;
  42146. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42147. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42148. break;
  42149. case BABYLON.Texture.CUBIC_MODE:
  42150. case BABYLON.Texture.INVCUBIC_MODE:
  42151. default:
  42152. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42153. break;
  42154. }
  42155. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42156. }
  42157. }
  42158. else {
  42159. defines.REFLECTION = false;
  42160. }
  42161. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42162. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42163. return false;
  42164. }
  42165. else {
  42166. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42167. }
  42168. }
  42169. else {
  42170. defines.EMISSIVE = false;
  42171. }
  42172. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42173. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42174. return false;
  42175. }
  42176. else {
  42177. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42178. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42179. }
  42180. }
  42181. else {
  42182. defines.LIGHTMAP = false;
  42183. }
  42184. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42185. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42186. return false;
  42187. }
  42188. else {
  42189. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42190. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42191. }
  42192. }
  42193. else {
  42194. defines.SPECULAR = false;
  42195. }
  42196. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42197. // Bump texure can not be not blocking.
  42198. if (!this._bumpTexture.isReady()) {
  42199. return false;
  42200. }
  42201. else {
  42202. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42203. defines.PARALLAX = this._useParallax;
  42204. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42205. }
  42206. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42207. }
  42208. else {
  42209. defines.BUMP = false;
  42210. }
  42211. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42212. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42213. return false;
  42214. }
  42215. else {
  42216. defines._needUVs = true;
  42217. defines.REFRACTION = true;
  42218. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42219. }
  42220. }
  42221. else {
  42222. defines.REFRACTION = false;
  42223. }
  42224. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42225. }
  42226. else {
  42227. defines.DIFFUSE = false;
  42228. defines.AMBIENT = false;
  42229. defines.OPACITY = false;
  42230. defines.REFLECTION = false;
  42231. defines.EMISSIVE = false;
  42232. defines.LIGHTMAP = false;
  42233. defines.BUMP = false;
  42234. defines.REFRACTION = false;
  42235. }
  42236. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42237. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42238. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42239. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42240. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42241. }
  42242. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42243. if (!this._imageProcessingConfiguration.isReady()) {
  42244. return false;
  42245. }
  42246. this._imageProcessingConfiguration.prepareDefines(defines);
  42247. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42248. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42249. }
  42250. if (defines._areFresnelDirty) {
  42251. if (StandardMaterial.FresnelEnabled) {
  42252. // Fresnel
  42253. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42254. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42255. this._reflectionFresnelParameters) {
  42256. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42257. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42258. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42259. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42260. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42261. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42262. defines._needNormals = true;
  42263. defines.FRESNEL = true;
  42264. }
  42265. }
  42266. else {
  42267. defines.FRESNEL = false;
  42268. }
  42269. }
  42270. // Misc.
  42271. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42272. // Attribs
  42273. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42274. // Values that need to be evaluated on every frame
  42275. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42276. // Get correct effect
  42277. if (defines.isDirty) {
  42278. defines.markAsProcessed();
  42279. scene.resetCachedMaterial();
  42280. // Fallbacks
  42281. var fallbacks = new BABYLON.EffectFallbacks();
  42282. if (defines.REFLECTION) {
  42283. fallbacks.addFallback(0, "REFLECTION");
  42284. }
  42285. if (defines.SPECULAR) {
  42286. fallbacks.addFallback(0, "SPECULAR");
  42287. }
  42288. if (defines.BUMP) {
  42289. fallbacks.addFallback(0, "BUMP");
  42290. }
  42291. if (defines.PARALLAX) {
  42292. fallbacks.addFallback(1, "PARALLAX");
  42293. }
  42294. if (defines.PARALLAXOCCLUSION) {
  42295. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42296. }
  42297. if (defines.SPECULAROVERALPHA) {
  42298. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42299. }
  42300. if (defines.FOG) {
  42301. fallbacks.addFallback(1, "FOG");
  42302. }
  42303. if (defines.POINTSIZE) {
  42304. fallbacks.addFallback(0, "POINTSIZE");
  42305. }
  42306. if (defines.LOGARITHMICDEPTH) {
  42307. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42308. }
  42309. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42310. if (defines.SPECULARTERM) {
  42311. fallbacks.addFallback(0, "SPECULARTERM");
  42312. }
  42313. if (defines.DIFFUSEFRESNEL) {
  42314. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42315. }
  42316. if (defines.OPACITYFRESNEL) {
  42317. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42318. }
  42319. if (defines.REFLECTIONFRESNEL) {
  42320. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42321. }
  42322. if (defines.EMISSIVEFRESNEL) {
  42323. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42324. }
  42325. if (defines.FRESNEL) {
  42326. fallbacks.addFallback(4, "FRESNEL");
  42327. }
  42328. //Attributes
  42329. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42330. if (defines.NORMAL) {
  42331. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42332. }
  42333. if (defines.UV1) {
  42334. attribs.push(BABYLON.VertexBuffer.UVKind);
  42335. }
  42336. if (defines.UV2) {
  42337. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42338. }
  42339. if (defines.VERTEXCOLOR) {
  42340. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42341. }
  42342. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42343. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42344. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42345. var shaderName = "default";
  42346. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42347. "vFogInfos", "vFogColor", "pointSize",
  42348. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42349. "mBones",
  42350. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42351. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42352. "vReflectionPosition", "vReflectionSize",
  42353. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42354. ];
  42355. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42356. var uniformBuffers = ["Material", "Scene"];
  42357. if (BABYLON.ImageProcessingConfiguration) {
  42358. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42359. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42360. }
  42361. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42362. uniformsNames: uniforms,
  42363. uniformBuffersNames: uniformBuffers,
  42364. samplers: samplers,
  42365. defines: defines,
  42366. maxSimultaneousLights: this._maxSimultaneousLights
  42367. });
  42368. if (this.customShaderNameResolve) {
  42369. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42370. }
  42371. var join = defines.toString();
  42372. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42373. attributes: attribs,
  42374. uniformsNames: uniforms,
  42375. uniformBuffersNames: uniformBuffers,
  42376. samplers: samplers,
  42377. defines: join,
  42378. fallbacks: fallbacks,
  42379. onCompiled: this.onCompiled,
  42380. onError: this.onError,
  42381. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42382. }, engine), defines);
  42383. this.buildUniformLayout();
  42384. }
  42385. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42386. return false;
  42387. }
  42388. defines._renderId = scene.getRenderId();
  42389. this._wasPreviouslyReady = true;
  42390. return true;
  42391. };
  42392. StandardMaterial.prototype.buildUniformLayout = function () {
  42393. // Order is important !
  42394. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42395. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42396. this._uniformBuffer.addUniform("opacityParts", 4);
  42397. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42398. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42399. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42400. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42401. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42402. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42403. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42404. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42405. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42406. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42407. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42408. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42409. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42410. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42411. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42412. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42413. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42414. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42415. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42416. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42417. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42418. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42419. this._uniformBuffer.addUniform("specularMatrix", 16);
  42420. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42421. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42422. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42423. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42424. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42425. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42426. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42427. this._uniformBuffer.addUniform("pointSize", 1);
  42428. this._uniformBuffer.create();
  42429. };
  42430. StandardMaterial.prototype.unbind = function () {
  42431. if (this._activeEffect) {
  42432. var needFlag = false;
  42433. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42434. this._activeEffect.setTexture("reflection2DSampler", null);
  42435. needFlag = true;
  42436. }
  42437. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42438. this._activeEffect.setTexture("refraction2DSampler", null);
  42439. needFlag = true;
  42440. }
  42441. if (needFlag) {
  42442. this._markAllSubMeshesAsTexturesDirty();
  42443. }
  42444. }
  42445. _super.prototype.unbind.call(this);
  42446. };
  42447. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42448. var scene = this.getScene();
  42449. var defines = subMesh._materialDefines;
  42450. if (!defines) {
  42451. return;
  42452. }
  42453. var effect = subMesh.effect;
  42454. if (!effect) {
  42455. return;
  42456. }
  42457. this._activeEffect = effect;
  42458. // Matrices
  42459. this.bindOnlyWorldMatrix(world);
  42460. // Normal Matrix
  42461. if (defines.OBJECTSPACE_NORMALMAP) {
  42462. world.toNormalMatrix(this._normalMatrix);
  42463. this.bindOnlyNormalMatrix(this._normalMatrix);
  42464. }
  42465. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42466. // Bones
  42467. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42468. if (mustRebind) {
  42469. this._uniformBuffer.bindToEffect(effect, "Material");
  42470. this.bindViewProjection(effect);
  42471. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42472. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42473. // Fresnel
  42474. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42475. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42476. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42477. }
  42478. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42479. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42480. }
  42481. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42482. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42483. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42484. }
  42485. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42486. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42487. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42488. }
  42489. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42490. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42491. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42492. }
  42493. }
  42494. // Textures
  42495. if (scene.texturesEnabled) {
  42496. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42497. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42498. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42499. if (this._diffuseTexture.hasAlpha) {
  42500. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42501. }
  42502. }
  42503. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42504. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42505. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42506. }
  42507. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42508. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42509. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42510. }
  42511. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42512. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42513. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42514. if (this._reflectionTexture.boundingBoxSize) {
  42515. var cubeTexture = this._reflectionTexture;
  42516. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42517. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42518. }
  42519. }
  42520. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42521. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42522. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42523. }
  42524. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42525. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42526. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42527. }
  42528. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42529. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42530. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42531. }
  42532. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42533. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42534. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42535. if (scene._mirroredCameraPosition) {
  42536. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42537. }
  42538. else {
  42539. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42540. }
  42541. }
  42542. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42543. var depth = 1.0;
  42544. if (!this._refractionTexture.isCube) {
  42545. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42546. if (this._refractionTexture.depth) {
  42547. depth = this._refractionTexture.depth;
  42548. }
  42549. }
  42550. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42551. }
  42552. }
  42553. // Point size
  42554. if (this.pointsCloud) {
  42555. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42556. }
  42557. if (defines.SPECULARTERM) {
  42558. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42559. }
  42560. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42561. // Diffuse
  42562. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42563. }
  42564. // Textures
  42565. if (scene.texturesEnabled) {
  42566. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42567. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42568. }
  42569. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42570. effect.setTexture("ambientSampler", this._ambientTexture);
  42571. }
  42572. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42573. effect.setTexture("opacitySampler", this._opacityTexture);
  42574. }
  42575. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42576. if (this._reflectionTexture.isCube) {
  42577. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42578. }
  42579. else {
  42580. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42581. }
  42582. }
  42583. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42584. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42585. }
  42586. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42587. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42588. }
  42589. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42590. effect.setTexture("specularSampler", this._specularTexture);
  42591. }
  42592. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42593. effect.setTexture("bumpSampler", this._bumpTexture);
  42594. }
  42595. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42596. var depth = 1.0;
  42597. if (this._refractionTexture.isCube) {
  42598. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42599. }
  42600. else {
  42601. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42602. }
  42603. }
  42604. }
  42605. // Clip plane
  42606. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42607. // Colors
  42608. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42609. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42610. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42611. }
  42612. if (mustRebind || !this.isFrozen) {
  42613. // Lights
  42614. if (scene.lightsEnabled && !this._disableLighting) {
  42615. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42616. }
  42617. // View
  42618. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42619. this.bindView(effect);
  42620. }
  42621. // Fog
  42622. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42623. // Morph targets
  42624. if (defines.NUM_MORPH_INFLUENCERS) {
  42625. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42626. }
  42627. // Log. depth
  42628. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42629. // image processing
  42630. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42631. this._imageProcessingConfiguration.bind(this._activeEffect);
  42632. }
  42633. }
  42634. this._uniformBuffer.update();
  42635. this._afterBind(mesh, this._activeEffect);
  42636. };
  42637. StandardMaterial.prototype.getAnimatables = function () {
  42638. var results = [];
  42639. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42640. results.push(this._diffuseTexture);
  42641. }
  42642. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42643. results.push(this._ambientTexture);
  42644. }
  42645. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42646. results.push(this._opacityTexture);
  42647. }
  42648. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42649. results.push(this._reflectionTexture);
  42650. }
  42651. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42652. results.push(this._emissiveTexture);
  42653. }
  42654. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42655. results.push(this._specularTexture);
  42656. }
  42657. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42658. results.push(this._bumpTexture);
  42659. }
  42660. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42661. results.push(this._lightmapTexture);
  42662. }
  42663. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42664. results.push(this._refractionTexture);
  42665. }
  42666. return results;
  42667. };
  42668. StandardMaterial.prototype.getActiveTextures = function () {
  42669. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42670. if (this._diffuseTexture) {
  42671. activeTextures.push(this._diffuseTexture);
  42672. }
  42673. if (this._ambientTexture) {
  42674. activeTextures.push(this._ambientTexture);
  42675. }
  42676. if (this._opacityTexture) {
  42677. activeTextures.push(this._opacityTexture);
  42678. }
  42679. if (this._reflectionTexture) {
  42680. activeTextures.push(this._reflectionTexture);
  42681. }
  42682. if (this._emissiveTexture) {
  42683. activeTextures.push(this._emissiveTexture);
  42684. }
  42685. if (this._specularTexture) {
  42686. activeTextures.push(this._specularTexture);
  42687. }
  42688. if (this._bumpTexture) {
  42689. activeTextures.push(this._bumpTexture);
  42690. }
  42691. if (this._lightmapTexture) {
  42692. activeTextures.push(this._lightmapTexture);
  42693. }
  42694. if (this._refractionTexture) {
  42695. activeTextures.push(this._refractionTexture);
  42696. }
  42697. return activeTextures;
  42698. };
  42699. StandardMaterial.prototype.hasTexture = function (texture) {
  42700. if (_super.prototype.hasTexture.call(this, texture)) {
  42701. return true;
  42702. }
  42703. if (this._diffuseTexture === texture) {
  42704. return true;
  42705. }
  42706. if (this._ambientTexture === texture) {
  42707. return true;
  42708. }
  42709. if (this._opacityTexture === texture) {
  42710. return true;
  42711. }
  42712. if (this._reflectionTexture === texture) {
  42713. return true;
  42714. }
  42715. if (this._emissiveTexture === texture) {
  42716. return true;
  42717. }
  42718. if (this._specularTexture === texture) {
  42719. return true;
  42720. }
  42721. if (this._bumpTexture === texture) {
  42722. return true;
  42723. }
  42724. if (this._lightmapTexture === texture) {
  42725. return true;
  42726. }
  42727. if (this._refractionTexture === texture) {
  42728. return true;
  42729. }
  42730. return false;
  42731. };
  42732. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42733. if (forceDisposeTextures) {
  42734. if (this._diffuseTexture) {
  42735. this._diffuseTexture.dispose();
  42736. }
  42737. if (this._ambientTexture) {
  42738. this._ambientTexture.dispose();
  42739. }
  42740. if (this._opacityTexture) {
  42741. this._opacityTexture.dispose();
  42742. }
  42743. if (this._reflectionTexture) {
  42744. this._reflectionTexture.dispose();
  42745. }
  42746. if (this._emissiveTexture) {
  42747. this._emissiveTexture.dispose();
  42748. }
  42749. if (this._specularTexture) {
  42750. this._specularTexture.dispose();
  42751. }
  42752. if (this._bumpTexture) {
  42753. this._bumpTexture.dispose();
  42754. }
  42755. if (this._lightmapTexture) {
  42756. this._lightmapTexture.dispose();
  42757. }
  42758. if (this._refractionTexture) {
  42759. this._refractionTexture.dispose();
  42760. }
  42761. }
  42762. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42763. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42764. }
  42765. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42766. };
  42767. StandardMaterial.prototype.clone = function (name) {
  42768. var _this = this;
  42769. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42770. result.name = name;
  42771. result.id = name;
  42772. return result;
  42773. };
  42774. StandardMaterial.prototype.serialize = function () {
  42775. return BABYLON.SerializationHelper.Serialize(this);
  42776. };
  42777. // Statics
  42778. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42779. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42780. };
  42781. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42782. get: function () {
  42783. return StandardMaterial._DiffuseTextureEnabled;
  42784. },
  42785. set: function (value) {
  42786. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42787. return;
  42788. }
  42789. StandardMaterial._DiffuseTextureEnabled = value;
  42790. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42791. },
  42792. enumerable: true,
  42793. configurable: true
  42794. });
  42795. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42796. get: function () {
  42797. return StandardMaterial._AmbientTextureEnabled;
  42798. },
  42799. set: function (value) {
  42800. if (StandardMaterial._AmbientTextureEnabled === value) {
  42801. return;
  42802. }
  42803. StandardMaterial._AmbientTextureEnabled = value;
  42804. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42805. },
  42806. enumerable: true,
  42807. configurable: true
  42808. });
  42809. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42810. get: function () {
  42811. return StandardMaterial._OpacityTextureEnabled;
  42812. },
  42813. set: function (value) {
  42814. if (StandardMaterial._OpacityTextureEnabled === value) {
  42815. return;
  42816. }
  42817. StandardMaterial._OpacityTextureEnabled = value;
  42818. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42819. },
  42820. enumerable: true,
  42821. configurable: true
  42822. });
  42823. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42824. get: function () {
  42825. return StandardMaterial._ReflectionTextureEnabled;
  42826. },
  42827. set: function (value) {
  42828. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42829. return;
  42830. }
  42831. StandardMaterial._ReflectionTextureEnabled = value;
  42832. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42838. get: function () {
  42839. return StandardMaterial._EmissiveTextureEnabled;
  42840. },
  42841. set: function (value) {
  42842. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42843. return;
  42844. }
  42845. StandardMaterial._EmissiveTextureEnabled = value;
  42846. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42847. },
  42848. enumerable: true,
  42849. configurable: true
  42850. });
  42851. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42852. get: function () {
  42853. return StandardMaterial._SpecularTextureEnabled;
  42854. },
  42855. set: function (value) {
  42856. if (StandardMaterial._SpecularTextureEnabled === value) {
  42857. return;
  42858. }
  42859. StandardMaterial._SpecularTextureEnabled = value;
  42860. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42861. },
  42862. enumerable: true,
  42863. configurable: true
  42864. });
  42865. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42866. get: function () {
  42867. return StandardMaterial._BumpTextureEnabled;
  42868. },
  42869. set: function (value) {
  42870. if (StandardMaterial._BumpTextureEnabled === value) {
  42871. return;
  42872. }
  42873. StandardMaterial._BumpTextureEnabled = value;
  42874. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42875. },
  42876. enumerable: true,
  42877. configurable: true
  42878. });
  42879. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42880. get: function () {
  42881. return StandardMaterial._LightmapTextureEnabled;
  42882. },
  42883. set: function (value) {
  42884. if (StandardMaterial._LightmapTextureEnabled === value) {
  42885. return;
  42886. }
  42887. StandardMaterial._LightmapTextureEnabled = value;
  42888. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42889. },
  42890. enumerable: true,
  42891. configurable: true
  42892. });
  42893. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42894. get: function () {
  42895. return StandardMaterial._RefractionTextureEnabled;
  42896. },
  42897. set: function (value) {
  42898. if (StandardMaterial._RefractionTextureEnabled === value) {
  42899. return;
  42900. }
  42901. StandardMaterial._RefractionTextureEnabled = value;
  42902. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42903. },
  42904. enumerable: true,
  42905. configurable: true
  42906. });
  42907. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42908. get: function () {
  42909. return StandardMaterial._ColorGradingTextureEnabled;
  42910. },
  42911. set: function (value) {
  42912. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42913. return;
  42914. }
  42915. StandardMaterial._ColorGradingTextureEnabled = value;
  42916. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42922. get: function () {
  42923. return StandardMaterial._FresnelEnabled;
  42924. },
  42925. set: function (value) {
  42926. if (StandardMaterial._FresnelEnabled === value) {
  42927. return;
  42928. }
  42929. StandardMaterial._FresnelEnabled = value;
  42930. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42931. },
  42932. enumerable: true,
  42933. configurable: true
  42934. });
  42935. // Flags used to enable or disable a type of texture for all Standard Materials
  42936. StandardMaterial._DiffuseTextureEnabled = true;
  42937. StandardMaterial._AmbientTextureEnabled = true;
  42938. StandardMaterial._OpacityTextureEnabled = true;
  42939. StandardMaterial._ReflectionTextureEnabled = true;
  42940. StandardMaterial._EmissiveTextureEnabled = true;
  42941. StandardMaterial._SpecularTextureEnabled = true;
  42942. StandardMaterial._BumpTextureEnabled = true;
  42943. StandardMaterial._LightmapTextureEnabled = true;
  42944. StandardMaterial._RefractionTextureEnabled = true;
  42945. StandardMaterial._ColorGradingTextureEnabled = true;
  42946. StandardMaterial._FresnelEnabled = true;
  42947. __decorate([
  42948. BABYLON.serializeAsTexture("diffuseTexture")
  42949. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42950. __decorate([
  42951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42952. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42953. __decorate([
  42954. BABYLON.serializeAsTexture("ambientTexture")
  42955. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42956. __decorate([
  42957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42958. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42959. __decorate([
  42960. BABYLON.serializeAsTexture("opacityTexture")
  42961. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42962. __decorate([
  42963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42964. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42965. __decorate([
  42966. BABYLON.serializeAsTexture("reflectionTexture")
  42967. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42968. __decorate([
  42969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42970. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42971. __decorate([
  42972. BABYLON.serializeAsTexture("emissiveTexture")
  42973. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42974. __decorate([
  42975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42976. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42977. __decorate([
  42978. BABYLON.serializeAsTexture("specularTexture")
  42979. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42980. __decorate([
  42981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42982. ], StandardMaterial.prototype, "specularTexture", void 0);
  42983. __decorate([
  42984. BABYLON.serializeAsTexture("bumpTexture")
  42985. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42986. __decorate([
  42987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42988. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42989. __decorate([
  42990. BABYLON.serializeAsTexture("lightmapTexture")
  42991. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42992. __decorate([
  42993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42994. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42995. __decorate([
  42996. BABYLON.serializeAsTexture("refractionTexture")
  42997. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42998. __decorate([
  42999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43000. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43001. __decorate([
  43002. BABYLON.serializeAsColor3("ambient")
  43003. ], StandardMaterial.prototype, "ambientColor", void 0);
  43004. __decorate([
  43005. BABYLON.serializeAsColor3("diffuse")
  43006. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43007. __decorate([
  43008. BABYLON.serializeAsColor3("specular")
  43009. ], StandardMaterial.prototype, "specularColor", void 0);
  43010. __decorate([
  43011. BABYLON.serializeAsColor3("emissive")
  43012. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43013. __decorate([
  43014. BABYLON.serialize()
  43015. ], StandardMaterial.prototype, "specularPower", void 0);
  43016. __decorate([
  43017. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43018. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43019. __decorate([
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43021. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43022. __decorate([
  43023. BABYLON.serialize("useEmissiveAsIllumination")
  43024. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43025. __decorate([
  43026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43027. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43028. __decorate([
  43029. BABYLON.serialize("linkEmissiveWithDiffuse")
  43030. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43031. __decorate([
  43032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43033. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43034. __decorate([
  43035. BABYLON.serialize("useSpecularOverAlpha")
  43036. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43037. __decorate([
  43038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43039. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43040. __decorate([
  43041. BABYLON.serialize("useReflectionOverAlpha")
  43042. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43043. __decorate([
  43044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43045. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43046. __decorate([
  43047. BABYLON.serialize("disableLighting")
  43048. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43049. __decorate([
  43050. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43051. ], StandardMaterial.prototype, "disableLighting", void 0);
  43052. __decorate([
  43053. BABYLON.serialize("useObjectSpaceNormalMap")
  43054. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43055. __decorate([
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43057. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43058. __decorate([
  43059. BABYLON.serialize("useParallax")
  43060. ], StandardMaterial.prototype, "_useParallax", void 0);
  43061. __decorate([
  43062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43063. ], StandardMaterial.prototype, "useParallax", void 0);
  43064. __decorate([
  43065. BABYLON.serialize("useParallaxOcclusion")
  43066. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43067. __decorate([
  43068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43069. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43070. __decorate([
  43071. BABYLON.serialize()
  43072. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43073. __decorate([
  43074. BABYLON.serialize("roughness")
  43075. ], StandardMaterial.prototype, "_roughness", void 0);
  43076. __decorate([
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], StandardMaterial.prototype, "roughness", void 0);
  43079. __decorate([
  43080. BABYLON.serialize()
  43081. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43082. __decorate([
  43083. BABYLON.serialize()
  43084. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43085. __decorate([
  43086. BABYLON.serialize()
  43087. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43088. __decorate([
  43089. BABYLON.serialize("useLightmapAsShadowmap")
  43090. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43091. __decorate([
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43093. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43094. __decorate([
  43095. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43096. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43097. __decorate([
  43098. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43099. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43100. __decorate([
  43101. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43102. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43103. __decorate([
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43105. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43106. __decorate([
  43107. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43108. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43109. __decorate([
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43111. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43112. __decorate([
  43113. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43114. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43115. __decorate([
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43117. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43118. __decorate([
  43119. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43120. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43121. __decorate([
  43122. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43123. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43124. __decorate([
  43125. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43126. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43127. __decorate([
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43129. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43130. __decorate([
  43131. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43132. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43133. __decorate([
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43135. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43136. __decorate([
  43137. BABYLON.serialize("maxSimultaneousLights")
  43138. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43139. __decorate([
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43141. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43142. __decorate([
  43143. BABYLON.serialize("invertNormalMapX")
  43144. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43145. __decorate([
  43146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43147. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43148. __decorate([
  43149. BABYLON.serialize("invertNormalMapY")
  43150. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43151. __decorate([
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43154. __decorate([
  43155. BABYLON.serialize("twoSidedLighting")
  43156. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43157. __decorate([
  43158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43159. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43160. __decorate([
  43161. BABYLON.serialize()
  43162. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43163. return StandardMaterial;
  43164. }(BABYLON.PushMaterial));
  43165. BABYLON.StandardMaterial = StandardMaterial;
  43166. })(BABYLON || (BABYLON = {}));
  43167. //# sourceMappingURL=babylon.standardMaterial.js.map
  43168. var BABYLON;
  43169. (function (BABYLON) {
  43170. /**
  43171. * Manages the defines for the PBR Material.
  43172. * @hiddenChildren
  43173. */
  43174. var PBRMaterialDefines = /** @class */ (function (_super) {
  43175. __extends(PBRMaterialDefines, _super);
  43176. /**
  43177. * Initializes the PBR Material defines.
  43178. */
  43179. function PBRMaterialDefines() {
  43180. var _this = _super.call(this) || this;
  43181. _this.PBR = true;
  43182. _this.MAINUV1 = false;
  43183. _this.MAINUV2 = false;
  43184. _this.UV1 = false;
  43185. _this.UV2 = false;
  43186. _this.ALBEDO = false;
  43187. _this.ALBEDODIRECTUV = 0;
  43188. _this.VERTEXCOLOR = false;
  43189. _this.AMBIENT = false;
  43190. _this.AMBIENTDIRECTUV = 0;
  43191. _this.AMBIENTINGRAYSCALE = false;
  43192. _this.OPACITY = false;
  43193. _this.VERTEXALPHA = false;
  43194. _this.OPACITYDIRECTUV = 0;
  43195. _this.OPACITYRGB = false;
  43196. _this.ALPHATEST = false;
  43197. _this.DEPTHPREPASS = false;
  43198. _this.ALPHABLEND = false;
  43199. _this.ALPHAFROMALBEDO = false;
  43200. _this.ALPHATESTVALUE = "0.5";
  43201. _this.SPECULAROVERALPHA = false;
  43202. _this.RADIANCEOVERALPHA = false;
  43203. _this.ALPHAFRESNEL = false;
  43204. _this.LINEARALPHAFRESNEL = false;
  43205. _this.PREMULTIPLYALPHA = false;
  43206. _this.EMISSIVE = false;
  43207. _this.EMISSIVEDIRECTUV = 0;
  43208. _this.REFLECTIVITY = false;
  43209. _this.REFLECTIVITYDIRECTUV = 0;
  43210. _this.SPECULARTERM = false;
  43211. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43212. _this.MICROSURFACEAUTOMATIC = false;
  43213. _this.LODBASEDMICROSFURACE = false;
  43214. _this.MICROSURFACEMAP = false;
  43215. _this.MICROSURFACEMAPDIRECTUV = 0;
  43216. _this.METALLICWORKFLOW = false;
  43217. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43218. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43219. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43220. _this.AOSTOREINMETALMAPRED = false;
  43221. _this.ENVIRONMENTBRDF = false;
  43222. _this.NORMAL = false;
  43223. _this.TANGENT = false;
  43224. _this.BUMP = false;
  43225. _this.BUMPDIRECTUV = 0;
  43226. _this.OBJECTSPACE_NORMALMAP = false;
  43227. _this.PARALLAX = false;
  43228. _this.PARALLAXOCCLUSION = false;
  43229. _this.NORMALXYSCALE = true;
  43230. _this.LIGHTMAP = false;
  43231. _this.LIGHTMAPDIRECTUV = 0;
  43232. _this.USELIGHTMAPASSHADOWMAP = false;
  43233. _this.GAMMALIGHTMAP = false;
  43234. _this.REFLECTION = false;
  43235. _this.REFLECTIONMAP_3D = false;
  43236. _this.REFLECTIONMAP_SPHERICAL = false;
  43237. _this.REFLECTIONMAP_PLANAR = false;
  43238. _this.REFLECTIONMAP_CUBIC = false;
  43239. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43240. _this.REFLECTIONMAP_PROJECTION = false;
  43241. _this.REFLECTIONMAP_SKYBOX = false;
  43242. _this.REFLECTIONMAP_EXPLICIT = false;
  43243. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43244. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43245. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43246. _this.INVERTCUBICMAP = false;
  43247. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43248. _this.USESPHERICALINVERTEX = false;
  43249. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43250. _this.LODINREFLECTIONALPHA = false;
  43251. _this.GAMMAREFLECTION = false;
  43252. _this.RGBDREFLECTION = false;
  43253. _this.RADIANCEOCCLUSION = false;
  43254. _this.HORIZONOCCLUSION = false;
  43255. _this.REFRACTION = false;
  43256. _this.REFRACTIONMAP_3D = false;
  43257. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43258. _this.LODINREFRACTIONALPHA = false;
  43259. _this.GAMMAREFRACTION = false;
  43260. _this.RGBDREFRACTION = false;
  43261. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43262. _this.INSTANCES = false;
  43263. _this.NUM_BONE_INFLUENCERS = 0;
  43264. _this.BonesPerMesh = 0;
  43265. _this.NONUNIFORMSCALING = false;
  43266. _this.MORPHTARGETS = false;
  43267. _this.MORPHTARGETS_NORMAL = false;
  43268. _this.MORPHTARGETS_TANGENT = false;
  43269. _this.NUM_MORPH_INFLUENCERS = 0;
  43270. _this.IMAGEPROCESSING = false;
  43271. _this.VIGNETTE = false;
  43272. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43273. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43274. _this.TONEMAPPING = false;
  43275. _this.CONTRAST = false;
  43276. _this.COLORCURVES = false;
  43277. _this.COLORGRADING = false;
  43278. _this.COLORGRADING3D = false;
  43279. _this.SAMPLER3DGREENDEPTH = false;
  43280. _this.SAMPLER3DBGRMAP = false;
  43281. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43282. _this.EXPOSURE = false;
  43283. _this.USEPHYSICALLIGHTFALLOFF = false;
  43284. _this.TWOSIDEDLIGHTING = false;
  43285. _this.SHADOWFLOAT = false;
  43286. _this.CLIPPLANE = false;
  43287. _this.POINTSIZE = false;
  43288. _this.FOG = false;
  43289. _this.LOGARITHMICDEPTH = false;
  43290. _this.FORCENORMALFORWARD = false;
  43291. _this.SPECULARAA = false;
  43292. _this.UNLIT = false;
  43293. _this.rebuild();
  43294. return _this;
  43295. }
  43296. /**
  43297. * Resets the PBR Material defines.
  43298. */
  43299. PBRMaterialDefines.prototype.reset = function () {
  43300. _super.prototype.reset.call(this);
  43301. this.ALPHATESTVALUE = "0.5";
  43302. this.PBR = true;
  43303. };
  43304. return PBRMaterialDefines;
  43305. }(BABYLON.MaterialDefines));
  43306. /**
  43307. * The Physically based material base class of BJS.
  43308. *
  43309. * This offers the main features of a standard PBR material.
  43310. * For more information, please refer to the documentation :
  43311. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43312. */
  43313. var PBRBaseMaterial = /** @class */ (function (_super) {
  43314. __extends(PBRBaseMaterial, _super);
  43315. /**
  43316. * Instantiates a new PBRMaterial instance.
  43317. *
  43318. * @param name The material name
  43319. * @param scene The scene the material will be use in.
  43320. */
  43321. function PBRBaseMaterial(name, scene) {
  43322. var _this = _super.call(this, name, scene) || this;
  43323. /**
  43324. * Intensity of the direct lights e.g. the four lights available in your scene.
  43325. * This impacts both the direct diffuse and specular highlights.
  43326. */
  43327. _this._directIntensity = 1.0;
  43328. /**
  43329. * Intensity of the emissive part of the material.
  43330. * This helps controlling the emissive effect without modifying the emissive color.
  43331. */
  43332. _this._emissiveIntensity = 1.0;
  43333. /**
  43334. * Intensity of the environment e.g. how much the environment will light the object
  43335. * either through harmonics for rough material or through the refelction for shiny ones.
  43336. */
  43337. _this._environmentIntensity = 1.0;
  43338. /**
  43339. * This is a special control allowing the reduction of the specular highlights coming from the
  43340. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43341. */
  43342. _this._specularIntensity = 1.0;
  43343. /**
  43344. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43345. */
  43346. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43347. /**
  43348. * Debug Control allowing disabling the bump map on this material.
  43349. */
  43350. _this._disableBumpMap = false;
  43351. /**
  43352. * AKA Occlusion Texture Intensity in other nomenclature.
  43353. */
  43354. _this._ambientTextureStrength = 1.0;
  43355. /**
  43356. * The color of a material in ambient lighting.
  43357. */
  43358. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43359. /**
  43360. * AKA Diffuse Color in other nomenclature.
  43361. */
  43362. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43363. /**
  43364. * AKA Specular Color in other nomenclature.
  43365. */
  43366. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43367. /**
  43368. * The color applied when light is reflected from a material.
  43369. */
  43370. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43371. /**
  43372. * The color applied when light is emitted from a material.
  43373. */
  43374. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43375. /**
  43376. * AKA Glossiness in other nomenclature.
  43377. */
  43378. _this._microSurface = 0.9;
  43379. /**
  43380. * source material index of refraction (IOR)' / 'destination material IOR.
  43381. */
  43382. _this._indexOfRefraction = 0.66;
  43383. /**
  43384. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43385. */
  43386. _this._invertRefractionY = false;
  43387. /**
  43388. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43389. * Materials half opaque for instance using refraction could benefit from this control.
  43390. */
  43391. _this._linkRefractionWithTransparency = false;
  43392. /**
  43393. * Specifies that the material will use the light map as a show map.
  43394. */
  43395. _this._useLightmapAsShadowmap = false;
  43396. /**
  43397. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43398. * makes the reflect vector face the model (under horizon).
  43399. */
  43400. _this._useHorizonOcclusion = true;
  43401. /**
  43402. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43403. * too much the area relying on ambient texture to define their ambient occlusion.
  43404. */
  43405. _this._useRadianceOcclusion = true;
  43406. /**
  43407. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43408. */
  43409. _this._useAlphaFromAlbedoTexture = false;
  43410. /**
  43411. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43412. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43413. */
  43414. _this._useSpecularOverAlpha = true;
  43415. /**
  43416. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43417. */
  43418. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43419. /**
  43420. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43421. */
  43422. _this._useRoughnessFromMetallicTextureAlpha = true;
  43423. /**
  43424. * Specifies if the metallic texture contains the roughness information in its green channel.
  43425. */
  43426. _this._useRoughnessFromMetallicTextureGreen = false;
  43427. /**
  43428. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43429. */
  43430. _this._useMetallnessFromMetallicTextureBlue = false;
  43431. /**
  43432. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43433. */
  43434. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43435. /**
  43436. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43437. */
  43438. _this._useAmbientInGrayScale = false;
  43439. /**
  43440. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43441. * The material will try to infer what glossiness each pixel should be.
  43442. */
  43443. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43444. /**
  43445. * BJS is using an harcoded light falloff based on a manually sets up range.
  43446. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43447. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43448. */
  43449. _this._usePhysicalLightFalloff = true;
  43450. /**
  43451. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43452. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43453. */
  43454. _this._useRadianceOverAlpha = true;
  43455. /**
  43456. * Allows using an object space normal map (instead of tangent space).
  43457. */
  43458. _this._useObjectSpaceNormalMap = false;
  43459. /**
  43460. * Allows using the bump map in parallax mode.
  43461. */
  43462. _this._useParallax = false;
  43463. /**
  43464. * Allows using the bump map in parallax occlusion mode.
  43465. */
  43466. _this._useParallaxOcclusion = false;
  43467. /**
  43468. * Controls the scale bias of the parallax mode.
  43469. */
  43470. _this._parallaxScaleBias = 0.05;
  43471. /**
  43472. * If sets to true, disables all the lights affecting the material.
  43473. */
  43474. _this._disableLighting = false;
  43475. /**
  43476. * Number of Simultaneous lights allowed on the material.
  43477. */
  43478. _this._maxSimultaneousLights = 4;
  43479. /**
  43480. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43481. */
  43482. _this._invertNormalMapX = false;
  43483. /**
  43484. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43485. */
  43486. _this._invertNormalMapY = false;
  43487. /**
  43488. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43489. */
  43490. _this._twoSidedLighting = false;
  43491. /**
  43492. * Defines the alpha limits in alpha test mode.
  43493. */
  43494. _this._alphaCutOff = 0.4;
  43495. /**
  43496. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43497. */
  43498. _this._forceAlphaTest = false;
  43499. /**
  43500. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43501. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43502. */
  43503. _this._useAlphaFresnel = false;
  43504. /**
  43505. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43506. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43507. */
  43508. _this._useLinearAlphaFresnel = false;
  43509. /**
  43510. * The transparency mode of the material.
  43511. */
  43512. _this._transparencyMode = null;
  43513. /**
  43514. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43515. * from cos thetav and roughness:
  43516. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43517. */
  43518. _this._environmentBRDFTexture = null;
  43519. /**
  43520. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43521. */
  43522. _this._forceIrradianceInFragment = false;
  43523. /**
  43524. * Force normal to face away from face.
  43525. */
  43526. _this._forceNormalForward = false;
  43527. /**
  43528. * Enables specular anti aliasing in the PBR shader.
  43529. * It will both interacts on the Geometry for analytical and IBL lighting.
  43530. * It also prefilter the roughness map based on the bump values.
  43531. */
  43532. _this._enableSpecularAntiAliasing = false;
  43533. /**
  43534. * Stores the available render targets.
  43535. */
  43536. _this._renderTargets = new BABYLON.SmartArray(16);
  43537. /**
  43538. * Sets the global ambient color for the material used in lighting calculations.
  43539. */
  43540. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43541. /**
  43542. * If set to true, no lighting calculations will be applied.
  43543. */
  43544. _this._unlit = false;
  43545. // Setup the default processing configuration to the scene.
  43546. _this._attachImageProcessingConfiguration(null);
  43547. _this.getRenderTargetTextures = function () {
  43548. _this._renderTargets.reset();
  43549. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43550. _this._renderTargets.push(_this._reflectionTexture);
  43551. }
  43552. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43553. _this._renderTargets.push(_this._refractionTexture);
  43554. }
  43555. return _this._renderTargets;
  43556. };
  43557. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43558. return _this;
  43559. }
  43560. /**
  43561. * Attaches a new image processing configuration to the PBR Material.
  43562. * @param configuration
  43563. */
  43564. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43565. var _this = this;
  43566. if (configuration === this._imageProcessingConfiguration) {
  43567. return;
  43568. }
  43569. // Detaches observer.
  43570. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43571. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43572. }
  43573. // Pick the scene configuration if needed.
  43574. if (!configuration) {
  43575. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43576. }
  43577. else {
  43578. this._imageProcessingConfiguration = configuration;
  43579. }
  43580. // Attaches observer.
  43581. if (this._imageProcessingConfiguration) {
  43582. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43583. _this._markAllSubMeshesAsImageProcessingDirty();
  43584. });
  43585. }
  43586. };
  43587. /**
  43588. * Gets the name of the material class.
  43589. */
  43590. PBRBaseMaterial.prototype.getClassName = function () {
  43591. return "PBRBaseMaterial";
  43592. };
  43593. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43594. /**
  43595. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43596. */
  43597. get: function () {
  43598. return this._useLogarithmicDepth;
  43599. },
  43600. /**
  43601. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43602. */
  43603. set: function (value) {
  43604. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43605. },
  43606. enumerable: true,
  43607. configurable: true
  43608. });
  43609. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43610. /**
  43611. * Gets the current transparency mode.
  43612. */
  43613. get: function () {
  43614. return this._transparencyMode;
  43615. },
  43616. /**
  43617. * Sets the transparency mode of the material.
  43618. *
  43619. * | Value | Type | Description |
  43620. * | ----- | ----------------------------------- | ----------- |
  43621. * | 0 | OPAQUE | |
  43622. * | 1 | ALPHATEST | |
  43623. * | 2 | ALPHABLEND | |
  43624. * | 3 | ALPHATESTANDBLEND | |
  43625. *
  43626. */
  43627. set: function (value) {
  43628. if (this._transparencyMode === value) {
  43629. return;
  43630. }
  43631. this._transparencyMode = value;
  43632. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43633. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43634. },
  43635. enumerable: true,
  43636. configurable: true
  43637. });
  43638. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43639. /**
  43640. * Returns true if alpha blending should be disabled.
  43641. */
  43642. get: function () {
  43643. return (this._linkRefractionWithTransparency ||
  43644. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43645. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43646. },
  43647. enumerable: true,
  43648. configurable: true
  43649. });
  43650. /**
  43651. * Specifies whether or not this material should be rendered in alpha blend mode.
  43652. */
  43653. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43654. if (this._disableAlphaBlending) {
  43655. return false;
  43656. }
  43657. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43658. };
  43659. /**
  43660. * Specifies if the mesh will require alpha blending.
  43661. * @param mesh - BJS mesh.
  43662. */
  43663. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43664. if (this._disableAlphaBlending) {
  43665. return false;
  43666. }
  43667. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43668. };
  43669. /**
  43670. * Specifies whether or not this material should be rendered in alpha test mode.
  43671. */
  43672. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43673. if (this._forceAlphaTest) {
  43674. return true;
  43675. }
  43676. if (this._linkRefractionWithTransparency) {
  43677. return false;
  43678. }
  43679. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43680. };
  43681. /**
  43682. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43683. */
  43684. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43685. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43686. };
  43687. /**
  43688. * Gets the texture used for the alpha test.
  43689. */
  43690. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43691. return this._albedoTexture;
  43692. };
  43693. /**
  43694. * Specifies that the submesh is ready to be used.
  43695. * @param mesh - BJS mesh.
  43696. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43697. * @param useInstances - Specifies that instances should be used.
  43698. * @returns - boolean indicating that the submesh is ready or not.
  43699. */
  43700. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43701. if (subMesh.effect && this.isFrozen) {
  43702. if (this._wasPreviouslyReady) {
  43703. return true;
  43704. }
  43705. }
  43706. if (!subMesh._materialDefines) {
  43707. subMesh._materialDefines = new PBRMaterialDefines();
  43708. }
  43709. var defines = subMesh._materialDefines;
  43710. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43711. if (defines._renderId === this.getScene().getRenderId()) {
  43712. return true;
  43713. }
  43714. }
  43715. var scene = this.getScene();
  43716. var engine = scene.getEngine();
  43717. if (defines._areTexturesDirty) {
  43718. if (scene.texturesEnabled) {
  43719. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43720. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43721. return false;
  43722. }
  43723. }
  43724. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43725. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43726. return false;
  43727. }
  43728. }
  43729. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43730. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43731. return false;
  43732. }
  43733. }
  43734. var reflectionTexture = this._getReflectionTexture();
  43735. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43736. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43737. return false;
  43738. }
  43739. }
  43740. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43741. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43742. return false;
  43743. }
  43744. }
  43745. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43746. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43747. return false;
  43748. }
  43749. }
  43750. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43751. if (this._metallicTexture) {
  43752. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43753. return false;
  43754. }
  43755. }
  43756. else if (this._reflectivityTexture) {
  43757. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43758. return false;
  43759. }
  43760. }
  43761. if (this._microSurfaceTexture) {
  43762. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43763. return false;
  43764. }
  43765. }
  43766. }
  43767. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43768. // Bump texture cannot be not blocking.
  43769. if (!this._bumpTexture.isReady()) {
  43770. return false;
  43771. }
  43772. }
  43773. var refractionTexture = this._getRefractionTexture();
  43774. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43775. if (!refractionTexture.isReadyOrNotBlocking()) {
  43776. return false;
  43777. }
  43778. }
  43779. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43780. // This is blocking.
  43781. if (!this._environmentBRDFTexture.isReady()) {
  43782. return false;
  43783. }
  43784. }
  43785. }
  43786. }
  43787. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43788. if (!this._imageProcessingConfiguration.isReady()) {
  43789. return false;
  43790. }
  43791. }
  43792. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43793. mesh.createNormals(true);
  43794. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43795. }
  43796. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43797. if (effect) {
  43798. scene.resetCachedMaterial();
  43799. subMesh.setEffect(effect, defines);
  43800. this.buildUniformLayout();
  43801. }
  43802. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43803. return false;
  43804. }
  43805. defines._renderId = scene.getRenderId();
  43806. this._wasPreviouslyReady = true;
  43807. return true;
  43808. };
  43809. /**
  43810. * Specifies if the material uses metallic roughness workflow.
  43811. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43812. */
  43813. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43814. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43815. return true;
  43816. }
  43817. return false;
  43818. };
  43819. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43820. if (onCompiled === void 0) { onCompiled = null; }
  43821. if (onError === void 0) { onError = null; }
  43822. if (useInstances === void 0) { useInstances = null; }
  43823. if (useClipPlane === void 0) { useClipPlane = null; }
  43824. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43825. if (!defines.isDirty) {
  43826. return null;
  43827. }
  43828. defines.markAsProcessed();
  43829. var scene = this.getScene();
  43830. var engine = scene.getEngine();
  43831. // Fallbacks
  43832. var fallbacks = new BABYLON.EffectFallbacks();
  43833. var fallbackRank = 0;
  43834. if (defines.USESPHERICALINVERTEX) {
  43835. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43836. }
  43837. if (defines.FOG) {
  43838. fallbacks.addFallback(fallbackRank, "FOG");
  43839. }
  43840. if (defines.SPECULARAA) {
  43841. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43842. }
  43843. if (defines.POINTSIZE) {
  43844. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43845. }
  43846. if (defines.LOGARITHMICDEPTH) {
  43847. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43848. }
  43849. if (defines.PARALLAX) {
  43850. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43851. }
  43852. if (defines.PARALLAXOCCLUSION) {
  43853. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43854. }
  43855. if (defines.ENVIRONMENTBRDF) {
  43856. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43857. }
  43858. if (defines.TANGENT) {
  43859. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43860. }
  43861. if (defines.BUMP) {
  43862. fallbacks.addFallback(fallbackRank++, "BUMP");
  43863. }
  43864. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43865. if (defines.SPECULARTERM) {
  43866. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43867. }
  43868. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43869. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43870. }
  43871. if (defines.LIGHTMAP) {
  43872. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43873. }
  43874. if (defines.NORMAL) {
  43875. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43876. }
  43877. if (defines.AMBIENT) {
  43878. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43879. }
  43880. if (defines.EMISSIVE) {
  43881. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43882. }
  43883. if (defines.VERTEXCOLOR) {
  43884. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43885. }
  43886. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43887. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43888. }
  43889. if (defines.MORPHTARGETS) {
  43890. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43891. }
  43892. //Attributes
  43893. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43894. if (defines.NORMAL) {
  43895. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43896. }
  43897. if (defines.TANGENT) {
  43898. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43899. }
  43900. if (defines.UV1) {
  43901. attribs.push(BABYLON.VertexBuffer.UVKind);
  43902. }
  43903. if (defines.UV2) {
  43904. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43905. }
  43906. if (defines.VERTEXCOLOR) {
  43907. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43908. }
  43909. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43910. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43911. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43912. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43913. "vFogInfos", "vFogColor", "pointSize",
  43914. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43915. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43916. "mBones",
  43917. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43918. "vLightingIntensity",
  43919. "logarithmicDepthConstant",
  43920. "vSphericalX", "vSphericalY", "vSphericalZ",
  43921. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43922. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43923. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43924. "vTangentSpaceParams"
  43925. ];
  43926. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43927. "bumpSampler", "lightmapSampler", "opacitySampler",
  43928. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43929. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43930. "microSurfaceSampler", "environmentBrdfSampler"];
  43931. var uniformBuffers = ["Material", "Scene"];
  43932. if (BABYLON.ImageProcessingConfiguration) {
  43933. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43934. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43935. }
  43936. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43937. uniformsNames: uniforms,
  43938. uniformBuffersNames: uniformBuffers,
  43939. samplers: samplers,
  43940. defines: defines,
  43941. maxSimultaneousLights: this._maxSimultaneousLights
  43942. });
  43943. var join = defines.toString();
  43944. return engine.createEffect("pbr", {
  43945. attributes: attribs,
  43946. uniformsNames: uniforms,
  43947. uniformBuffersNames: uniformBuffers,
  43948. samplers: samplers,
  43949. defines: join,
  43950. fallbacks: fallbacks,
  43951. onCompiled: onCompiled,
  43952. onError: onError,
  43953. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43954. }, engine);
  43955. };
  43956. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43957. if (useInstances === void 0) { useInstances = null; }
  43958. if (useClipPlane === void 0) { useClipPlane = null; }
  43959. var scene = this.getScene();
  43960. var engine = scene.getEngine();
  43961. // Lights
  43962. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43963. defines._needNormals = true;
  43964. // Textures
  43965. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43966. if (defines._areTexturesDirty) {
  43967. defines._needUVs = false;
  43968. if (scene.texturesEnabled) {
  43969. if (scene.getEngine().getCaps().textureLOD) {
  43970. defines.LODBASEDMICROSFURACE = true;
  43971. }
  43972. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43973. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43974. }
  43975. else {
  43976. defines.ALBEDO = false;
  43977. }
  43978. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43979. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43980. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43981. }
  43982. else {
  43983. defines.AMBIENT = false;
  43984. }
  43985. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43986. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43987. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43988. }
  43989. else {
  43990. defines.OPACITY = false;
  43991. }
  43992. var reflectionTexture = this._getReflectionTexture();
  43993. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43994. defines.REFLECTION = true;
  43995. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43996. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43997. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43998. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43999. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44000. defines.INVERTCUBICMAP = true;
  44001. }
  44002. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44003. switch (reflectionTexture.coordinatesMode) {
  44004. case BABYLON.Texture.EXPLICIT_MODE:
  44005. defines.REFLECTIONMAP_EXPLICIT = true;
  44006. break;
  44007. case BABYLON.Texture.PLANAR_MODE:
  44008. defines.REFLECTIONMAP_PLANAR = true;
  44009. break;
  44010. case BABYLON.Texture.PROJECTION_MODE:
  44011. defines.REFLECTIONMAP_PROJECTION = true;
  44012. break;
  44013. case BABYLON.Texture.SKYBOX_MODE:
  44014. defines.REFLECTIONMAP_SKYBOX = true;
  44015. break;
  44016. case BABYLON.Texture.SPHERICAL_MODE:
  44017. defines.REFLECTIONMAP_SPHERICAL = true;
  44018. break;
  44019. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44020. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44021. break;
  44022. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44023. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44024. break;
  44025. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44026. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44027. break;
  44028. case BABYLON.Texture.CUBIC_MODE:
  44029. case BABYLON.Texture.INVCUBIC_MODE:
  44030. default:
  44031. defines.REFLECTIONMAP_CUBIC = true;
  44032. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44033. break;
  44034. }
  44035. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44036. if (reflectionTexture.sphericalPolynomial) {
  44037. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44038. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44039. defines.USESPHERICALINVERTEX = false;
  44040. }
  44041. else {
  44042. defines.USESPHERICALINVERTEX = true;
  44043. }
  44044. }
  44045. }
  44046. }
  44047. else {
  44048. defines.REFLECTION = false;
  44049. defines.REFLECTIONMAP_3D = false;
  44050. defines.REFLECTIONMAP_SPHERICAL = false;
  44051. defines.REFLECTIONMAP_PLANAR = false;
  44052. defines.REFLECTIONMAP_CUBIC = false;
  44053. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44054. defines.REFLECTIONMAP_PROJECTION = false;
  44055. defines.REFLECTIONMAP_SKYBOX = false;
  44056. defines.REFLECTIONMAP_EXPLICIT = false;
  44057. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44058. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44059. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44060. defines.INVERTCUBICMAP = false;
  44061. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44062. defines.USESPHERICALINVERTEX = false;
  44063. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44064. defines.LODINREFLECTIONALPHA = false;
  44065. defines.GAMMAREFLECTION = false;
  44066. defines.RGBDREFLECTION = false;
  44067. }
  44068. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44069. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44070. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44071. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44072. }
  44073. else {
  44074. defines.LIGHTMAP = false;
  44075. }
  44076. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44077. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44078. }
  44079. else {
  44080. defines.EMISSIVE = false;
  44081. }
  44082. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44083. if (this._metallicTexture) {
  44084. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44085. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44086. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44087. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44088. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44089. }
  44090. else if (this._reflectivityTexture) {
  44091. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44092. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44093. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44094. }
  44095. else {
  44096. defines.REFLECTIVITY = false;
  44097. }
  44098. if (this._microSurfaceTexture) {
  44099. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44100. }
  44101. else {
  44102. defines.MICROSURFACEMAP = false;
  44103. }
  44104. }
  44105. else {
  44106. defines.REFLECTIVITY = false;
  44107. defines.MICROSURFACEMAP = false;
  44108. }
  44109. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44110. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44111. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44112. defines.PARALLAX = true;
  44113. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44114. }
  44115. else {
  44116. defines.PARALLAX = false;
  44117. }
  44118. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44119. }
  44120. else {
  44121. defines.BUMP = false;
  44122. }
  44123. var refractionTexture = this._getRefractionTexture();
  44124. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44125. defines.REFRACTION = true;
  44126. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44127. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44128. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44129. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44130. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44131. if (this._linkRefractionWithTransparency) {
  44132. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44133. }
  44134. }
  44135. else {
  44136. defines.REFRACTION = false;
  44137. }
  44138. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44139. defines.ENVIRONMENTBRDF = true;
  44140. }
  44141. else {
  44142. defines.ENVIRONMENTBRDF = false;
  44143. }
  44144. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44145. defines.ALPHAFROMALBEDO = true;
  44146. }
  44147. else {
  44148. defines.ALPHAFROMALBEDO = false;
  44149. }
  44150. }
  44151. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44152. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44153. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44154. if (!this.backFaceCulling && this._twoSidedLighting) {
  44155. defines.TWOSIDEDLIGHTING = true;
  44156. }
  44157. else {
  44158. defines.TWOSIDEDLIGHTING = false;
  44159. }
  44160. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44161. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44162. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44163. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44164. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44165. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44166. }
  44167. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44168. this._imageProcessingConfiguration.prepareDefines(defines);
  44169. }
  44170. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44171. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44172. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44173. // Misc.
  44174. if (defines._areMiscDirty) {
  44175. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44176. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44177. }
  44178. // Values that need to be evaluated on every frame
  44179. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44180. // Attribs
  44181. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44182. };
  44183. /**
  44184. * Force shader compilation
  44185. */
  44186. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44187. var _this = this;
  44188. var localOptions = __assign({ clipPlane: false }, options);
  44189. var defines = new PBRMaterialDefines();
  44190. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44191. if (effect.isReady()) {
  44192. if (onCompiled) {
  44193. onCompiled(this);
  44194. }
  44195. }
  44196. else {
  44197. effect.onCompileObservable.add(function () {
  44198. if (onCompiled) {
  44199. onCompiled(_this);
  44200. }
  44201. });
  44202. }
  44203. };
  44204. /**
  44205. * Initializes the uniform buffer layout for the shader.
  44206. */
  44207. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44208. // Order is important !
  44209. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44210. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44211. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44212. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44213. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44214. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44215. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44216. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44217. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44218. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44219. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44220. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44221. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44222. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44223. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44224. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44225. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44226. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44227. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44228. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44229. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44230. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44231. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44232. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44233. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44234. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44235. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44236. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44237. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44238. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44239. this._uniformBuffer.addUniform("pointSize", 1);
  44240. this._uniformBuffer.create();
  44241. };
  44242. /**
  44243. * Unbinds the textures.
  44244. */
  44245. PBRBaseMaterial.prototype.unbind = function () {
  44246. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44247. this._uniformBuffer.setTexture("reflectionSampler", null);
  44248. }
  44249. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44250. this._uniformBuffer.setTexture("refractionSampler", null);
  44251. }
  44252. _super.prototype.unbind.call(this);
  44253. };
  44254. /**
  44255. * Binds the submesh data.
  44256. * @param world - The world matrix.
  44257. * @param mesh - The BJS mesh.
  44258. * @param subMesh - A submesh of the BJS mesh.
  44259. */
  44260. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44261. var scene = this.getScene();
  44262. var defines = subMesh._materialDefines;
  44263. if (!defines) {
  44264. return;
  44265. }
  44266. var effect = subMesh.effect;
  44267. if (!effect) {
  44268. return;
  44269. }
  44270. this._activeEffect = effect;
  44271. // Matrices
  44272. this.bindOnlyWorldMatrix(world);
  44273. // Normal Matrix
  44274. if (defines.OBJECTSPACE_NORMALMAP) {
  44275. world.toNormalMatrix(this._normalMatrix);
  44276. this.bindOnlyNormalMatrix(this._normalMatrix);
  44277. }
  44278. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44279. // Bones
  44280. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44281. var reflectionTexture = null;
  44282. if (mustRebind) {
  44283. this._uniformBuffer.bindToEffect(effect, "Material");
  44284. this.bindViewProjection(effect);
  44285. reflectionTexture = this._getReflectionTexture();
  44286. var refractionTexture = this._getRefractionTexture();
  44287. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44288. // Texture uniforms
  44289. if (scene.texturesEnabled) {
  44290. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44291. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44292. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44293. }
  44294. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44295. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44296. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44297. }
  44298. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44299. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44300. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44301. }
  44302. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44303. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44304. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44305. if (reflectionTexture.boundingBoxSize) {
  44306. var cubeTexture = reflectionTexture;
  44307. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44308. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44309. }
  44310. var polynomials = reflectionTexture.sphericalPolynomial;
  44311. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44312. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44313. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44314. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44315. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44316. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44317. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44318. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44319. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44320. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44321. }
  44322. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44323. }
  44324. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44325. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44326. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44327. }
  44328. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44329. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44330. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44331. }
  44332. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44333. if (this._metallicTexture) {
  44334. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44335. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44336. }
  44337. else if (this._reflectivityTexture) {
  44338. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44339. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44340. }
  44341. if (this._microSurfaceTexture) {
  44342. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44343. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44344. }
  44345. }
  44346. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44347. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44348. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44349. if (scene._mirroredCameraPosition) {
  44350. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44351. }
  44352. else {
  44353. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44354. }
  44355. }
  44356. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44357. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44358. var depth = 1.0;
  44359. if (!refractionTexture.isCube) {
  44360. if (refractionTexture.depth) {
  44361. depth = refractionTexture.depth;
  44362. }
  44363. }
  44364. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44365. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44366. }
  44367. }
  44368. // Point size
  44369. if (this.pointsCloud) {
  44370. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44371. }
  44372. // Colors
  44373. if (defines.METALLICWORKFLOW) {
  44374. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44375. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44376. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44377. }
  44378. else {
  44379. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44380. }
  44381. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44382. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44383. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44384. // Misc
  44385. this._lightingInfos.x = this._directIntensity;
  44386. this._lightingInfos.y = this._emissiveIntensity;
  44387. this._lightingInfos.z = this._environmentIntensity;
  44388. this._lightingInfos.w = this._specularIntensity;
  44389. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44390. }
  44391. // Textures
  44392. if (scene.texturesEnabled) {
  44393. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44394. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44395. }
  44396. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44397. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44398. }
  44399. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44400. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44401. }
  44402. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44403. if (defines.LODBASEDMICROSFURACE) {
  44404. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44405. }
  44406. else {
  44407. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44408. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44409. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44410. }
  44411. }
  44412. if (defines.ENVIRONMENTBRDF) {
  44413. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44414. }
  44415. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44416. if (defines.LODBASEDMICROSFURACE) {
  44417. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44418. }
  44419. else {
  44420. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44421. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44422. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44423. }
  44424. }
  44425. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44426. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44427. }
  44428. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44429. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44430. }
  44431. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44432. if (this._metallicTexture) {
  44433. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44434. }
  44435. else if (this._reflectivityTexture) {
  44436. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44437. }
  44438. if (this._microSurfaceTexture) {
  44439. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44440. }
  44441. }
  44442. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44443. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44444. }
  44445. }
  44446. // Clip plane
  44447. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44448. // Colors
  44449. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44450. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44451. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44452. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44453. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44454. }
  44455. if (mustRebind || !this.isFrozen) {
  44456. // Lights
  44457. if (scene.lightsEnabled && !this._disableLighting) {
  44458. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44459. }
  44460. // View
  44461. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44462. this.bindView(effect);
  44463. }
  44464. // Fog
  44465. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44466. // Morph targets
  44467. if (defines.NUM_MORPH_INFLUENCERS) {
  44468. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44469. }
  44470. // image processing
  44471. this._imageProcessingConfiguration.bind(this._activeEffect);
  44472. // Log. depth
  44473. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44474. }
  44475. this._uniformBuffer.update();
  44476. this._afterBind(mesh, this._activeEffect);
  44477. };
  44478. /**
  44479. * Returns the animatable textures.
  44480. * @returns - Array of animatable textures.
  44481. */
  44482. PBRBaseMaterial.prototype.getAnimatables = function () {
  44483. var results = [];
  44484. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44485. results.push(this._albedoTexture);
  44486. }
  44487. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44488. results.push(this._ambientTexture);
  44489. }
  44490. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44491. results.push(this._opacityTexture);
  44492. }
  44493. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44494. results.push(this._reflectionTexture);
  44495. }
  44496. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44497. results.push(this._emissiveTexture);
  44498. }
  44499. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44500. results.push(this._metallicTexture);
  44501. }
  44502. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44503. results.push(this._reflectivityTexture);
  44504. }
  44505. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44506. results.push(this._bumpTexture);
  44507. }
  44508. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44509. results.push(this._lightmapTexture);
  44510. }
  44511. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44512. results.push(this._refractionTexture);
  44513. }
  44514. return results;
  44515. };
  44516. /**
  44517. * Returns the texture used for reflections.
  44518. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44519. */
  44520. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44521. if (this._reflectionTexture) {
  44522. return this._reflectionTexture;
  44523. }
  44524. return this.getScene().environmentTexture;
  44525. };
  44526. /**
  44527. * Returns the texture used for refraction or null if none is used.
  44528. * @returns - Refection texture if present. If no refraction texture and refraction
  44529. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44530. */
  44531. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44532. if (this._refractionTexture) {
  44533. return this._refractionTexture;
  44534. }
  44535. if (this._linkRefractionWithTransparency) {
  44536. return this.getScene().environmentTexture;
  44537. }
  44538. return null;
  44539. };
  44540. /**
  44541. * Disposes the resources of the material.
  44542. * @param forceDisposeEffect - Forces the disposal of effects.
  44543. * @param forceDisposeTextures - Forces the disposal of all textures.
  44544. */
  44545. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44546. if (forceDisposeTextures) {
  44547. if (this._albedoTexture) {
  44548. this._albedoTexture.dispose();
  44549. }
  44550. if (this._ambientTexture) {
  44551. this._ambientTexture.dispose();
  44552. }
  44553. if (this._opacityTexture) {
  44554. this._opacityTexture.dispose();
  44555. }
  44556. if (this._reflectionTexture) {
  44557. this._reflectionTexture.dispose();
  44558. }
  44559. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44560. this._environmentBRDFTexture.dispose();
  44561. }
  44562. if (this._emissiveTexture) {
  44563. this._emissiveTexture.dispose();
  44564. }
  44565. if (this._metallicTexture) {
  44566. this._metallicTexture.dispose();
  44567. }
  44568. if (this._reflectivityTexture) {
  44569. this._reflectivityTexture.dispose();
  44570. }
  44571. if (this._bumpTexture) {
  44572. this._bumpTexture.dispose();
  44573. }
  44574. if (this._lightmapTexture) {
  44575. this._lightmapTexture.dispose();
  44576. }
  44577. if (this._refractionTexture) {
  44578. this._refractionTexture.dispose();
  44579. }
  44580. }
  44581. this._renderTargets.dispose();
  44582. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44583. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44584. }
  44585. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44586. };
  44587. /**
  44588. * Stores the reflectivity values based on metallic roughness workflow.
  44589. */
  44590. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44591. __decorate([
  44592. BABYLON.serializeAsImageProcessingConfiguration()
  44593. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44594. __decorate([
  44595. BABYLON.serialize()
  44596. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44597. __decorate([
  44598. BABYLON.serialize()
  44599. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44600. return PBRBaseMaterial;
  44601. }(BABYLON.PushMaterial));
  44602. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44603. })(BABYLON || (BABYLON = {}));
  44604. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44605. var BABYLON;
  44606. (function (BABYLON) {
  44607. /**
  44608. * The Physically based simple base material of BJS.
  44609. *
  44610. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44611. * It is used as the base class for both the specGloss and metalRough conventions.
  44612. */
  44613. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44614. __extends(PBRBaseSimpleMaterial, _super);
  44615. /**
  44616. * Instantiates a new PBRMaterial instance.
  44617. *
  44618. * @param name The material name
  44619. * @param scene The scene the material will be use in.
  44620. */
  44621. function PBRBaseSimpleMaterial(name, scene) {
  44622. var _this = _super.call(this, name, scene) || this;
  44623. /**
  44624. * Number of Simultaneous lights allowed on the material.
  44625. */
  44626. _this.maxSimultaneousLights = 4;
  44627. /**
  44628. * If sets to true, disables all the lights affecting the material.
  44629. */
  44630. _this.disableLighting = false;
  44631. /**
  44632. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44633. */
  44634. _this.invertNormalMapX = false;
  44635. /**
  44636. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44637. */
  44638. _this.invertNormalMapY = false;
  44639. /**
  44640. * Emissivie color used to self-illuminate the model.
  44641. */
  44642. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44643. /**
  44644. * Occlusion Channel Strenght.
  44645. */
  44646. _this.occlusionStrength = 1.0;
  44647. _this.useLightmapAsShadowmap = false;
  44648. _this._useAlphaFromAlbedoTexture = true;
  44649. _this._useAmbientInGrayScale = true;
  44650. return _this;
  44651. }
  44652. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44653. /**
  44654. * Gets the current double sided mode.
  44655. */
  44656. get: function () {
  44657. return this._twoSidedLighting;
  44658. },
  44659. /**
  44660. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44661. */
  44662. set: function (value) {
  44663. if (this._twoSidedLighting === value) {
  44664. return;
  44665. }
  44666. this._twoSidedLighting = value;
  44667. this.backFaceCulling = !value;
  44668. this._markAllSubMeshesAsTexturesDirty();
  44669. },
  44670. enumerable: true,
  44671. configurable: true
  44672. });
  44673. /**
  44674. * Return the active textures of the material.
  44675. */
  44676. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44677. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44678. if (this.environmentTexture) {
  44679. activeTextures.push(this.environmentTexture);
  44680. }
  44681. if (this.normalTexture) {
  44682. activeTextures.push(this.normalTexture);
  44683. }
  44684. if (this.emissiveTexture) {
  44685. activeTextures.push(this.emissiveTexture);
  44686. }
  44687. if (this.occlusionTexture) {
  44688. activeTextures.push(this.occlusionTexture);
  44689. }
  44690. if (this.lightmapTexture) {
  44691. activeTextures.push(this.lightmapTexture);
  44692. }
  44693. return activeTextures;
  44694. };
  44695. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44696. if (_super.prototype.hasTexture.call(this, texture)) {
  44697. return true;
  44698. }
  44699. if (this.lightmapTexture === texture) {
  44700. return true;
  44701. }
  44702. return false;
  44703. };
  44704. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44705. return "PBRBaseSimpleMaterial";
  44706. };
  44707. __decorate([
  44708. BABYLON.serialize(),
  44709. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44710. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44711. __decorate([
  44712. BABYLON.serialize(),
  44713. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44714. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44715. __decorate([
  44716. BABYLON.serializeAsTexture(),
  44717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44718. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44719. __decorate([
  44720. BABYLON.serialize(),
  44721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44722. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44723. __decorate([
  44724. BABYLON.serialize(),
  44725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44726. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44727. __decorate([
  44728. BABYLON.serializeAsTexture(),
  44729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44730. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44731. __decorate([
  44732. BABYLON.serializeAsColor3("emissive"),
  44733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44734. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44735. __decorate([
  44736. BABYLON.serializeAsTexture(),
  44737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44738. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44739. __decorate([
  44740. BABYLON.serialize(),
  44741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44742. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44743. __decorate([
  44744. BABYLON.serializeAsTexture(),
  44745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44746. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44747. __decorate([
  44748. BABYLON.serialize(),
  44749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44750. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44751. __decorate([
  44752. BABYLON.serialize()
  44753. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44754. __decorate([
  44755. BABYLON.serializeAsTexture(),
  44756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44757. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44758. __decorate([
  44759. BABYLON.serialize(),
  44760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44761. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44762. return PBRBaseSimpleMaterial;
  44763. }(BABYLON.PBRBaseMaterial));
  44764. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44765. })(BABYLON || (BABYLON = {}));
  44766. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44767. var BABYLON;
  44768. (function (BABYLON) {
  44769. /**
  44770. * The Physically based material of BJS.
  44771. *
  44772. * This offers the main features of a standard PBR material.
  44773. * For more information, please refer to the documentation :
  44774. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44775. */
  44776. var PBRMaterial = /** @class */ (function (_super) {
  44777. __extends(PBRMaterial, _super);
  44778. /**
  44779. * Instantiates a new PBRMaterial instance.
  44780. *
  44781. * @param name The material name
  44782. * @param scene The scene the material will be use in.
  44783. */
  44784. function PBRMaterial(name, scene) {
  44785. var _this = _super.call(this, name, scene) || this;
  44786. /**
  44787. * Intensity of the direct lights e.g. the four lights available in your scene.
  44788. * This impacts both the direct diffuse and specular highlights.
  44789. */
  44790. _this.directIntensity = 1.0;
  44791. /**
  44792. * Intensity of the emissive part of the material.
  44793. * This helps controlling the emissive effect without modifying the emissive color.
  44794. */
  44795. _this.emissiveIntensity = 1.0;
  44796. /**
  44797. * Intensity of the environment e.g. how much the environment will light the object
  44798. * either through harmonics for rough material or through the refelction for shiny ones.
  44799. */
  44800. _this.environmentIntensity = 1.0;
  44801. /**
  44802. * This is a special control allowing the reduction of the specular highlights coming from the
  44803. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44804. */
  44805. _this.specularIntensity = 1.0;
  44806. /**
  44807. * Debug Control allowing disabling the bump map on this material.
  44808. */
  44809. _this.disableBumpMap = false;
  44810. /**
  44811. * AKA Occlusion Texture Intensity in other nomenclature.
  44812. */
  44813. _this.ambientTextureStrength = 1.0;
  44814. /**
  44815. * The color of a material in ambient lighting.
  44816. */
  44817. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44818. /**
  44819. * AKA Diffuse Color in other nomenclature.
  44820. */
  44821. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44822. /**
  44823. * AKA Specular Color in other nomenclature.
  44824. */
  44825. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44826. /**
  44827. * The color reflected from the material.
  44828. */
  44829. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44830. /**
  44831. * The color emitted from the material.
  44832. */
  44833. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44834. /**
  44835. * AKA Glossiness in other nomenclature.
  44836. */
  44837. _this.microSurface = 1.0;
  44838. /**
  44839. * source material index of refraction (IOR)' / 'destination material IOR.
  44840. */
  44841. _this.indexOfRefraction = 0.66;
  44842. /**
  44843. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44844. */
  44845. _this.invertRefractionY = false;
  44846. /**
  44847. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44848. * Materials half opaque for instance using refraction could benefit from this control.
  44849. */
  44850. _this.linkRefractionWithTransparency = false;
  44851. _this.useLightmapAsShadowmap = false;
  44852. /**
  44853. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44854. */
  44855. _this.useAlphaFromAlbedoTexture = false;
  44856. /**
  44857. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44858. */
  44859. _this.forceAlphaTest = false;
  44860. /**
  44861. * Defines the alpha limits in alpha test mode.
  44862. */
  44863. _this.alphaCutOff = 0.4;
  44864. /**
  44865. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44866. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44867. */
  44868. _this.useSpecularOverAlpha = true;
  44869. /**
  44870. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44871. */
  44872. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44873. /**
  44874. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44875. */
  44876. _this.useRoughnessFromMetallicTextureAlpha = true;
  44877. /**
  44878. * Specifies if the metallic texture contains the roughness information in its green channel.
  44879. */
  44880. _this.useRoughnessFromMetallicTextureGreen = false;
  44881. /**
  44882. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44883. */
  44884. _this.useMetallnessFromMetallicTextureBlue = false;
  44885. /**
  44886. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44887. */
  44888. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44889. /**
  44890. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44891. */
  44892. _this.useAmbientInGrayScale = false;
  44893. /**
  44894. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44895. * The material will try to infer what glossiness each pixel should be.
  44896. */
  44897. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44898. /**
  44899. * BJS is using an harcoded light falloff based on a manually sets up range.
  44900. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44901. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44902. */
  44903. _this.usePhysicalLightFalloff = true;
  44904. /**
  44905. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44906. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44907. */
  44908. _this.useRadianceOverAlpha = true;
  44909. /**
  44910. * Allows using an object space normal map (instead of tangent space).
  44911. */
  44912. _this.useObjectSpaceNormalMap = false;
  44913. /**
  44914. * Allows using the bump map in parallax mode.
  44915. */
  44916. _this.useParallax = false;
  44917. /**
  44918. * Allows using the bump map in parallax occlusion mode.
  44919. */
  44920. _this.useParallaxOcclusion = false;
  44921. /**
  44922. * Controls the scale bias of the parallax mode.
  44923. */
  44924. _this.parallaxScaleBias = 0.05;
  44925. /**
  44926. * If sets to true, disables all the lights affecting the material.
  44927. */
  44928. _this.disableLighting = false;
  44929. /**
  44930. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44931. */
  44932. _this.forceIrradianceInFragment = false;
  44933. /**
  44934. * Number of Simultaneous lights allowed on the material.
  44935. */
  44936. _this.maxSimultaneousLights = 4;
  44937. /**
  44938. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44939. */
  44940. _this.invertNormalMapX = false;
  44941. /**
  44942. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44943. */
  44944. _this.invertNormalMapY = false;
  44945. /**
  44946. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44947. */
  44948. _this.twoSidedLighting = false;
  44949. /**
  44950. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44951. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44952. */
  44953. _this.useAlphaFresnel = false;
  44954. /**
  44955. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44956. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44957. */
  44958. _this.useLinearAlphaFresnel = false;
  44959. /**
  44960. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44961. * And/Or occlude the blended part.
  44962. */
  44963. _this.environmentBRDFTexture = null;
  44964. /**
  44965. * Force normal to face away from face.
  44966. */
  44967. _this.forceNormalForward = false;
  44968. /**
  44969. * Enables specular anti aliasing in the PBR shader.
  44970. * It will both interacts on the Geometry for analytical and IBL lighting.
  44971. * It also prefilter the roughness map based on the bump values.
  44972. */
  44973. _this.enableSpecularAntiAliasing = false;
  44974. /**
  44975. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44976. * makes the reflect vector face the model (under horizon).
  44977. */
  44978. _this.useHorizonOcclusion = true;
  44979. /**
  44980. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44981. * too much the area relying on ambient texture to define their ambient occlusion.
  44982. */
  44983. _this.useRadianceOcclusion = true;
  44984. /**
  44985. * If set to true, no lighting calculations will be applied.
  44986. */
  44987. _this.unlit = false;
  44988. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44989. return _this;
  44990. }
  44991. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44992. /**
  44993. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44994. */
  44995. get: function () {
  44996. return this._PBRMATERIAL_OPAQUE;
  44997. },
  44998. enumerable: true,
  44999. configurable: true
  45000. });
  45001. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45002. /**
  45003. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45004. */
  45005. get: function () {
  45006. return this._PBRMATERIAL_ALPHATEST;
  45007. },
  45008. enumerable: true,
  45009. configurable: true
  45010. });
  45011. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45012. /**
  45013. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45014. */
  45015. get: function () {
  45016. return this._PBRMATERIAL_ALPHABLEND;
  45017. },
  45018. enumerable: true,
  45019. configurable: true
  45020. });
  45021. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45022. /**
  45023. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45024. * They are also discarded below the alpha cutoff threshold to improve performances.
  45025. */
  45026. get: function () {
  45027. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45028. },
  45029. enumerable: true,
  45030. configurable: true
  45031. });
  45032. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45033. /**
  45034. * Gets the image processing configuration used either in this material.
  45035. */
  45036. get: function () {
  45037. return this._imageProcessingConfiguration;
  45038. },
  45039. /**
  45040. * Sets the Default image processing configuration used either in the this material.
  45041. *
  45042. * If sets to null, the scene one is in use.
  45043. */
  45044. set: function (value) {
  45045. this._attachImageProcessingConfiguration(value);
  45046. // Ensure the effect will be rebuilt.
  45047. this._markAllSubMeshesAsTexturesDirty();
  45048. },
  45049. enumerable: true,
  45050. configurable: true
  45051. });
  45052. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45053. /**
  45054. * Gets wether the color curves effect is enabled.
  45055. */
  45056. get: function () {
  45057. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45058. },
  45059. /**
  45060. * Sets wether the color curves effect is enabled.
  45061. */
  45062. set: function (value) {
  45063. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45064. },
  45065. enumerable: true,
  45066. configurable: true
  45067. });
  45068. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45069. /**
  45070. * Gets wether the color grading effect is enabled.
  45071. */
  45072. get: function () {
  45073. return this.imageProcessingConfiguration.colorGradingEnabled;
  45074. },
  45075. /**
  45076. * Gets wether the color grading effect is enabled.
  45077. */
  45078. set: function (value) {
  45079. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45080. },
  45081. enumerable: true,
  45082. configurable: true
  45083. });
  45084. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45085. /**
  45086. * Gets wether tonemapping is enabled or not.
  45087. */
  45088. get: function () {
  45089. return this._imageProcessingConfiguration.toneMappingEnabled;
  45090. },
  45091. /**
  45092. * Sets wether tonemapping is enabled or not
  45093. */
  45094. set: function (value) {
  45095. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45096. },
  45097. enumerable: true,
  45098. configurable: true
  45099. });
  45100. ;
  45101. ;
  45102. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45103. /**
  45104. * The camera exposure used on this material.
  45105. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45106. * This corresponds to a photographic exposure.
  45107. */
  45108. get: function () {
  45109. return this._imageProcessingConfiguration.exposure;
  45110. },
  45111. /**
  45112. * The camera exposure used on this material.
  45113. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45114. * This corresponds to a photographic exposure.
  45115. */
  45116. set: function (value) {
  45117. this._imageProcessingConfiguration.exposure = value;
  45118. },
  45119. enumerable: true,
  45120. configurable: true
  45121. });
  45122. ;
  45123. ;
  45124. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45125. /**
  45126. * Gets The camera contrast used on this material.
  45127. */
  45128. get: function () {
  45129. return this._imageProcessingConfiguration.contrast;
  45130. },
  45131. /**
  45132. * Sets The camera contrast used on this material.
  45133. */
  45134. set: function (value) {
  45135. this._imageProcessingConfiguration.contrast = value;
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45141. /**
  45142. * Gets the Color Grading 2D Lookup Texture.
  45143. */
  45144. get: function () {
  45145. return this._imageProcessingConfiguration.colorGradingTexture;
  45146. },
  45147. /**
  45148. * Sets the Color Grading 2D Lookup Texture.
  45149. */
  45150. set: function (value) {
  45151. this._imageProcessingConfiguration.colorGradingTexture = value;
  45152. },
  45153. enumerable: true,
  45154. configurable: true
  45155. });
  45156. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45157. /**
  45158. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45159. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45160. * 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;
  45161. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45162. */
  45163. get: function () {
  45164. return this._imageProcessingConfiguration.colorCurves;
  45165. },
  45166. /**
  45167. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45168. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45169. * 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;
  45170. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45171. */
  45172. set: function (value) {
  45173. this._imageProcessingConfiguration.colorCurves = value;
  45174. },
  45175. enumerable: true,
  45176. configurable: true
  45177. });
  45178. /**
  45179. * Returns the name of this material class.
  45180. */
  45181. PBRMaterial.prototype.getClassName = function () {
  45182. return "PBRMaterial";
  45183. };
  45184. /**
  45185. * Returns an array of the actively used textures.
  45186. * @returns - Array of BaseTextures
  45187. */
  45188. PBRMaterial.prototype.getActiveTextures = function () {
  45189. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45190. if (this._albedoTexture) {
  45191. activeTextures.push(this._albedoTexture);
  45192. }
  45193. if (this._ambientTexture) {
  45194. activeTextures.push(this._ambientTexture);
  45195. }
  45196. if (this._opacityTexture) {
  45197. activeTextures.push(this._opacityTexture);
  45198. }
  45199. if (this._reflectionTexture) {
  45200. activeTextures.push(this._reflectionTexture);
  45201. }
  45202. if (this._emissiveTexture) {
  45203. activeTextures.push(this._emissiveTexture);
  45204. }
  45205. if (this._reflectivityTexture) {
  45206. activeTextures.push(this._reflectivityTexture);
  45207. }
  45208. if (this._metallicTexture) {
  45209. activeTextures.push(this._metallicTexture);
  45210. }
  45211. if (this._microSurfaceTexture) {
  45212. activeTextures.push(this._microSurfaceTexture);
  45213. }
  45214. if (this._bumpTexture) {
  45215. activeTextures.push(this._bumpTexture);
  45216. }
  45217. if (this._lightmapTexture) {
  45218. activeTextures.push(this._lightmapTexture);
  45219. }
  45220. if (this._refractionTexture) {
  45221. activeTextures.push(this._refractionTexture);
  45222. }
  45223. return activeTextures;
  45224. };
  45225. /**
  45226. * Checks to see if a texture is used in the material.
  45227. * @param texture - Base texture to use.
  45228. * @returns - Boolean specifying if a texture is used in the material.
  45229. */
  45230. PBRMaterial.prototype.hasTexture = function (texture) {
  45231. if (_super.prototype.hasTexture.call(this, texture)) {
  45232. return true;
  45233. }
  45234. if (this._albedoTexture === texture) {
  45235. return true;
  45236. }
  45237. if (this._ambientTexture === texture) {
  45238. return true;
  45239. }
  45240. if (this._opacityTexture === texture) {
  45241. return true;
  45242. }
  45243. if (this._reflectionTexture === texture) {
  45244. return true;
  45245. }
  45246. if (this._reflectivityTexture === texture) {
  45247. return true;
  45248. }
  45249. if (this._metallicTexture === texture) {
  45250. return true;
  45251. }
  45252. if (this._microSurfaceTexture === texture) {
  45253. return true;
  45254. }
  45255. if (this._bumpTexture === texture) {
  45256. return true;
  45257. }
  45258. if (this._lightmapTexture === texture) {
  45259. return true;
  45260. }
  45261. if (this._refractionTexture === texture) {
  45262. return true;
  45263. }
  45264. return false;
  45265. };
  45266. /**
  45267. * Makes a duplicate of the current material.
  45268. * @param name - name to use for the new material.
  45269. */
  45270. PBRMaterial.prototype.clone = function (name) {
  45271. var _this = this;
  45272. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45273. clone.id = name;
  45274. clone.name = name;
  45275. return clone;
  45276. };
  45277. /**
  45278. * Serializes this PBR Material.
  45279. * @returns - An object with the serialized material.
  45280. */
  45281. PBRMaterial.prototype.serialize = function () {
  45282. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45283. serializationObject.customType = "BABYLON.PBRMaterial";
  45284. return serializationObject;
  45285. };
  45286. // Statics
  45287. /**
  45288. * Parses a PBR Material from a serialized object.
  45289. * @param source - Serialized object.
  45290. * @param scene - BJS scene instance.
  45291. * @param rootUrl - url for the scene object
  45292. * @returns - PBRMaterial
  45293. */
  45294. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45295. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45296. };
  45297. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45298. /**
  45299. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45300. */
  45301. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45302. /**
  45303. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45304. */
  45305. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45306. /**
  45307. * 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.
  45308. * They are also discarded below the alpha cutoff threshold to improve performances.
  45309. */
  45310. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45311. __decorate([
  45312. BABYLON.serialize(),
  45313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45314. ], PBRMaterial.prototype, "directIntensity", void 0);
  45315. __decorate([
  45316. BABYLON.serialize(),
  45317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45318. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45319. __decorate([
  45320. BABYLON.serialize(),
  45321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45322. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45323. __decorate([
  45324. BABYLON.serialize(),
  45325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45326. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45327. __decorate([
  45328. BABYLON.serialize(),
  45329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45330. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45331. __decorate([
  45332. BABYLON.serializeAsTexture(),
  45333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45334. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45335. __decorate([
  45336. BABYLON.serializeAsTexture(),
  45337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45338. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45339. __decorate([
  45340. BABYLON.serialize(),
  45341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45342. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45343. __decorate([
  45344. BABYLON.serializeAsTexture(),
  45345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45346. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45347. __decorate([
  45348. BABYLON.serializeAsTexture(),
  45349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45350. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45351. __decorate([
  45352. BABYLON.serializeAsTexture(),
  45353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45354. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45355. __decorate([
  45356. BABYLON.serializeAsTexture(),
  45357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45358. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45359. __decorate([
  45360. BABYLON.serializeAsTexture(),
  45361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45362. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45363. __decorate([
  45364. BABYLON.serialize(),
  45365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45366. ], PBRMaterial.prototype, "metallic", void 0);
  45367. __decorate([
  45368. BABYLON.serialize(),
  45369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45370. ], PBRMaterial.prototype, "roughness", void 0);
  45371. __decorate([
  45372. BABYLON.serializeAsTexture(),
  45373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45374. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45375. __decorate([
  45376. BABYLON.serializeAsTexture(),
  45377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45378. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45379. __decorate([
  45380. BABYLON.serializeAsTexture(),
  45381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45382. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45383. __decorate([
  45384. BABYLON.serializeAsTexture(),
  45385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45386. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45387. __decorate([
  45388. BABYLON.serializeAsColor3("ambient"),
  45389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45390. ], PBRMaterial.prototype, "ambientColor", void 0);
  45391. __decorate([
  45392. BABYLON.serializeAsColor3("albedo"),
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45394. ], PBRMaterial.prototype, "albedoColor", void 0);
  45395. __decorate([
  45396. BABYLON.serializeAsColor3("reflectivity"),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45398. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45399. __decorate([
  45400. BABYLON.serializeAsColor3("reflection"),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45402. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45403. __decorate([
  45404. BABYLON.serializeAsColor3("emissive"),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45407. __decorate([
  45408. BABYLON.serialize(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRMaterial.prototype, "microSurface", void 0);
  45411. __decorate([
  45412. BABYLON.serialize(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45415. __decorate([
  45416. BABYLON.serialize(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45418. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45419. __decorate([
  45420. BABYLON.serialize(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45423. __decorate([
  45424. BABYLON.serialize(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45426. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45427. __decorate([
  45428. BABYLON.serialize(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45430. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45431. __decorate([
  45432. BABYLON.serialize(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45434. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45435. __decorate([
  45436. BABYLON.serialize(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45438. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45439. __decorate([
  45440. BABYLON.serialize(),
  45441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45442. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45443. __decorate([
  45444. BABYLON.serialize(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45446. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45447. __decorate([
  45448. BABYLON.serialize(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45451. __decorate([
  45452. BABYLON.serialize(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45455. __decorate([
  45456. BABYLON.serialize(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45459. __decorate([
  45460. BABYLON.serialize(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45463. __decorate([
  45464. BABYLON.serialize(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45467. __decorate([
  45468. BABYLON.serialize(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45471. __decorate([
  45472. BABYLON.serialize(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45475. __decorate([
  45476. BABYLON.serialize(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45479. __decorate([
  45480. BABYLON.serialize(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45483. __decorate([
  45484. BABYLON.serialize(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "useParallax", void 0);
  45487. __decorate([
  45488. BABYLON.serialize(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45491. __decorate([
  45492. BABYLON.serialize(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45494. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45495. __decorate([
  45496. BABYLON.serialize(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45498. ], PBRMaterial.prototype, "disableLighting", void 0);
  45499. __decorate([
  45500. BABYLON.serialize(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45503. __decorate([
  45504. BABYLON.serialize(),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45506. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45507. __decorate([
  45508. BABYLON.serialize(),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45510. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45511. __decorate([
  45512. BABYLON.serialize(),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45514. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45515. __decorate([
  45516. BABYLON.serialize(),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45518. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45519. __decorate([
  45520. BABYLON.serialize(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45523. __decorate([
  45524. BABYLON.serialize(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45527. __decorate([
  45528. BABYLON.serializeAsTexture(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45531. __decorate([
  45532. BABYLON.serialize(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45535. __decorate([
  45536. BABYLON.serialize(),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45539. __decorate([
  45540. BABYLON.serialize(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45543. __decorate([
  45544. BABYLON.serialize(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45550. ], PBRMaterial.prototype, "unlit", void 0);
  45551. return PBRMaterial;
  45552. }(BABYLON.PBRBaseMaterial));
  45553. BABYLON.PBRMaterial = PBRMaterial;
  45554. })(BABYLON || (BABYLON = {}));
  45555. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45556. var BABYLON;
  45557. (function (BABYLON) {
  45558. /**
  45559. * The PBR material of BJS following the metal roughness convention.
  45560. *
  45561. * This fits to the PBR convention in the GLTF definition:
  45562. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45563. */
  45564. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45565. __extends(PBRMetallicRoughnessMaterial, _super);
  45566. /**
  45567. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45568. *
  45569. * @param name The material name
  45570. * @param scene The scene the material will be use in.
  45571. */
  45572. function PBRMetallicRoughnessMaterial(name, scene) {
  45573. var _this = _super.call(this, name, scene) || this;
  45574. _this._useRoughnessFromMetallicTextureAlpha = false;
  45575. _this._useRoughnessFromMetallicTextureGreen = true;
  45576. _this._useMetallnessFromMetallicTextureBlue = true;
  45577. _this.metallic = 1.0;
  45578. _this.roughness = 1.0;
  45579. return _this;
  45580. }
  45581. /**
  45582. * Return the currrent class name of the material.
  45583. */
  45584. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45585. return "PBRMetallicRoughnessMaterial";
  45586. };
  45587. /**
  45588. * Return the active textures of the material.
  45589. */
  45590. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45591. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45592. if (this.baseTexture) {
  45593. activeTextures.push(this.baseTexture);
  45594. }
  45595. if (this.metallicRoughnessTexture) {
  45596. activeTextures.push(this.metallicRoughnessTexture);
  45597. }
  45598. return activeTextures;
  45599. };
  45600. /**
  45601. * Checks to see if a texture is used in the material.
  45602. * @param texture - Base texture to use.
  45603. * @returns - Boolean specifying if a texture is used in the material.
  45604. */
  45605. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45606. if (_super.prototype.hasTexture.call(this, texture)) {
  45607. return true;
  45608. }
  45609. if (this.baseTexture === texture) {
  45610. return true;
  45611. }
  45612. if (this.metallicRoughnessTexture === texture) {
  45613. return true;
  45614. }
  45615. return false;
  45616. };
  45617. /**
  45618. * Makes a duplicate of the current material.
  45619. * @param name - name to use for the new material.
  45620. */
  45621. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45622. var _this = this;
  45623. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45624. clone.id = name;
  45625. clone.name = name;
  45626. return clone;
  45627. };
  45628. /**
  45629. * Serialize the material to a parsable JSON object.
  45630. */
  45631. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45632. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45633. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45634. return serializationObject;
  45635. };
  45636. /**
  45637. * Parses a JSON object correponding to the serialize function.
  45638. */
  45639. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45640. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45641. };
  45642. __decorate([
  45643. BABYLON.serializeAsColor3(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45645. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45646. __decorate([
  45647. BABYLON.serializeAsTexture(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45649. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45658. __decorate([
  45659. BABYLON.serializeAsTexture(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45661. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45662. return PBRMetallicRoughnessMaterial;
  45663. }(BABYLON.PBRBaseSimpleMaterial));
  45664. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45665. })(BABYLON || (BABYLON = {}));
  45666. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45667. var BABYLON;
  45668. (function (BABYLON) {
  45669. /**
  45670. * The PBR material of BJS following the specular glossiness convention.
  45671. *
  45672. * This fits to the PBR convention in the GLTF definition:
  45673. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45674. */
  45675. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45676. __extends(PBRSpecularGlossinessMaterial, _super);
  45677. /**
  45678. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45679. *
  45680. * @param name The material name
  45681. * @param scene The scene the material will be use in.
  45682. */
  45683. function PBRSpecularGlossinessMaterial(name, scene) {
  45684. var _this = _super.call(this, name, scene) || this;
  45685. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45686. return _this;
  45687. }
  45688. /**
  45689. * Return the currrent class name of the material.
  45690. */
  45691. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45692. return "PBRSpecularGlossinessMaterial";
  45693. };
  45694. /**
  45695. * Return the active textures of the material.
  45696. */
  45697. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45698. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45699. if (this.diffuseTexture) {
  45700. activeTextures.push(this.diffuseTexture);
  45701. }
  45702. if (this.specularGlossinessTexture) {
  45703. activeTextures.push(this.specularGlossinessTexture);
  45704. }
  45705. return activeTextures;
  45706. };
  45707. /**
  45708. * Checks to see if a texture is used in the material.
  45709. * @param texture - Base texture to use.
  45710. * @returns - Boolean specifying if a texture is used in the material.
  45711. */
  45712. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45713. if (_super.prototype.hasTexture.call(this, texture)) {
  45714. return true;
  45715. }
  45716. if (this.diffuseTexture === texture) {
  45717. return true;
  45718. }
  45719. if (this.specularGlossinessTexture === texture) {
  45720. return true;
  45721. }
  45722. return false;
  45723. };
  45724. /**
  45725. * Makes a duplicate of the current material.
  45726. * @param name - name to use for the new material.
  45727. */
  45728. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45729. var _this = this;
  45730. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45731. clone.id = name;
  45732. clone.name = name;
  45733. return clone;
  45734. };
  45735. /**
  45736. * Serialize the material to a parsable JSON object.
  45737. */
  45738. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45739. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45740. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45741. return serializationObject;
  45742. };
  45743. /**
  45744. * Parses a JSON object correponding to the serialize function.
  45745. */
  45746. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45747. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45748. };
  45749. __decorate([
  45750. BABYLON.serializeAsColor3("diffuse"),
  45751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45752. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45753. __decorate([
  45754. BABYLON.serializeAsTexture(),
  45755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45756. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45757. __decorate([
  45758. BABYLON.serializeAsColor3("specular"),
  45759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45760. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45761. __decorate([
  45762. BABYLON.serialize(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45764. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45765. __decorate([
  45766. BABYLON.serializeAsTexture(),
  45767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45768. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45769. return PBRSpecularGlossinessMaterial;
  45770. }(BABYLON.PBRBaseSimpleMaterial));
  45771. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45772. })(BABYLON || (BABYLON = {}));
  45773. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45774. var BABYLON;
  45775. (function (BABYLON) {
  45776. BABYLON.CameraInputTypes = {};
  45777. var CameraInputsManager = /** @class */ (function () {
  45778. function CameraInputsManager(camera) {
  45779. this.attached = {};
  45780. this.camera = camera;
  45781. this.checkInputs = function () { };
  45782. }
  45783. /**
  45784. * Add an input method to a camera
  45785. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45786. * @param input camera input method
  45787. */
  45788. CameraInputsManager.prototype.add = function (input) {
  45789. var type = input.getSimpleName();
  45790. if (this.attached[type]) {
  45791. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45792. return;
  45793. }
  45794. this.attached[type] = input;
  45795. input.camera = this.camera;
  45796. //for checkInputs, we are dynamically creating a function
  45797. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45798. if (input.checkInputs) {
  45799. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45800. }
  45801. if (this.attachedElement) {
  45802. input.attachControl(this.attachedElement);
  45803. }
  45804. };
  45805. /**
  45806. * Remove a specific input method from a camera
  45807. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45808. * @param inputToRemove camera input method
  45809. */
  45810. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45811. for (var cam in this.attached) {
  45812. var input = this.attached[cam];
  45813. if (input === inputToRemove) {
  45814. input.detachControl(this.attachedElement);
  45815. input.camera = null;
  45816. delete this.attached[cam];
  45817. this.rebuildInputCheck();
  45818. }
  45819. }
  45820. };
  45821. CameraInputsManager.prototype.removeByType = function (inputType) {
  45822. for (var cam in this.attached) {
  45823. var input = this.attached[cam];
  45824. if (input.getClassName() === inputType) {
  45825. input.detachControl(this.attachedElement);
  45826. input.camera = null;
  45827. delete this.attached[cam];
  45828. this.rebuildInputCheck();
  45829. }
  45830. }
  45831. };
  45832. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45833. var current = this.checkInputs;
  45834. return function () {
  45835. current();
  45836. fn();
  45837. };
  45838. };
  45839. CameraInputsManager.prototype.attachInput = function (input) {
  45840. if (this.attachedElement) {
  45841. input.attachControl(this.attachedElement, this.noPreventDefault);
  45842. }
  45843. };
  45844. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45845. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45846. if (this.attachedElement) {
  45847. return;
  45848. }
  45849. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45850. this.attachedElement = element;
  45851. this.noPreventDefault = noPreventDefault;
  45852. for (var cam in this.attached) {
  45853. this.attached[cam].attachControl(element, noPreventDefault);
  45854. }
  45855. };
  45856. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45857. if (disconnect === void 0) { disconnect = false; }
  45858. if (this.attachedElement !== element) {
  45859. return;
  45860. }
  45861. for (var cam in this.attached) {
  45862. this.attached[cam].detachControl(element);
  45863. if (disconnect) {
  45864. this.attached[cam].camera = null;
  45865. }
  45866. }
  45867. this.attachedElement = null;
  45868. };
  45869. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45870. this.checkInputs = function () { };
  45871. for (var cam in this.attached) {
  45872. var input = this.attached[cam];
  45873. if (input.checkInputs) {
  45874. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45875. }
  45876. }
  45877. };
  45878. /**
  45879. * Remove all attached input methods from a camera
  45880. */
  45881. CameraInputsManager.prototype.clear = function () {
  45882. if (this.attachedElement) {
  45883. this.detachElement(this.attachedElement, true);
  45884. }
  45885. this.attached = {};
  45886. this.attachedElement = null;
  45887. this.checkInputs = function () { };
  45888. };
  45889. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45890. var inputs = {};
  45891. for (var cam in this.attached) {
  45892. var input = this.attached[cam];
  45893. var res = BABYLON.SerializationHelper.Serialize(input);
  45894. inputs[input.getClassName()] = res;
  45895. }
  45896. serializedCamera.inputsmgr = inputs;
  45897. };
  45898. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45899. var parsedInputs = parsedCamera.inputsmgr;
  45900. if (parsedInputs) {
  45901. this.clear();
  45902. for (var n in parsedInputs) {
  45903. var construct = BABYLON.CameraInputTypes[n];
  45904. if (construct) {
  45905. var parsedinput = parsedInputs[n];
  45906. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45907. this.add(input);
  45908. }
  45909. }
  45910. }
  45911. else {
  45912. //2016-03-08 this part is for managing backward compatibility
  45913. for (var n in this.attached) {
  45914. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45915. if (construct) {
  45916. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45917. this.remove(this.attached[n]);
  45918. this.add(input);
  45919. }
  45920. }
  45921. }
  45922. };
  45923. return CameraInputsManager;
  45924. }());
  45925. BABYLON.CameraInputsManager = CameraInputsManager;
  45926. })(BABYLON || (BABYLON = {}));
  45927. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45928. var BABYLON;
  45929. (function (BABYLON) {
  45930. var TargetCamera = /** @class */ (function (_super) {
  45931. __extends(TargetCamera, _super);
  45932. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45933. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45934. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45935. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45936. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45937. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45938. _this.speed = 2.0;
  45939. _this.noRotationConstraint = false;
  45940. _this.lockedTarget = null;
  45941. _this._currentTarget = BABYLON.Vector3.Zero();
  45942. _this._viewMatrix = BABYLON.Matrix.Zero();
  45943. _this._camMatrix = BABYLON.Matrix.Zero();
  45944. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45945. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45946. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45947. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45948. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45949. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45950. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45951. return _this;
  45952. }
  45953. TargetCamera.prototype.getFrontPosition = function (distance) {
  45954. this.getWorldMatrix();
  45955. var direction = this.getTarget().subtract(this.position);
  45956. direction.normalize();
  45957. direction.scaleInPlace(distance);
  45958. return this.globalPosition.add(direction);
  45959. };
  45960. TargetCamera.prototype._getLockedTargetPosition = function () {
  45961. if (!this.lockedTarget) {
  45962. return null;
  45963. }
  45964. if (this.lockedTarget.absolutePosition) {
  45965. this.lockedTarget.computeWorldMatrix();
  45966. }
  45967. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45968. };
  45969. TargetCamera.prototype.storeState = function () {
  45970. this._storedPosition = this.position.clone();
  45971. this._storedRotation = this.rotation.clone();
  45972. if (this.rotationQuaternion) {
  45973. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45974. }
  45975. return _super.prototype.storeState.call(this);
  45976. };
  45977. /**
  45978. * Restored camera state. You must call storeState() first
  45979. */
  45980. TargetCamera.prototype._restoreStateValues = function () {
  45981. if (!_super.prototype._restoreStateValues.call(this)) {
  45982. return false;
  45983. }
  45984. this.position = this._storedPosition.clone();
  45985. this.rotation = this._storedRotation.clone();
  45986. if (this.rotationQuaternion) {
  45987. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45988. }
  45989. this.cameraDirection.copyFromFloats(0, 0, 0);
  45990. this.cameraRotation.copyFromFloats(0, 0);
  45991. return true;
  45992. };
  45993. // Cache
  45994. TargetCamera.prototype._initCache = function () {
  45995. _super.prototype._initCache.call(this);
  45996. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45997. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45998. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45999. };
  46000. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46001. if (!ignoreParentClass) {
  46002. _super.prototype._updateCache.call(this);
  46003. }
  46004. var lockedTargetPosition = this._getLockedTargetPosition();
  46005. if (!lockedTargetPosition) {
  46006. this._cache.lockedTarget = null;
  46007. }
  46008. else {
  46009. if (!this._cache.lockedTarget) {
  46010. this._cache.lockedTarget = lockedTargetPosition.clone();
  46011. }
  46012. else {
  46013. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46014. }
  46015. }
  46016. this._cache.rotation.copyFrom(this.rotation);
  46017. if (this.rotationQuaternion)
  46018. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46019. };
  46020. // Synchronized
  46021. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46022. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46023. return false;
  46024. }
  46025. var lockedTargetPosition = this._getLockedTargetPosition();
  46026. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46027. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46028. };
  46029. // Methods
  46030. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46031. var engine = this.getEngine();
  46032. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46033. };
  46034. // Target
  46035. TargetCamera.prototype.setTarget = function (target) {
  46036. this.upVector.normalize();
  46037. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46038. this._camMatrix.invert();
  46039. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46040. var vDir = target.subtract(this.position);
  46041. if (vDir.x >= 0.0) {
  46042. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46043. }
  46044. else {
  46045. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46046. }
  46047. this.rotation.z = 0;
  46048. if (isNaN(this.rotation.x)) {
  46049. this.rotation.x = 0;
  46050. }
  46051. if (isNaN(this.rotation.y)) {
  46052. this.rotation.y = 0;
  46053. }
  46054. if (isNaN(this.rotation.z)) {
  46055. this.rotation.z = 0;
  46056. }
  46057. if (this.rotationQuaternion) {
  46058. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46059. }
  46060. };
  46061. /**
  46062. * Return the current target position of the camera. This value is expressed in local space.
  46063. */
  46064. TargetCamera.prototype.getTarget = function () {
  46065. return this._currentTarget;
  46066. };
  46067. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46068. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46069. };
  46070. TargetCamera.prototype._updatePosition = function () {
  46071. if (this.parent) {
  46072. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46073. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46074. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46075. return;
  46076. }
  46077. this.position.addInPlace(this.cameraDirection);
  46078. };
  46079. TargetCamera.prototype._checkInputs = function () {
  46080. var needToMove = this._decideIfNeedsToMove();
  46081. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46082. // Move
  46083. if (needToMove) {
  46084. this._updatePosition();
  46085. }
  46086. // Rotate
  46087. if (needToRotate) {
  46088. this.rotation.x += this.cameraRotation.x;
  46089. this.rotation.y += this.cameraRotation.y;
  46090. //rotate, if quaternion is set and rotation was used
  46091. if (this.rotationQuaternion) {
  46092. var len = this.rotation.lengthSquared();
  46093. if (len) {
  46094. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46095. }
  46096. }
  46097. if (!this.noRotationConstraint) {
  46098. var limit = (Math.PI / 2) * 0.95;
  46099. if (this.rotation.x > limit)
  46100. this.rotation.x = limit;
  46101. if (this.rotation.x < -limit)
  46102. this.rotation.x = -limit;
  46103. }
  46104. }
  46105. // Inertia
  46106. if (needToMove) {
  46107. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46108. this.cameraDirection.x = 0;
  46109. }
  46110. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46111. this.cameraDirection.y = 0;
  46112. }
  46113. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46114. this.cameraDirection.z = 0;
  46115. }
  46116. this.cameraDirection.scaleInPlace(this.inertia);
  46117. }
  46118. if (needToRotate) {
  46119. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46120. this.cameraRotation.x = 0;
  46121. }
  46122. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46123. this.cameraRotation.y = 0;
  46124. }
  46125. this.cameraRotation.scaleInPlace(this.inertia);
  46126. }
  46127. _super.prototype._checkInputs.call(this);
  46128. };
  46129. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46130. if (this.rotationQuaternion) {
  46131. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46132. }
  46133. else {
  46134. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46135. }
  46136. //update the up vector!
  46137. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46138. };
  46139. TargetCamera.prototype._getViewMatrix = function () {
  46140. if (this.lockedTarget) {
  46141. this.setTarget(this._getLockedTargetPosition());
  46142. }
  46143. // Compute
  46144. this._updateCameraRotationMatrix();
  46145. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46146. // Computing target and final matrix
  46147. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46148. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46149. return this._viewMatrix;
  46150. };
  46151. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46152. if (this.parent) {
  46153. var parentWorldMatrix = this.parent.getWorldMatrix();
  46154. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46155. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46156. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46157. this._markSyncedWithParent();
  46158. }
  46159. else {
  46160. this._globalPosition.copyFrom(this.position);
  46161. this._globalCurrentTarget.copyFrom(target);
  46162. this._globalCurrentUpVector.copyFrom(up);
  46163. }
  46164. if (this.getScene().useRightHandedSystem) {
  46165. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46166. }
  46167. else {
  46168. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46169. }
  46170. };
  46171. /**
  46172. * @override
  46173. * Override Camera.createRigCamera
  46174. */
  46175. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46176. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46177. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46178. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46179. if (!this.rotationQuaternion) {
  46180. this.rotationQuaternion = new BABYLON.Quaternion();
  46181. }
  46182. rigCamera._cameraRigParams = {};
  46183. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46184. }
  46185. return rigCamera;
  46186. }
  46187. return null;
  46188. };
  46189. /**
  46190. * @override
  46191. * Override Camera._updateRigCameras
  46192. */
  46193. TargetCamera.prototype._updateRigCameras = function () {
  46194. var camLeft = this._rigCameras[0];
  46195. var camRight = this._rigCameras[1];
  46196. switch (this.cameraRigMode) {
  46197. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46198. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46199. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46200. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46201. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46202. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46203. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46204. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46205. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46206. camLeft.setTarget(this.getTarget());
  46207. camRight.setTarget(this.getTarget());
  46208. break;
  46209. case BABYLON.Camera.RIG_MODE_VR:
  46210. if (camLeft.rotationQuaternion) {
  46211. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46212. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46213. }
  46214. else {
  46215. camLeft.rotation.copyFrom(this.rotation);
  46216. camRight.rotation.copyFrom(this.rotation);
  46217. }
  46218. camLeft.position.copyFrom(this.position);
  46219. camRight.position.copyFrom(this.position);
  46220. break;
  46221. }
  46222. _super.prototype._updateRigCameras.call(this);
  46223. };
  46224. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46225. if (!this._rigCamTransformMatrix) {
  46226. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46227. }
  46228. var target = this.getTarget();
  46229. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46230. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46231. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46232. };
  46233. TargetCamera.prototype.getClassName = function () {
  46234. return "TargetCamera";
  46235. };
  46236. __decorate([
  46237. BABYLON.serializeAsVector3()
  46238. ], TargetCamera.prototype, "rotation", void 0);
  46239. __decorate([
  46240. BABYLON.serialize()
  46241. ], TargetCamera.prototype, "speed", void 0);
  46242. __decorate([
  46243. BABYLON.serializeAsMeshReference("lockedTargetId")
  46244. ], TargetCamera.prototype, "lockedTarget", void 0);
  46245. return TargetCamera;
  46246. }(BABYLON.Camera));
  46247. BABYLON.TargetCamera = TargetCamera;
  46248. })(BABYLON || (BABYLON = {}));
  46249. //# sourceMappingURL=babylon.targetCamera.js.map
  46250. var BABYLON;
  46251. (function (BABYLON) {
  46252. var FreeCameraMouseInput = /** @class */ (function () {
  46253. function FreeCameraMouseInput(touchEnabled) {
  46254. if (touchEnabled === void 0) { touchEnabled = true; }
  46255. this.touchEnabled = touchEnabled;
  46256. this.buttons = [0, 1, 2];
  46257. this.angularSensibility = 2000.0;
  46258. this.previousPosition = null;
  46259. }
  46260. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46261. var _this = this;
  46262. var engine = this.camera.getEngine();
  46263. if (!this._pointerInput) {
  46264. this._pointerInput = function (p, s) {
  46265. var evt = p.event;
  46266. if (engine.isInVRExclusivePointerMode) {
  46267. return;
  46268. }
  46269. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46270. return;
  46271. }
  46272. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46273. return;
  46274. }
  46275. var srcElement = (evt.srcElement || evt.target);
  46276. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46277. try {
  46278. srcElement.setPointerCapture(evt.pointerId);
  46279. }
  46280. catch (e) {
  46281. //Nothing to do with the error. Execution will continue.
  46282. }
  46283. _this.previousPosition = {
  46284. x: evt.clientX,
  46285. y: evt.clientY
  46286. };
  46287. if (!noPreventDefault) {
  46288. evt.preventDefault();
  46289. element.focus();
  46290. }
  46291. }
  46292. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46293. try {
  46294. srcElement.releasePointerCapture(evt.pointerId);
  46295. }
  46296. catch (e) {
  46297. //Nothing to do with the error.
  46298. }
  46299. _this.previousPosition = null;
  46300. if (!noPreventDefault) {
  46301. evt.preventDefault();
  46302. }
  46303. }
  46304. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46305. if (!_this.previousPosition || engine.isPointerLock) {
  46306. return;
  46307. }
  46308. var offsetX = evt.clientX - _this.previousPosition.x;
  46309. if (_this.camera.getScene().useRightHandedSystem)
  46310. offsetX *= -1;
  46311. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46312. offsetX *= -1;
  46313. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46314. var offsetY = evt.clientY - _this.previousPosition.y;
  46315. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46316. _this.previousPosition = {
  46317. x: evt.clientX,
  46318. y: evt.clientY
  46319. };
  46320. if (!noPreventDefault) {
  46321. evt.preventDefault();
  46322. }
  46323. }
  46324. };
  46325. }
  46326. this._onMouseMove = function (evt) {
  46327. if (!engine.isPointerLock) {
  46328. return;
  46329. }
  46330. if (engine.isInVRExclusivePointerMode) {
  46331. return;
  46332. }
  46333. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46334. if (_this.camera.getScene().useRightHandedSystem)
  46335. offsetX *= -1;
  46336. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46337. offsetX *= -1;
  46338. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46339. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46340. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46341. _this.previousPosition = null;
  46342. if (!noPreventDefault) {
  46343. evt.preventDefault();
  46344. }
  46345. };
  46346. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46347. element.addEventListener("mousemove", this._onMouseMove, false);
  46348. };
  46349. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46350. if (this._observer && element) {
  46351. this.camera.getScene().onPointerObservable.remove(this._observer);
  46352. if (this._onMouseMove) {
  46353. element.removeEventListener("mousemove", this._onMouseMove);
  46354. }
  46355. this._observer = null;
  46356. this._onMouseMove = null;
  46357. this.previousPosition = null;
  46358. }
  46359. };
  46360. FreeCameraMouseInput.prototype.getClassName = function () {
  46361. return "FreeCameraMouseInput";
  46362. };
  46363. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46364. return "mouse";
  46365. };
  46366. __decorate([
  46367. BABYLON.serialize()
  46368. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46369. __decorate([
  46370. BABYLON.serialize()
  46371. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46372. return FreeCameraMouseInput;
  46373. }());
  46374. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46375. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46376. })(BABYLON || (BABYLON = {}));
  46377. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46378. var BABYLON;
  46379. (function (BABYLON) {
  46380. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46381. function FreeCameraKeyboardMoveInput() {
  46382. this._keys = new Array();
  46383. this.keysUp = [38];
  46384. this.keysDown = [40];
  46385. this.keysLeft = [37];
  46386. this.keysRight = [39];
  46387. }
  46388. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46389. var _this = this;
  46390. if (this._onCanvasBlurObserver) {
  46391. return;
  46392. }
  46393. this._scene = this.camera.getScene();
  46394. this._engine = this._scene.getEngine();
  46395. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46396. _this._keys = [];
  46397. });
  46398. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46399. var evt = info.event;
  46400. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46401. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46402. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46403. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46404. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46405. var index = _this._keys.indexOf(evt.keyCode);
  46406. if (index === -1) {
  46407. _this._keys.push(evt.keyCode);
  46408. }
  46409. if (!noPreventDefault) {
  46410. evt.preventDefault();
  46411. }
  46412. }
  46413. }
  46414. else {
  46415. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46416. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46417. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46418. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46419. var index = _this._keys.indexOf(evt.keyCode);
  46420. if (index >= 0) {
  46421. _this._keys.splice(index, 1);
  46422. }
  46423. if (!noPreventDefault) {
  46424. evt.preventDefault();
  46425. }
  46426. }
  46427. }
  46428. });
  46429. };
  46430. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46431. if (this._scene) {
  46432. if (this._onKeyboardObserver) {
  46433. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46434. }
  46435. if (this._onCanvasBlurObserver) {
  46436. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46437. }
  46438. this._onKeyboardObserver = null;
  46439. this._onCanvasBlurObserver = null;
  46440. }
  46441. this._keys = [];
  46442. };
  46443. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46444. if (this._onKeyboardObserver) {
  46445. var camera = this.camera;
  46446. // Keyboard
  46447. for (var index = 0; index < this._keys.length; index++) {
  46448. var keyCode = this._keys[index];
  46449. var speed = camera._computeLocalCameraSpeed();
  46450. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46451. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46452. }
  46453. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46454. camera._localDirection.copyFromFloats(0, 0, speed);
  46455. }
  46456. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46457. camera._localDirection.copyFromFloats(speed, 0, 0);
  46458. }
  46459. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46460. camera._localDirection.copyFromFloats(0, 0, -speed);
  46461. }
  46462. if (camera.getScene().useRightHandedSystem) {
  46463. camera._localDirection.z *= -1;
  46464. }
  46465. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46466. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46467. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46468. }
  46469. }
  46470. };
  46471. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46472. return "FreeCameraKeyboardMoveInput";
  46473. };
  46474. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46475. this._keys = [];
  46476. };
  46477. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46478. return "keyboard";
  46479. };
  46480. __decorate([
  46481. BABYLON.serialize()
  46482. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46483. __decorate([
  46484. BABYLON.serialize()
  46485. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46486. __decorate([
  46487. BABYLON.serialize()
  46488. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46489. __decorate([
  46490. BABYLON.serialize()
  46491. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46492. return FreeCameraKeyboardMoveInput;
  46493. }());
  46494. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46495. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46496. })(BABYLON || (BABYLON = {}));
  46497. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46498. var BABYLON;
  46499. (function (BABYLON) {
  46500. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46501. __extends(FreeCameraInputsManager, _super);
  46502. function FreeCameraInputsManager(camera) {
  46503. return _super.call(this, camera) || this;
  46504. }
  46505. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46506. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46507. return this;
  46508. };
  46509. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46510. if (touchEnabled === void 0) { touchEnabled = true; }
  46511. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46512. return this;
  46513. };
  46514. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46515. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46516. return this;
  46517. };
  46518. FreeCameraInputsManager.prototype.addTouch = function () {
  46519. this.add(new BABYLON.FreeCameraTouchInput());
  46520. return this;
  46521. };
  46522. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46523. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46524. return this;
  46525. };
  46526. return FreeCameraInputsManager;
  46527. }(BABYLON.CameraInputsManager));
  46528. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46529. })(BABYLON || (BABYLON = {}));
  46530. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46531. var BABYLON;
  46532. (function (BABYLON) {
  46533. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46534. // Forcing to use the Universal camera
  46535. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46536. });
  46537. var FreeCamera = /** @class */ (function (_super) {
  46538. __extends(FreeCamera, _super);
  46539. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46540. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46541. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46542. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46543. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46544. _this.checkCollisions = false;
  46545. _this.applyGravity = false;
  46546. _this._needMoveForGravity = false;
  46547. _this._oldPosition = BABYLON.Vector3.Zero();
  46548. _this._diffPosition = BABYLON.Vector3.Zero();
  46549. _this._newPosition = BABYLON.Vector3.Zero();
  46550. // Collisions
  46551. _this._collisionMask = -1;
  46552. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46553. if (collidedMesh === void 0) { collidedMesh = null; }
  46554. //TODO move this to the collision coordinator!
  46555. if (_this.getScene().workerCollisions)
  46556. newPosition.multiplyInPlace(_this._collider._radius);
  46557. var updatePosition = function (newPos) {
  46558. _this._newPosition.copyFrom(newPos);
  46559. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46560. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46561. _this.position.addInPlace(_this._diffPosition);
  46562. if (_this.onCollide && collidedMesh) {
  46563. _this.onCollide(collidedMesh);
  46564. }
  46565. }
  46566. };
  46567. updatePosition(newPosition);
  46568. };
  46569. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46570. _this.inputs.addKeyboard().addMouse();
  46571. return _this;
  46572. }
  46573. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46574. //-- begin properties for backward compatibility for inputs
  46575. /**
  46576. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46577. * Higher values reduce sensitivity.
  46578. */
  46579. get: function () {
  46580. var mouse = this.inputs.attached["mouse"];
  46581. if (mouse)
  46582. return mouse.angularSensibility;
  46583. return 0;
  46584. },
  46585. /**
  46586. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46587. * Higher values reduce sensitivity.
  46588. */
  46589. set: function (value) {
  46590. var mouse = this.inputs.attached["mouse"];
  46591. if (mouse)
  46592. mouse.angularSensibility = value;
  46593. },
  46594. enumerable: true,
  46595. configurable: true
  46596. });
  46597. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46598. get: function () {
  46599. var keyboard = this.inputs.attached["keyboard"];
  46600. if (keyboard)
  46601. return keyboard.keysUp;
  46602. return [];
  46603. },
  46604. set: function (value) {
  46605. var keyboard = this.inputs.attached["keyboard"];
  46606. if (keyboard)
  46607. keyboard.keysUp = value;
  46608. },
  46609. enumerable: true,
  46610. configurable: true
  46611. });
  46612. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46613. get: function () {
  46614. var keyboard = this.inputs.attached["keyboard"];
  46615. if (keyboard)
  46616. return keyboard.keysDown;
  46617. return [];
  46618. },
  46619. set: function (value) {
  46620. var keyboard = this.inputs.attached["keyboard"];
  46621. if (keyboard)
  46622. keyboard.keysDown = value;
  46623. },
  46624. enumerable: true,
  46625. configurable: true
  46626. });
  46627. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46628. get: function () {
  46629. var keyboard = this.inputs.attached["keyboard"];
  46630. if (keyboard)
  46631. return keyboard.keysLeft;
  46632. return [];
  46633. },
  46634. set: function (value) {
  46635. var keyboard = this.inputs.attached["keyboard"];
  46636. if (keyboard)
  46637. keyboard.keysLeft = value;
  46638. },
  46639. enumerable: true,
  46640. configurable: true
  46641. });
  46642. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46643. get: function () {
  46644. var keyboard = this.inputs.attached["keyboard"];
  46645. if (keyboard)
  46646. return keyboard.keysRight;
  46647. return [];
  46648. },
  46649. set: function (value) {
  46650. var keyboard = this.inputs.attached["keyboard"];
  46651. if (keyboard)
  46652. keyboard.keysRight = value;
  46653. },
  46654. enumerable: true,
  46655. configurable: true
  46656. });
  46657. // Controls
  46658. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46659. this.inputs.attachElement(element, noPreventDefault);
  46660. };
  46661. FreeCamera.prototype.detachControl = function (element) {
  46662. this.inputs.detachElement(element);
  46663. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46664. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46665. };
  46666. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46667. get: function () {
  46668. return this._collisionMask;
  46669. },
  46670. set: function (mask) {
  46671. this._collisionMask = !isNaN(mask) ? mask : -1;
  46672. },
  46673. enumerable: true,
  46674. configurable: true
  46675. });
  46676. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46677. var globalPosition;
  46678. if (this.parent) {
  46679. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46680. }
  46681. else {
  46682. globalPosition = this.position;
  46683. }
  46684. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46685. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46686. if (!this._collider) {
  46687. this._collider = new BABYLON.Collider();
  46688. }
  46689. this._collider._radius = this.ellipsoid;
  46690. this._collider.collisionMask = this._collisionMask;
  46691. //no need for clone, as long as gravity is not on.
  46692. var actualDisplacement = displacement;
  46693. //add gravity to the direction to prevent the dual-collision checking
  46694. if (this.applyGravity) {
  46695. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46696. actualDisplacement = displacement.add(this.getScene().gravity);
  46697. }
  46698. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46699. };
  46700. FreeCamera.prototype._checkInputs = function () {
  46701. if (!this._localDirection) {
  46702. this._localDirection = BABYLON.Vector3.Zero();
  46703. this._transformedDirection = BABYLON.Vector3.Zero();
  46704. }
  46705. this.inputs.checkInputs();
  46706. _super.prototype._checkInputs.call(this);
  46707. };
  46708. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46709. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46710. };
  46711. FreeCamera.prototype._updatePosition = function () {
  46712. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46713. this._collideWithWorld(this.cameraDirection);
  46714. }
  46715. else {
  46716. _super.prototype._updatePosition.call(this);
  46717. }
  46718. };
  46719. FreeCamera.prototype.dispose = function () {
  46720. this.inputs.clear();
  46721. _super.prototype.dispose.call(this);
  46722. };
  46723. FreeCamera.prototype.getClassName = function () {
  46724. return "FreeCamera";
  46725. };
  46726. __decorate([
  46727. BABYLON.serializeAsVector3()
  46728. ], FreeCamera.prototype, "ellipsoid", void 0);
  46729. __decorate([
  46730. BABYLON.serializeAsVector3()
  46731. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46732. __decorate([
  46733. BABYLON.serialize()
  46734. ], FreeCamera.prototype, "checkCollisions", void 0);
  46735. __decorate([
  46736. BABYLON.serialize()
  46737. ], FreeCamera.prototype, "applyGravity", void 0);
  46738. return FreeCamera;
  46739. }(BABYLON.TargetCamera));
  46740. BABYLON.FreeCamera = FreeCamera;
  46741. })(BABYLON || (BABYLON = {}));
  46742. //# sourceMappingURL=babylon.freeCamera.js.map
  46743. var BABYLON;
  46744. (function (BABYLON) {
  46745. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46746. function ArcRotateCameraKeyboardMoveInput() {
  46747. this._keys = new Array();
  46748. this.keysUp = [38];
  46749. this.keysDown = [40];
  46750. this.keysLeft = [37];
  46751. this.keysRight = [39];
  46752. this.keysReset = [220];
  46753. this.panningSensibility = 50.0;
  46754. this.zoomingSensibility = 25.0;
  46755. this.useAltToZoom = true;
  46756. }
  46757. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46758. var _this = this;
  46759. if (this._onCanvasBlurObserver) {
  46760. return;
  46761. }
  46762. this._scene = this.camera.getScene();
  46763. this._engine = this._scene.getEngine();
  46764. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46765. _this._keys = [];
  46766. });
  46767. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46768. var evt = info.event;
  46769. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46770. _this._ctrlPressed = evt.ctrlKey;
  46771. _this._altPressed = evt.altKey;
  46772. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46773. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46774. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46775. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46776. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46777. var index = _this._keys.indexOf(evt.keyCode);
  46778. if (index === -1) {
  46779. _this._keys.push(evt.keyCode);
  46780. }
  46781. if (evt.preventDefault) {
  46782. if (!noPreventDefault) {
  46783. evt.preventDefault();
  46784. }
  46785. }
  46786. }
  46787. }
  46788. else {
  46789. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46790. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46791. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46792. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46793. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46794. var index = _this._keys.indexOf(evt.keyCode);
  46795. if (index >= 0) {
  46796. _this._keys.splice(index, 1);
  46797. }
  46798. if (evt.preventDefault) {
  46799. if (!noPreventDefault) {
  46800. evt.preventDefault();
  46801. }
  46802. }
  46803. }
  46804. }
  46805. });
  46806. };
  46807. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46808. if (this._scene) {
  46809. if (this._onKeyboardObserver) {
  46810. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46811. }
  46812. if (this._onCanvasBlurObserver) {
  46813. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46814. }
  46815. this._onKeyboardObserver = null;
  46816. this._onCanvasBlurObserver = null;
  46817. }
  46818. this._keys = [];
  46819. };
  46820. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46821. if (this._onKeyboardObserver) {
  46822. var camera = this.camera;
  46823. for (var index = 0; index < this._keys.length; index++) {
  46824. var keyCode = this._keys[index];
  46825. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46826. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46827. camera.inertialPanningX -= 1 / this.panningSensibility;
  46828. }
  46829. else {
  46830. camera.inertialAlphaOffset -= 0.01;
  46831. }
  46832. }
  46833. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46834. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46835. camera.inertialPanningY += 1 / this.panningSensibility;
  46836. }
  46837. else if (this._altPressed && this.useAltToZoom) {
  46838. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46839. }
  46840. else {
  46841. camera.inertialBetaOffset -= 0.01;
  46842. }
  46843. }
  46844. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46845. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46846. camera.inertialPanningX += 1 / this.panningSensibility;
  46847. }
  46848. else {
  46849. camera.inertialAlphaOffset += 0.01;
  46850. }
  46851. }
  46852. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46853. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46854. camera.inertialPanningY -= 1 / this.panningSensibility;
  46855. }
  46856. else if (this._altPressed && this.useAltToZoom) {
  46857. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46858. }
  46859. else {
  46860. camera.inertialBetaOffset += 0.01;
  46861. }
  46862. }
  46863. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46864. camera.restoreState();
  46865. }
  46866. }
  46867. }
  46868. };
  46869. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46870. return "ArcRotateCameraKeyboardMoveInput";
  46871. };
  46872. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46873. return "keyboard";
  46874. };
  46875. __decorate([
  46876. BABYLON.serialize()
  46877. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46878. __decorate([
  46879. BABYLON.serialize()
  46880. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46881. __decorate([
  46882. BABYLON.serialize()
  46883. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46884. __decorate([
  46885. BABYLON.serialize()
  46886. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46887. __decorate([
  46888. BABYLON.serialize()
  46889. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46890. __decorate([
  46891. BABYLON.serialize()
  46892. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46893. __decorate([
  46894. BABYLON.serialize()
  46895. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46896. __decorate([
  46897. BABYLON.serialize()
  46898. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46899. return ArcRotateCameraKeyboardMoveInput;
  46900. }());
  46901. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46902. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46903. })(BABYLON || (BABYLON = {}));
  46904. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46905. var BABYLON;
  46906. (function (BABYLON) {
  46907. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46908. function ArcRotateCameraMouseWheelInput() {
  46909. this.wheelPrecision = 3.0;
  46910. /**
  46911. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46912. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46913. */
  46914. this.wheelDeltaPercentage = 0;
  46915. }
  46916. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46917. var _this = this;
  46918. this._wheel = function (p, s) {
  46919. //sanity check - this should be a PointerWheel event.
  46920. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46921. return;
  46922. var event = p.event;
  46923. var delta = 0;
  46924. if (event.wheelDelta) {
  46925. if (_this.wheelDeltaPercentage) {
  46926. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46927. if (event.wheelDelta > 0) {
  46928. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46929. }
  46930. else {
  46931. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46932. }
  46933. }
  46934. else {
  46935. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46936. }
  46937. }
  46938. else if (event.detail) {
  46939. delta = -event.detail / _this.wheelPrecision;
  46940. }
  46941. if (delta)
  46942. _this.camera.inertialRadiusOffset += delta;
  46943. if (event.preventDefault) {
  46944. if (!noPreventDefault) {
  46945. event.preventDefault();
  46946. }
  46947. }
  46948. };
  46949. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46950. };
  46951. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46952. if (this._observer && element) {
  46953. this.camera.getScene().onPointerObservable.remove(this._observer);
  46954. this._observer = null;
  46955. this._wheel = null;
  46956. }
  46957. };
  46958. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46959. return "ArcRotateCameraMouseWheelInput";
  46960. };
  46961. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46962. return "mousewheel";
  46963. };
  46964. __decorate([
  46965. BABYLON.serialize()
  46966. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46967. __decorate([
  46968. BABYLON.serialize()
  46969. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46970. return ArcRotateCameraMouseWheelInput;
  46971. }());
  46972. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46973. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46974. })(BABYLON || (BABYLON = {}));
  46975. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46976. var BABYLON;
  46977. (function (BABYLON) {
  46978. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46979. function ArcRotateCameraPointersInput() {
  46980. this.buttons = [0, 1, 2];
  46981. this.angularSensibilityX = 1000.0;
  46982. this.angularSensibilityY = 1000.0;
  46983. this.pinchPrecision = 12.0;
  46984. /**
  46985. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46986. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46987. */
  46988. this.pinchDeltaPercentage = 0;
  46989. this.panningSensibility = 1000.0;
  46990. this.multiTouchPanning = true;
  46991. this.multiTouchPanAndZoom = true;
  46992. this._isPanClick = false;
  46993. this.pinchInwards = true;
  46994. }
  46995. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46996. var _this = this;
  46997. var engine = this.camera.getEngine();
  46998. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46999. var pointA = null;
  47000. var pointB = null;
  47001. var previousPinchSquaredDistance = 0;
  47002. var initialDistance = 0;
  47003. var twoFingerActivityCount = 0;
  47004. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47005. this._pointerInput = function (p, s) {
  47006. var evt = p.event;
  47007. var isTouch = p.event.pointerType === "touch";
  47008. if (engine.isInVRExclusivePointerMode) {
  47009. return;
  47010. }
  47011. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47012. return;
  47013. }
  47014. var srcElement = (evt.srcElement || evt.target);
  47015. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47016. try {
  47017. srcElement.setPointerCapture(evt.pointerId);
  47018. }
  47019. catch (e) {
  47020. //Nothing to do with the error. Execution will continue.
  47021. }
  47022. // Manage panning with pan button click
  47023. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47024. // manage pointers
  47025. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47026. if (pointA === null) {
  47027. pointA = cacheSoloPointer;
  47028. }
  47029. else if (pointB === null) {
  47030. pointB = cacheSoloPointer;
  47031. }
  47032. if (!noPreventDefault) {
  47033. evt.preventDefault();
  47034. element.focus();
  47035. }
  47036. }
  47037. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47038. _this.camera.restoreState();
  47039. }
  47040. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47041. try {
  47042. srcElement.releasePointerCapture(evt.pointerId);
  47043. }
  47044. catch (e) {
  47045. //Nothing to do with the error.
  47046. }
  47047. cacheSoloPointer = null;
  47048. previousPinchSquaredDistance = 0;
  47049. previousMultiTouchPanPosition.isPaning = false;
  47050. previousMultiTouchPanPosition.isPinching = false;
  47051. twoFingerActivityCount = 0;
  47052. initialDistance = 0;
  47053. if (!isTouch) {
  47054. pointB = null; // Mouse and pen are mono pointer
  47055. }
  47056. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47057. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47058. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47059. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47060. if (engine._badOS) {
  47061. pointA = pointB = null;
  47062. }
  47063. else {
  47064. //only remove the impacted pointer in case of multitouch allowing on most
  47065. //platforms switching from rotate to zoom and pan seamlessly.
  47066. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47067. pointA = pointB;
  47068. pointB = null;
  47069. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47070. }
  47071. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47072. pointB = null;
  47073. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47074. }
  47075. else {
  47076. pointA = pointB = null;
  47077. }
  47078. }
  47079. if (!noPreventDefault) {
  47080. evt.preventDefault();
  47081. }
  47082. }
  47083. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47084. if (!noPreventDefault) {
  47085. evt.preventDefault();
  47086. }
  47087. // One button down
  47088. if (pointA && pointB === null && cacheSoloPointer) {
  47089. if (_this.panningSensibility !== 0 &&
  47090. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47091. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47092. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47093. }
  47094. else {
  47095. var offsetX = evt.clientX - cacheSoloPointer.x;
  47096. var offsetY = evt.clientY - cacheSoloPointer.y;
  47097. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47098. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47099. }
  47100. cacheSoloPointer.x = evt.clientX;
  47101. cacheSoloPointer.y = evt.clientY;
  47102. }
  47103. // Two buttons down: pinch/pan
  47104. else if (pointA && pointB) {
  47105. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47106. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47107. ed.x = evt.clientX;
  47108. ed.y = evt.clientY;
  47109. var direction = _this.pinchInwards ? 1 : -1;
  47110. var distX = pointA.x - pointB.x;
  47111. var distY = pointA.y - pointB.y;
  47112. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47113. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47114. if (previousPinchSquaredDistance === 0) {
  47115. initialDistance = pinchDistance;
  47116. previousPinchSquaredDistance = pinchSquaredDistance;
  47117. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47118. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47119. return;
  47120. }
  47121. if (_this.multiTouchPanAndZoom) {
  47122. if (_this.pinchDeltaPercentage) {
  47123. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47124. }
  47125. else {
  47126. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47127. (_this.pinchPrecision *
  47128. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47129. direction);
  47130. }
  47131. if (_this.panningSensibility !== 0) {
  47132. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47133. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47134. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47135. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47136. previousMultiTouchPanPosition.x = pointersCenterX;
  47137. previousMultiTouchPanPosition.y = pointersCenterY;
  47138. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47139. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47140. }
  47141. }
  47142. else {
  47143. twoFingerActivityCount++;
  47144. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47145. if (_this.pinchDeltaPercentage) {
  47146. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47147. }
  47148. else {
  47149. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47150. (_this.pinchPrecision *
  47151. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47152. direction);
  47153. }
  47154. previousMultiTouchPanPosition.isPaning = false;
  47155. previousMultiTouchPanPosition.isPinching = true;
  47156. }
  47157. else {
  47158. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47159. if (!previousMultiTouchPanPosition.isPaning) {
  47160. previousMultiTouchPanPosition.isPaning = true;
  47161. previousMultiTouchPanPosition.isPinching = false;
  47162. previousMultiTouchPanPosition.x = ed.x;
  47163. previousMultiTouchPanPosition.y = ed.y;
  47164. return;
  47165. }
  47166. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47167. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47168. }
  47169. }
  47170. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47171. previousMultiTouchPanPosition.x = ed.x;
  47172. previousMultiTouchPanPosition.y = ed.y;
  47173. }
  47174. }
  47175. previousPinchSquaredDistance = pinchSquaredDistance;
  47176. }
  47177. }
  47178. };
  47179. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47180. this._onContextMenu = function (evt) {
  47181. evt.preventDefault();
  47182. };
  47183. if (!this.camera._useCtrlForPanning) {
  47184. element.addEventListener("contextmenu", this._onContextMenu, false);
  47185. }
  47186. this._onLostFocus = function () {
  47187. //this._keys = [];
  47188. pointA = pointB = null;
  47189. previousPinchSquaredDistance = 0;
  47190. previousMultiTouchPanPosition.isPaning = false;
  47191. previousMultiTouchPanPosition.isPinching = false;
  47192. twoFingerActivityCount = 0;
  47193. cacheSoloPointer = null;
  47194. initialDistance = 0;
  47195. };
  47196. this._onMouseMove = function (evt) {
  47197. if (!engine.isPointerLock) {
  47198. return;
  47199. }
  47200. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47201. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47202. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47203. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47204. if (!noPreventDefault) {
  47205. evt.preventDefault();
  47206. }
  47207. };
  47208. this._onGestureStart = function (e) {
  47209. if (window.MSGesture === undefined) {
  47210. return;
  47211. }
  47212. if (!_this._MSGestureHandler) {
  47213. _this._MSGestureHandler = new MSGesture();
  47214. _this._MSGestureHandler.target = element;
  47215. }
  47216. _this._MSGestureHandler.addPointer(e.pointerId);
  47217. };
  47218. this._onGesture = function (e) {
  47219. _this.camera.radius *= e.scale;
  47220. if (e.preventDefault) {
  47221. if (!noPreventDefault) {
  47222. e.stopPropagation();
  47223. e.preventDefault();
  47224. }
  47225. }
  47226. };
  47227. element.addEventListener("mousemove", this._onMouseMove, false);
  47228. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47229. element.addEventListener("MSGestureChange", this._onGesture, false);
  47230. BABYLON.Tools.RegisterTopRootEvents([
  47231. { name: "blur", handler: this._onLostFocus }
  47232. ]);
  47233. };
  47234. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47235. if (this._onLostFocus) {
  47236. BABYLON.Tools.UnregisterTopRootEvents([
  47237. { name: "blur", handler: this._onLostFocus }
  47238. ]);
  47239. }
  47240. if (element && this._observer) {
  47241. this.camera.getScene().onPointerObservable.remove(this._observer);
  47242. this._observer = null;
  47243. if (this._onContextMenu) {
  47244. element.removeEventListener("contextmenu", this._onContextMenu);
  47245. }
  47246. if (this._onMouseMove) {
  47247. element.removeEventListener("mousemove", this._onMouseMove);
  47248. }
  47249. if (this._onGestureStart) {
  47250. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47251. }
  47252. if (this._onGesture) {
  47253. element.removeEventListener("MSGestureChange", this._onGesture);
  47254. }
  47255. this._isPanClick = false;
  47256. this.pinchInwards = true;
  47257. this._onMouseMove = null;
  47258. this._onGestureStart = null;
  47259. this._onGesture = null;
  47260. this._MSGestureHandler = null;
  47261. this._onLostFocus = null;
  47262. this._onContextMenu = null;
  47263. }
  47264. };
  47265. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47266. return "ArcRotateCameraPointersInput";
  47267. };
  47268. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47269. return "pointers";
  47270. };
  47271. __decorate([
  47272. BABYLON.serialize()
  47273. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47274. __decorate([
  47275. BABYLON.serialize()
  47276. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47277. __decorate([
  47278. BABYLON.serialize()
  47279. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47280. __decorate([
  47281. BABYLON.serialize()
  47282. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47283. __decorate([
  47284. BABYLON.serialize()
  47285. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47286. __decorate([
  47287. BABYLON.serialize()
  47288. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47289. __decorate([
  47290. BABYLON.serialize()
  47291. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47292. __decorate([
  47293. BABYLON.serialize()
  47294. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47295. return ArcRotateCameraPointersInput;
  47296. }());
  47297. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47298. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47299. })(BABYLON || (BABYLON = {}));
  47300. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47301. var BABYLON;
  47302. (function (BABYLON) {
  47303. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47304. __extends(ArcRotateCameraInputsManager, _super);
  47305. function ArcRotateCameraInputsManager(camera) {
  47306. return _super.call(this, camera) || this;
  47307. }
  47308. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47309. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47310. return this;
  47311. };
  47312. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47313. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47314. return this;
  47315. };
  47316. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47317. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47318. return this;
  47319. };
  47320. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47321. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47322. return this;
  47323. };
  47324. return ArcRotateCameraInputsManager;
  47325. }(BABYLON.CameraInputsManager));
  47326. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47327. })(BABYLON || (BABYLON = {}));
  47328. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47329. var BABYLON;
  47330. (function (BABYLON) {
  47331. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47332. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47333. });
  47334. var ArcRotateCamera = /** @class */ (function (_super) {
  47335. __extends(ArcRotateCamera, _super);
  47336. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47337. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47338. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47339. _this.inertialAlphaOffset = 0;
  47340. _this.inertialBetaOffset = 0;
  47341. _this.inertialRadiusOffset = 0;
  47342. _this.lowerAlphaLimit = null;
  47343. _this.upperAlphaLimit = null;
  47344. _this.lowerBetaLimit = 0.01;
  47345. _this.upperBetaLimit = Math.PI;
  47346. _this.lowerRadiusLimit = null;
  47347. _this.upperRadiusLimit = null;
  47348. _this.inertialPanningX = 0;
  47349. _this.inertialPanningY = 0;
  47350. _this.pinchToPanMaxDistance = 20;
  47351. _this.panningDistanceLimit = null;
  47352. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47353. _this.panningInertia = 0.9;
  47354. //-- end properties for backward compatibility for inputs
  47355. _this.zoomOnFactor = 1;
  47356. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47357. _this.allowUpsideDown = true;
  47358. _this._viewMatrix = new BABYLON.Matrix();
  47359. // Panning
  47360. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47361. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47362. _this.checkCollisions = false;
  47363. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47364. _this._previousPosition = BABYLON.Vector3.Zero();
  47365. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47366. _this._newPosition = BABYLON.Vector3.Zero();
  47367. _this._computationVector = BABYLON.Vector3.Zero();
  47368. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47369. if (collidedMesh === void 0) { collidedMesh = null; }
  47370. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47371. newPosition.multiplyInPlace(_this._collider._radius);
  47372. }
  47373. if (!collidedMesh) {
  47374. _this._previousPosition.copyFrom(_this.position);
  47375. }
  47376. else {
  47377. _this.setPosition(newPosition);
  47378. if (_this.onCollide) {
  47379. _this.onCollide(collidedMesh);
  47380. }
  47381. }
  47382. // Recompute because of constraints
  47383. var cosa = Math.cos(_this.alpha);
  47384. var sina = Math.sin(_this.alpha);
  47385. var cosb = Math.cos(_this.beta);
  47386. var sinb = Math.sin(_this.beta);
  47387. if (sinb === 0) {
  47388. sinb = 0.0001;
  47389. }
  47390. var target = _this._getTargetPosition();
  47391. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47392. target.addToRef(_this._computationVector, _this._newPosition);
  47393. _this.position.copyFrom(_this._newPosition);
  47394. var up = _this.upVector;
  47395. if (_this.allowUpsideDown && _this.beta < 0) {
  47396. up = up.clone();
  47397. up = up.negate();
  47398. }
  47399. _this._computeViewMatrix(_this.position, target, up);
  47400. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47401. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47402. _this._collisionTriggered = false;
  47403. };
  47404. _this._target = BABYLON.Vector3.Zero();
  47405. if (target) {
  47406. _this.setTarget(target);
  47407. }
  47408. _this.alpha = alpha;
  47409. _this.beta = beta;
  47410. _this.radius = radius;
  47411. _this.getViewMatrix();
  47412. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47413. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47414. return _this;
  47415. }
  47416. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47417. get: function () {
  47418. return this._target;
  47419. },
  47420. set: function (value) {
  47421. this.setTarget(value);
  47422. },
  47423. enumerable: true,
  47424. configurable: true
  47425. });
  47426. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47427. //-- begin properties for backward compatibility for inputs
  47428. get: function () {
  47429. var pointers = this.inputs.attached["pointers"];
  47430. if (pointers)
  47431. return pointers.angularSensibilityX;
  47432. return 0;
  47433. },
  47434. set: function (value) {
  47435. var pointers = this.inputs.attached["pointers"];
  47436. if (pointers) {
  47437. pointers.angularSensibilityX = value;
  47438. }
  47439. },
  47440. enumerable: true,
  47441. configurable: true
  47442. });
  47443. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47444. get: function () {
  47445. var pointers = this.inputs.attached["pointers"];
  47446. if (pointers)
  47447. return pointers.angularSensibilityY;
  47448. return 0;
  47449. },
  47450. set: function (value) {
  47451. var pointers = this.inputs.attached["pointers"];
  47452. if (pointers) {
  47453. pointers.angularSensibilityY = value;
  47454. }
  47455. },
  47456. enumerable: true,
  47457. configurable: true
  47458. });
  47459. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47460. get: function () {
  47461. var pointers = this.inputs.attached["pointers"];
  47462. if (pointers)
  47463. return pointers.pinchPrecision;
  47464. return 0;
  47465. },
  47466. set: function (value) {
  47467. var pointers = this.inputs.attached["pointers"];
  47468. if (pointers) {
  47469. pointers.pinchPrecision = value;
  47470. }
  47471. },
  47472. enumerable: true,
  47473. configurable: true
  47474. });
  47475. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47476. get: function () {
  47477. var pointers = this.inputs.attached["pointers"];
  47478. if (pointers)
  47479. return pointers.pinchDeltaPercentage;
  47480. return 0;
  47481. },
  47482. set: function (value) {
  47483. var pointers = this.inputs.attached["pointers"];
  47484. if (pointers) {
  47485. pointers.pinchDeltaPercentage = value;
  47486. }
  47487. },
  47488. enumerable: true,
  47489. configurable: true
  47490. });
  47491. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47492. get: function () {
  47493. var pointers = this.inputs.attached["pointers"];
  47494. if (pointers)
  47495. return pointers.panningSensibility;
  47496. return 0;
  47497. },
  47498. set: function (value) {
  47499. var pointers = this.inputs.attached["pointers"];
  47500. if (pointers) {
  47501. pointers.panningSensibility = value;
  47502. }
  47503. },
  47504. enumerable: true,
  47505. configurable: true
  47506. });
  47507. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47508. get: function () {
  47509. var keyboard = this.inputs.attached["keyboard"];
  47510. if (keyboard)
  47511. return keyboard.keysUp;
  47512. return [];
  47513. },
  47514. set: function (value) {
  47515. var keyboard = this.inputs.attached["keyboard"];
  47516. if (keyboard)
  47517. keyboard.keysUp = value;
  47518. },
  47519. enumerable: true,
  47520. configurable: true
  47521. });
  47522. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47523. get: function () {
  47524. var keyboard = this.inputs.attached["keyboard"];
  47525. if (keyboard)
  47526. return keyboard.keysDown;
  47527. return [];
  47528. },
  47529. set: function (value) {
  47530. var keyboard = this.inputs.attached["keyboard"];
  47531. if (keyboard)
  47532. keyboard.keysDown = value;
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47538. get: function () {
  47539. var keyboard = this.inputs.attached["keyboard"];
  47540. if (keyboard)
  47541. return keyboard.keysLeft;
  47542. return [];
  47543. },
  47544. set: function (value) {
  47545. var keyboard = this.inputs.attached["keyboard"];
  47546. if (keyboard)
  47547. keyboard.keysLeft = value;
  47548. },
  47549. enumerable: true,
  47550. configurable: true
  47551. });
  47552. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47553. get: function () {
  47554. var keyboard = this.inputs.attached["keyboard"];
  47555. if (keyboard)
  47556. return keyboard.keysRight;
  47557. return [];
  47558. },
  47559. set: function (value) {
  47560. var keyboard = this.inputs.attached["keyboard"];
  47561. if (keyboard)
  47562. keyboard.keysRight = value;
  47563. },
  47564. enumerable: true,
  47565. configurable: true
  47566. });
  47567. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47568. get: function () {
  47569. var mousewheel = this.inputs.attached["mousewheel"];
  47570. if (mousewheel)
  47571. return mousewheel.wheelPrecision;
  47572. return 0;
  47573. },
  47574. set: function (value) {
  47575. var mousewheel = this.inputs.attached["mousewheel"];
  47576. if (mousewheel)
  47577. mousewheel.wheelPrecision = value;
  47578. },
  47579. enumerable: true,
  47580. configurable: true
  47581. });
  47582. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47583. get: function () {
  47584. var mousewheel = this.inputs.attached["mousewheel"];
  47585. if (mousewheel)
  47586. return mousewheel.wheelDeltaPercentage;
  47587. return 0;
  47588. },
  47589. set: function (value) {
  47590. var mousewheel = this.inputs.attached["mousewheel"];
  47591. if (mousewheel)
  47592. mousewheel.wheelDeltaPercentage = value;
  47593. },
  47594. enumerable: true,
  47595. configurable: true
  47596. });
  47597. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47598. get: function () {
  47599. return this._bouncingBehavior;
  47600. },
  47601. enumerable: true,
  47602. configurable: true
  47603. });
  47604. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47605. get: function () {
  47606. return this._bouncingBehavior != null;
  47607. },
  47608. set: function (value) {
  47609. if (value === this.useBouncingBehavior) {
  47610. return;
  47611. }
  47612. if (value) {
  47613. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47614. this.addBehavior(this._bouncingBehavior);
  47615. }
  47616. else if (this._bouncingBehavior) {
  47617. this.removeBehavior(this._bouncingBehavior);
  47618. this._bouncingBehavior = null;
  47619. }
  47620. },
  47621. enumerable: true,
  47622. configurable: true
  47623. });
  47624. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47625. get: function () {
  47626. return this._framingBehavior;
  47627. },
  47628. enumerable: true,
  47629. configurable: true
  47630. });
  47631. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47632. get: function () {
  47633. return this._framingBehavior != null;
  47634. },
  47635. set: function (value) {
  47636. if (value === this.useFramingBehavior) {
  47637. return;
  47638. }
  47639. if (value) {
  47640. this._framingBehavior = new BABYLON.FramingBehavior();
  47641. this.addBehavior(this._framingBehavior);
  47642. }
  47643. else if (this._framingBehavior) {
  47644. this.removeBehavior(this._framingBehavior);
  47645. this._framingBehavior = null;
  47646. }
  47647. },
  47648. enumerable: true,
  47649. configurable: true
  47650. });
  47651. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47652. get: function () {
  47653. return this._autoRotationBehavior;
  47654. },
  47655. enumerable: true,
  47656. configurable: true
  47657. });
  47658. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47659. get: function () {
  47660. return this._autoRotationBehavior != null;
  47661. },
  47662. set: function (value) {
  47663. if (value === this.useAutoRotationBehavior) {
  47664. return;
  47665. }
  47666. if (value) {
  47667. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47668. this.addBehavior(this._autoRotationBehavior);
  47669. }
  47670. else if (this._autoRotationBehavior) {
  47671. this.removeBehavior(this._autoRotationBehavior);
  47672. this._autoRotationBehavior = null;
  47673. }
  47674. },
  47675. enumerable: true,
  47676. configurable: true
  47677. });
  47678. // Cache
  47679. ArcRotateCamera.prototype._initCache = function () {
  47680. _super.prototype._initCache.call(this);
  47681. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47682. this._cache.alpha = undefined;
  47683. this._cache.beta = undefined;
  47684. this._cache.radius = undefined;
  47685. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47686. };
  47687. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47688. if (!ignoreParentClass) {
  47689. _super.prototype._updateCache.call(this);
  47690. }
  47691. this._cache._target.copyFrom(this._getTargetPosition());
  47692. this._cache.alpha = this.alpha;
  47693. this._cache.beta = this.beta;
  47694. this._cache.radius = this.radius;
  47695. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47696. };
  47697. ArcRotateCamera.prototype._getTargetPosition = function () {
  47698. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47699. var pos = this._targetHost.getAbsolutePosition();
  47700. if (this._targetBoundingCenter) {
  47701. pos.addToRef(this._targetBoundingCenter, this._target);
  47702. }
  47703. else {
  47704. this._target.copyFrom(pos);
  47705. }
  47706. }
  47707. var lockedTargetPosition = this._getLockedTargetPosition();
  47708. if (lockedTargetPosition) {
  47709. return lockedTargetPosition;
  47710. }
  47711. return this._target;
  47712. };
  47713. ArcRotateCamera.prototype.storeState = function () {
  47714. this._storedAlpha = this.alpha;
  47715. this._storedBeta = this.beta;
  47716. this._storedRadius = this.radius;
  47717. this._storedTarget = this._getTargetPosition().clone();
  47718. return _super.prototype.storeState.call(this);
  47719. };
  47720. /**
  47721. * Restored camera state. You must call storeState() first
  47722. */
  47723. ArcRotateCamera.prototype._restoreStateValues = function () {
  47724. if (!_super.prototype._restoreStateValues.call(this)) {
  47725. return false;
  47726. }
  47727. this.alpha = this._storedAlpha;
  47728. this.beta = this._storedBeta;
  47729. this.radius = this._storedRadius;
  47730. this.setTarget(this._storedTarget.clone());
  47731. this.inertialAlphaOffset = 0;
  47732. this.inertialBetaOffset = 0;
  47733. this.inertialRadiusOffset = 0;
  47734. this.inertialPanningX = 0;
  47735. this.inertialPanningY = 0;
  47736. return true;
  47737. };
  47738. // Synchronized
  47739. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47740. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47741. return false;
  47742. return this._cache._target.equals(this._getTargetPosition())
  47743. && this._cache.alpha === this.alpha
  47744. && this._cache.beta === this.beta
  47745. && this._cache.radius === this.radius
  47746. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47747. };
  47748. // Methods
  47749. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47750. var _this = this;
  47751. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47752. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47753. this._useCtrlForPanning = useCtrlForPanning;
  47754. this._panningMouseButton = panningMouseButton;
  47755. this.inputs.attachElement(element, noPreventDefault);
  47756. this._reset = function () {
  47757. _this.inertialAlphaOffset = 0;
  47758. _this.inertialBetaOffset = 0;
  47759. _this.inertialRadiusOffset = 0;
  47760. _this.inertialPanningX = 0;
  47761. _this.inertialPanningY = 0;
  47762. };
  47763. };
  47764. ArcRotateCamera.prototype.detachControl = function (element) {
  47765. this.inputs.detachElement(element);
  47766. if (this._reset) {
  47767. this._reset();
  47768. }
  47769. };
  47770. ArcRotateCamera.prototype._checkInputs = function () {
  47771. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47772. if (this._collisionTriggered) {
  47773. return;
  47774. }
  47775. this.inputs.checkInputs();
  47776. // Inertia
  47777. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47778. var inertialAlphaOffset = this.inertialAlphaOffset;
  47779. if (this.beta <= 0)
  47780. inertialAlphaOffset *= -1;
  47781. if (this.getScene().useRightHandedSystem)
  47782. inertialAlphaOffset *= -1;
  47783. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47784. inertialAlphaOffset *= -1;
  47785. this.alpha += inertialAlphaOffset;
  47786. this.beta += this.inertialBetaOffset;
  47787. this.radius -= this.inertialRadiusOffset;
  47788. this.inertialAlphaOffset *= this.inertia;
  47789. this.inertialBetaOffset *= this.inertia;
  47790. this.inertialRadiusOffset *= this.inertia;
  47791. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47792. this.inertialAlphaOffset = 0;
  47793. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47794. this.inertialBetaOffset = 0;
  47795. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47796. this.inertialRadiusOffset = 0;
  47797. }
  47798. // Panning inertia
  47799. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47800. if (!this._localDirection) {
  47801. this._localDirection = BABYLON.Vector3.Zero();
  47802. this._transformedDirection = BABYLON.Vector3.Zero();
  47803. }
  47804. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47805. this._localDirection.multiplyInPlace(this.panningAxis);
  47806. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47807. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47808. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47809. if (!this.panningAxis.y) {
  47810. this._transformedDirection.y = 0;
  47811. }
  47812. if (!this._targetHost) {
  47813. if (this.panningDistanceLimit) {
  47814. this._transformedDirection.addInPlace(this._target);
  47815. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47816. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47817. this._target.copyFrom(this._transformedDirection);
  47818. }
  47819. }
  47820. else {
  47821. this._target.addInPlace(this._transformedDirection);
  47822. }
  47823. }
  47824. this.inertialPanningX *= this.panningInertia;
  47825. this.inertialPanningY *= this.panningInertia;
  47826. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47827. this.inertialPanningX = 0;
  47828. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47829. this.inertialPanningY = 0;
  47830. }
  47831. // Limits
  47832. this._checkLimits();
  47833. _super.prototype._checkInputs.call(this);
  47834. };
  47835. ArcRotateCamera.prototype._checkLimits = function () {
  47836. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47837. if (this.allowUpsideDown && this.beta > Math.PI) {
  47838. this.beta = this.beta - (2 * Math.PI);
  47839. }
  47840. }
  47841. else {
  47842. if (this.beta < this.lowerBetaLimit) {
  47843. this.beta = this.lowerBetaLimit;
  47844. }
  47845. }
  47846. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47847. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47848. this.beta = this.beta + (2 * Math.PI);
  47849. }
  47850. }
  47851. else {
  47852. if (this.beta > this.upperBetaLimit) {
  47853. this.beta = this.upperBetaLimit;
  47854. }
  47855. }
  47856. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47857. this.alpha = this.lowerAlphaLimit;
  47858. }
  47859. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47860. this.alpha = this.upperAlphaLimit;
  47861. }
  47862. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47863. this.radius = this.lowerRadiusLimit;
  47864. }
  47865. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47866. this.radius = this.upperRadiusLimit;
  47867. }
  47868. };
  47869. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47870. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47871. this.radius = this._computationVector.length();
  47872. if (this.radius === 0) {
  47873. this.radius = 0.0001; // Just to avoid division by zero
  47874. }
  47875. // Alpha
  47876. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47877. if (this._computationVector.z < 0) {
  47878. this.alpha = 2 * Math.PI - this.alpha;
  47879. }
  47880. // Beta
  47881. this.beta = Math.acos(this._computationVector.y / this.radius);
  47882. this._checkLimits();
  47883. };
  47884. ArcRotateCamera.prototype.setPosition = function (position) {
  47885. if (this.position.equals(position)) {
  47886. return;
  47887. }
  47888. this.position.copyFrom(position);
  47889. this.rebuildAnglesAndRadius();
  47890. };
  47891. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47892. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47893. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47894. if (target.getBoundingInfo) {
  47895. if (toBoundingCenter) {
  47896. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47897. }
  47898. else {
  47899. this._targetBoundingCenter = null;
  47900. }
  47901. this._targetHost = target;
  47902. this._target = this._getTargetPosition();
  47903. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47904. }
  47905. else {
  47906. var newTarget = target;
  47907. var currentTarget = this._getTargetPosition();
  47908. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47909. return;
  47910. }
  47911. this._targetHost = null;
  47912. this._target = newTarget;
  47913. this._targetBoundingCenter = null;
  47914. this.onMeshTargetChangedObservable.notifyObservers(null);
  47915. }
  47916. this.rebuildAnglesAndRadius();
  47917. };
  47918. ArcRotateCamera.prototype._getViewMatrix = function () {
  47919. // Compute
  47920. var cosa = Math.cos(this.alpha);
  47921. var sina = Math.sin(this.alpha);
  47922. var cosb = Math.cos(this.beta);
  47923. var sinb = Math.sin(this.beta);
  47924. if (sinb === 0) {
  47925. sinb = 0.0001;
  47926. }
  47927. var target = this._getTargetPosition();
  47928. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47929. target.addToRef(this._computationVector, this._newPosition);
  47930. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47931. if (!this._collider) {
  47932. this._collider = new BABYLON.Collider();
  47933. }
  47934. this._collider._radius = this.collisionRadius;
  47935. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47936. this._collisionTriggered = true;
  47937. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47938. }
  47939. else {
  47940. this.position.copyFrom(this._newPosition);
  47941. var up = this.upVector;
  47942. if (this.allowUpsideDown && sinb < 0) {
  47943. up = up.clone();
  47944. up = up.negate();
  47945. }
  47946. this._computeViewMatrix(this.position, target, up);
  47947. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47948. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47949. }
  47950. this._currentTarget = target;
  47951. return this._viewMatrix;
  47952. };
  47953. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47954. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47955. meshes = meshes || this.getScene().meshes;
  47956. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47957. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47958. this.radius = distance * this.zoomOnFactor;
  47959. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47960. };
  47961. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47962. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47963. var meshesOrMinMaxVector;
  47964. var distance;
  47965. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47966. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47967. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47968. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47969. }
  47970. else { //minMaxVector and distance
  47971. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47972. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47973. distance = minMaxVectorAndDistance.distance;
  47974. }
  47975. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47976. if (!doNotUpdateMaxZ) {
  47977. this.maxZ = distance * 2;
  47978. }
  47979. };
  47980. /**
  47981. * @override
  47982. * Override Camera.createRigCamera
  47983. */
  47984. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47985. var alphaShift = 0;
  47986. switch (this.cameraRigMode) {
  47987. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47989. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47990. case BABYLON.Camera.RIG_MODE_VR:
  47991. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47992. break;
  47993. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47994. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47995. break;
  47996. }
  47997. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47998. rigCam._cameraRigParams = {};
  47999. return rigCam;
  48000. };
  48001. /**
  48002. * @override
  48003. * Override Camera._updateRigCameras
  48004. */
  48005. ArcRotateCamera.prototype._updateRigCameras = function () {
  48006. var camLeft = this._rigCameras[0];
  48007. var camRight = this._rigCameras[1];
  48008. camLeft.beta = camRight.beta = this.beta;
  48009. camLeft.radius = camRight.radius = this.radius;
  48010. switch (this.cameraRigMode) {
  48011. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48012. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48013. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48014. case BABYLON.Camera.RIG_MODE_VR:
  48015. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48016. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48017. break;
  48018. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48019. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48020. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48021. break;
  48022. }
  48023. _super.prototype._updateRigCameras.call(this);
  48024. };
  48025. ArcRotateCamera.prototype.dispose = function () {
  48026. this.inputs.clear();
  48027. _super.prototype.dispose.call(this);
  48028. };
  48029. ArcRotateCamera.prototype.getClassName = function () {
  48030. return "ArcRotateCamera";
  48031. };
  48032. __decorate([
  48033. BABYLON.serialize()
  48034. ], ArcRotateCamera.prototype, "alpha", void 0);
  48035. __decorate([
  48036. BABYLON.serialize()
  48037. ], ArcRotateCamera.prototype, "beta", void 0);
  48038. __decorate([
  48039. BABYLON.serialize()
  48040. ], ArcRotateCamera.prototype, "radius", void 0);
  48041. __decorate([
  48042. BABYLON.serializeAsVector3("target")
  48043. ], ArcRotateCamera.prototype, "_target", void 0);
  48044. __decorate([
  48045. BABYLON.serialize()
  48046. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48047. __decorate([
  48048. BABYLON.serialize()
  48049. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48050. __decorate([
  48051. BABYLON.serialize()
  48052. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48053. __decorate([
  48054. BABYLON.serialize()
  48055. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48056. __decorate([
  48057. BABYLON.serialize()
  48058. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48059. __decorate([
  48060. BABYLON.serialize()
  48061. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48062. __decorate([
  48063. BABYLON.serialize()
  48064. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48065. __decorate([
  48066. BABYLON.serialize()
  48067. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48068. __decorate([
  48069. BABYLON.serialize()
  48070. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48071. __decorate([
  48072. BABYLON.serialize()
  48073. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48074. __decorate([
  48075. BABYLON.serialize()
  48076. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48077. __decorate([
  48078. BABYLON.serialize()
  48079. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48080. __decorate([
  48081. BABYLON.serialize()
  48082. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48083. __decorate([
  48084. BABYLON.serializeAsVector3()
  48085. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48086. __decorate([
  48087. BABYLON.serialize()
  48088. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48089. __decorate([
  48090. BABYLON.serialize()
  48091. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48092. __decorate([
  48093. BABYLON.serialize()
  48094. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48095. return ArcRotateCamera;
  48096. }(BABYLON.TargetCamera));
  48097. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48098. })(BABYLON || (BABYLON = {}));
  48099. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48100. var BABYLON;
  48101. (function (BABYLON) {
  48102. /**
  48103. * The HemisphericLight simulates the ambient environment light,
  48104. * so the passed direction is the light reflection direction, not the incoming direction.
  48105. */
  48106. var HemisphericLight = /** @class */ (function (_super) {
  48107. __extends(HemisphericLight, _super);
  48108. /**
  48109. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48110. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48111. * The HemisphericLight can't cast shadows.
  48112. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48113. * @param name The friendly name of the light
  48114. * @param direction The direction of the light reflection
  48115. * @param scene The scene the light belongs to
  48116. */
  48117. function HemisphericLight(name, direction, scene) {
  48118. var _this = _super.call(this, name, scene) || this;
  48119. /**
  48120. * The groundColor is the light in the opposite direction to the one specified during creation.
  48121. * 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.
  48122. */
  48123. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48124. _this.direction = direction || BABYLON.Vector3.Up();
  48125. return _this;
  48126. }
  48127. HemisphericLight.prototype._buildUniformLayout = function () {
  48128. this._uniformBuffer.addUniform("vLightData", 4);
  48129. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48130. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48131. this._uniformBuffer.addUniform("vLightGround", 3);
  48132. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48133. this._uniformBuffer.addUniform("depthValues", 2);
  48134. this._uniformBuffer.create();
  48135. };
  48136. /**
  48137. * Returns the string "HemisphericLight".
  48138. * @return The class name
  48139. */
  48140. HemisphericLight.prototype.getClassName = function () {
  48141. return "HemisphericLight";
  48142. };
  48143. /**
  48144. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48145. * Returns the updated direction.
  48146. * @param target The target the direction should point to
  48147. * @return The computed direction
  48148. */
  48149. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48150. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48151. return this.direction;
  48152. };
  48153. /**
  48154. * Returns the shadow generator associated to the light.
  48155. * @returns Always null for hemispheric lights because it does not support shadows.
  48156. */
  48157. HemisphericLight.prototype.getShadowGenerator = function () {
  48158. return null;
  48159. };
  48160. /**
  48161. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48162. * @param effect The effect to update
  48163. * @param lightIndex The index of the light in the effect to update
  48164. * @returns The hemispheric light
  48165. */
  48166. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48167. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48168. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48169. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48170. return this;
  48171. };
  48172. /**
  48173. * @hidden internal use only.
  48174. */
  48175. HemisphericLight.prototype._getWorldMatrix = function () {
  48176. if (!this._worldMatrix) {
  48177. this._worldMatrix = BABYLON.Matrix.Identity();
  48178. }
  48179. return this._worldMatrix;
  48180. };
  48181. /**
  48182. * Returns the integer 3.
  48183. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48184. */
  48185. HemisphericLight.prototype.getTypeID = function () {
  48186. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48187. };
  48188. __decorate([
  48189. BABYLON.serializeAsColor3()
  48190. ], HemisphericLight.prototype, "groundColor", void 0);
  48191. __decorate([
  48192. BABYLON.serializeAsVector3()
  48193. ], HemisphericLight.prototype, "direction", void 0);
  48194. return HemisphericLight;
  48195. }(BABYLON.Light));
  48196. BABYLON.HemisphericLight = HemisphericLight;
  48197. })(BABYLON || (BABYLON = {}));
  48198. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48199. var BABYLON;
  48200. (function (BABYLON) {
  48201. /**
  48202. * Base implementation IShadowLight
  48203. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48204. */
  48205. var ShadowLight = /** @class */ (function (_super) {
  48206. __extends(ShadowLight, _super);
  48207. function ShadowLight() {
  48208. var _this = _super !== null && _super.apply(this, arguments) || this;
  48209. _this._needProjectionMatrixCompute = true;
  48210. return _this;
  48211. }
  48212. ShadowLight.prototype._setPosition = function (value) {
  48213. this._position = value;
  48214. };
  48215. Object.defineProperty(ShadowLight.prototype, "position", {
  48216. /**
  48217. * Sets the position the shadow will be casted from. Also use as the light position for both
  48218. * point and spot lights.
  48219. */
  48220. get: function () {
  48221. return this._position;
  48222. },
  48223. /**
  48224. * Sets the position the shadow will be casted from. Also use as the light position for both
  48225. * point and spot lights.
  48226. */
  48227. set: function (value) {
  48228. this._setPosition(value);
  48229. },
  48230. enumerable: true,
  48231. configurable: true
  48232. });
  48233. ShadowLight.prototype._setDirection = function (value) {
  48234. this._direction = value;
  48235. };
  48236. Object.defineProperty(ShadowLight.prototype, "direction", {
  48237. /**
  48238. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48239. * Also use as the light direction on spot and directional lights.
  48240. */
  48241. get: function () {
  48242. return this._direction;
  48243. },
  48244. /**
  48245. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48246. * Also use as the light direction on spot and directional lights.
  48247. */
  48248. set: function (value) {
  48249. this._setDirection(value);
  48250. },
  48251. enumerable: true,
  48252. configurable: true
  48253. });
  48254. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48255. /**
  48256. * Gets the shadow projection clipping minimum z value.
  48257. */
  48258. get: function () {
  48259. return this._shadowMinZ;
  48260. },
  48261. /**
  48262. * Sets the shadow projection clipping minimum z value.
  48263. */
  48264. set: function (value) {
  48265. this._shadowMinZ = value;
  48266. this.forceProjectionMatrixCompute();
  48267. },
  48268. enumerable: true,
  48269. configurable: true
  48270. });
  48271. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48272. /**
  48273. * Sets the shadow projection clipping maximum z value.
  48274. */
  48275. get: function () {
  48276. return this._shadowMaxZ;
  48277. },
  48278. /**
  48279. * Gets the shadow projection clipping maximum z value.
  48280. */
  48281. set: function (value) {
  48282. this._shadowMaxZ = value;
  48283. this.forceProjectionMatrixCompute();
  48284. },
  48285. enumerable: true,
  48286. configurable: true
  48287. });
  48288. /**
  48289. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48290. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48291. */
  48292. ShadowLight.prototype.computeTransformedInformation = function () {
  48293. if (this.parent && this.parent.getWorldMatrix) {
  48294. if (!this.transformedPosition) {
  48295. this.transformedPosition = BABYLON.Vector3.Zero();
  48296. }
  48297. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48298. // In case the direction is present.
  48299. if (this.direction) {
  48300. if (!this.transformedDirection) {
  48301. this.transformedDirection = BABYLON.Vector3.Zero();
  48302. }
  48303. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48304. }
  48305. return true;
  48306. }
  48307. return false;
  48308. };
  48309. /**
  48310. * Return the depth scale used for the shadow map.
  48311. * @returns the depth scale.
  48312. */
  48313. ShadowLight.prototype.getDepthScale = function () {
  48314. return 50.0;
  48315. };
  48316. /**
  48317. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48318. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48319. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48320. */
  48321. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48322. return this.transformedDirection ? this.transformedDirection : this.direction;
  48323. };
  48324. /**
  48325. * Returns the ShadowLight absolute position in the World.
  48326. * @returns the position vector in world space
  48327. */
  48328. ShadowLight.prototype.getAbsolutePosition = function () {
  48329. return this.transformedPosition ? this.transformedPosition : this.position;
  48330. };
  48331. /**
  48332. * Sets the ShadowLight direction toward the passed target.
  48333. * @param target The point tot target in local space
  48334. * @returns the updated ShadowLight direction
  48335. */
  48336. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48337. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48338. return this.direction;
  48339. };
  48340. /**
  48341. * Returns the light rotation in euler definition.
  48342. * @returns the x y z rotation in local space.
  48343. */
  48344. ShadowLight.prototype.getRotation = function () {
  48345. this.direction.normalize();
  48346. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48347. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48348. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48349. };
  48350. /**
  48351. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48352. * @returns true if a cube texture needs to be use
  48353. */
  48354. ShadowLight.prototype.needCube = function () {
  48355. return false;
  48356. };
  48357. /**
  48358. * Detects if the projection matrix requires to be recomputed this frame.
  48359. * @returns true if it requires to be recomputed otherwise, false.
  48360. */
  48361. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48362. return this._needProjectionMatrixCompute;
  48363. };
  48364. /**
  48365. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48366. */
  48367. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48368. this._needProjectionMatrixCompute = true;
  48369. };
  48370. /**
  48371. * Get the world matrix of the sahdow lights.
  48372. * @hidden Internal Use Only
  48373. */
  48374. ShadowLight.prototype._getWorldMatrix = function () {
  48375. if (!this._worldMatrix) {
  48376. this._worldMatrix = BABYLON.Matrix.Identity();
  48377. }
  48378. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48379. return this._worldMatrix;
  48380. };
  48381. /**
  48382. * Gets the minZ used for shadow according to both the scene and the light.
  48383. * @param activeCamera The camera we are returning the min for
  48384. * @returns the depth min z
  48385. */
  48386. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48387. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48388. };
  48389. /**
  48390. * Gets the maxZ used for shadow according to both the scene and the light.
  48391. * @param activeCamera The camera we are returning the max for
  48392. * @returns the depth max z
  48393. */
  48394. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48395. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48396. };
  48397. /**
  48398. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48399. * @param matrix The materix to updated with the projection information
  48400. * @param viewMatrix The transform matrix of the light
  48401. * @param renderList The list of mesh to render in the map
  48402. * @returns The current light
  48403. */
  48404. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48405. if (this.customProjectionMatrixBuilder) {
  48406. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48407. }
  48408. else {
  48409. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48410. }
  48411. return this;
  48412. };
  48413. __decorate([
  48414. BABYLON.serializeAsVector3()
  48415. ], ShadowLight.prototype, "position", null);
  48416. __decorate([
  48417. BABYLON.serializeAsVector3()
  48418. ], ShadowLight.prototype, "direction", null);
  48419. __decorate([
  48420. BABYLON.serialize()
  48421. ], ShadowLight.prototype, "shadowMinZ", null);
  48422. __decorate([
  48423. BABYLON.serialize()
  48424. ], ShadowLight.prototype, "shadowMaxZ", null);
  48425. return ShadowLight;
  48426. }(BABYLON.Light));
  48427. BABYLON.ShadowLight = ShadowLight;
  48428. })(BABYLON || (BABYLON = {}));
  48429. //# sourceMappingURL=babylon.shadowLight.js.map
  48430. var BABYLON;
  48431. (function (BABYLON) {
  48432. /**
  48433. * A point light is a light defined by an unique point in world space.
  48434. * The light is emitted in every direction from this point.
  48435. * A good example of a point light is a standard light bulb.
  48436. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48437. */
  48438. var PointLight = /** @class */ (function (_super) {
  48439. __extends(PointLight, _super);
  48440. /**
  48441. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48442. * A PointLight emits the light in every direction.
  48443. * It can cast shadows.
  48444. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48445. * ```javascript
  48446. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48447. * ```
  48448. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48449. * @param name The light friendly name
  48450. * @param position The position of the point light in the scene
  48451. * @param scene The scene the lights belongs to
  48452. */
  48453. function PointLight(name, position, scene) {
  48454. var _this = _super.call(this, name, scene) || this;
  48455. _this._shadowAngle = Math.PI / 2;
  48456. _this.position = position;
  48457. return _this;
  48458. }
  48459. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48460. /**
  48461. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48462. * This specifies what angle the shadow will use to be created.
  48463. *
  48464. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48465. */
  48466. get: function () {
  48467. return this._shadowAngle;
  48468. },
  48469. /**
  48470. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48471. * This specifies what angle the shadow will use to be created.
  48472. *
  48473. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48474. */
  48475. set: function (value) {
  48476. this._shadowAngle = value;
  48477. this.forceProjectionMatrixCompute();
  48478. },
  48479. enumerable: true,
  48480. configurable: true
  48481. });
  48482. Object.defineProperty(PointLight.prototype, "direction", {
  48483. /**
  48484. * Gets the direction if it has been set.
  48485. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48486. */
  48487. get: function () {
  48488. return this._direction;
  48489. },
  48490. /**
  48491. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48492. */
  48493. set: function (value) {
  48494. var previousNeedCube = this.needCube();
  48495. this._direction = value;
  48496. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48497. this._shadowGenerator.recreateShadowMap();
  48498. }
  48499. },
  48500. enumerable: true,
  48501. configurable: true
  48502. });
  48503. /**
  48504. * Returns the string "PointLight"
  48505. * @returns the class name
  48506. */
  48507. PointLight.prototype.getClassName = function () {
  48508. return "PointLight";
  48509. };
  48510. /**
  48511. * Returns the integer 0.
  48512. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48513. */
  48514. PointLight.prototype.getTypeID = function () {
  48515. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48516. };
  48517. /**
  48518. * Specifies wether or not the shadowmap should be a cube texture.
  48519. * @returns true if the shadowmap needs to be a cube texture.
  48520. */
  48521. PointLight.prototype.needCube = function () {
  48522. return !this.direction;
  48523. };
  48524. /**
  48525. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48526. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48527. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48528. */
  48529. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48530. if (this.direction) {
  48531. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48532. }
  48533. else {
  48534. switch (faceIndex) {
  48535. case 0:
  48536. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48537. case 1:
  48538. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48539. case 2:
  48540. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48541. case 3:
  48542. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48543. case 4:
  48544. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48545. case 5:
  48546. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48547. }
  48548. }
  48549. return BABYLON.Vector3.Zero();
  48550. };
  48551. /**
  48552. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48553. * - fov = PI / 2
  48554. * - aspect ratio : 1.0
  48555. * - z-near and far equal to the active camera minZ and maxZ.
  48556. * Returns the PointLight.
  48557. */
  48558. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48559. var activeCamera = this.getScene().activeCamera;
  48560. if (!activeCamera) {
  48561. return;
  48562. }
  48563. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48564. };
  48565. PointLight.prototype._buildUniformLayout = function () {
  48566. this._uniformBuffer.addUniform("vLightData", 4);
  48567. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48568. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48569. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48570. this._uniformBuffer.addUniform("depthValues", 2);
  48571. this._uniformBuffer.create();
  48572. };
  48573. /**
  48574. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48575. * @param effect The effect to update
  48576. * @param lightIndex The index of the light in the effect to update
  48577. * @returns The point light
  48578. */
  48579. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48580. if (this.computeTransformedInformation()) {
  48581. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48582. return this;
  48583. }
  48584. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48585. return this;
  48586. };
  48587. __decorate([
  48588. BABYLON.serialize()
  48589. ], PointLight.prototype, "shadowAngle", null);
  48590. return PointLight;
  48591. }(BABYLON.ShadowLight));
  48592. BABYLON.PointLight = PointLight;
  48593. })(BABYLON || (BABYLON = {}));
  48594. //# sourceMappingURL=babylon.pointLight.js.map
  48595. var BABYLON;
  48596. (function (BABYLON) {
  48597. /**
  48598. * A directional light is defined by a direction (what a surprise!).
  48599. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48600. * 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.
  48601. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48602. */
  48603. var DirectionalLight = /** @class */ (function (_super) {
  48604. __extends(DirectionalLight, _super);
  48605. /**
  48606. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48607. * The directional light is emitted from everywhere in the given direction.
  48608. * It can cast shawdows.
  48609. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48610. * @param name The friendly name of the light
  48611. * @param direction The direction of the light
  48612. * @param scene The scene the light belongs to
  48613. */
  48614. function DirectionalLight(name, direction, scene) {
  48615. var _this = _super.call(this, name, scene) || this;
  48616. _this._shadowFrustumSize = 0;
  48617. _this._shadowOrthoScale = 0.1;
  48618. /**
  48619. * Automatically compute the projection matrix to best fit (including all the casters)
  48620. * on each frame.
  48621. */
  48622. _this.autoUpdateExtends = true;
  48623. // Cache
  48624. _this._orthoLeft = Number.MAX_VALUE;
  48625. _this._orthoRight = Number.MIN_VALUE;
  48626. _this._orthoTop = Number.MIN_VALUE;
  48627. _this._orthoBottom = Number.MAX_VALUE;
  48628. _this.position = direction.scale(-1.0);
  48629. _this.direction = direction;
  48630. return _this;
  48631. }
  48632. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48633. /**
  48634. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48635. */
  48636. get: function () {
  48637. return this._shadowFrustumSize;
  48638. },
  48639. /**
  48640. * Specifies a fix frustum size for the shadow generation.
  48641. */
  48642. set: function (value) {
  48643. this._shadowFrustumSize = value;
  48644. this.forceProjectionMatrixCompute();
  48645. },
  48646. enumerable: true,
  48647. configurable: true
  48648. });
  48649. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48650. /**
  48651. * Gets the shadow projection scale against the optimal computed one.
  48652. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48653. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48654. */
  48655. get: function () {
  48656. return this._shadowOrthoScale;
  48657. },
  48658. /**
  48659. * Sets the shadow projection scale against the optimal computed one.
  48660. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48661. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48662. */
  48663. set: function (value) {
  48664. this._shadowOrthoScale = value;
  48665. this.forceProjectionMatrixCompute();
  48666. },
  48667. enumerable: true,
  48668. configurable: true
  48669. });
  48670. /**
  48671. * Returns the string "DirectionalLight".
  48672. * @return The class name
  48673. */
  48674. DirectionalLight.prototype.getClassName = function () {
  48675. return "DirectionalLight";
  48676. };
  48677. /**
  48678. * Returns the integer 1.
  48679. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48680. */
  48681. DirectionalLight.prototype.getTypeID = function () {
  48682. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48683. };
  48684. /**
  48685. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48686. * Returns the DirectionalLight Shadow projection matrix.
  48687. */
  48688. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48689. if (this.shadowFrustumSize > 0) {
  48690. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48691. }
  48692. else {
  48693. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48694. }
  48695. };
  48696. /**
  48697. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48698. * Returns the DirectionalLight Shadow projection matrix.
  48699. */
  48700. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48701. var activeCamera = this.getScene().activeCamera;
  48702. if (!activeCamera) {
  48703. return;
  48704. }
  48705. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48706. };
  48707. /**
  48708. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48709. * Returns the DirectionalLight Shadow projection matrix.
  48710. */
  48711. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48712. var activeCamera = this.getScene().activeCamera;
  48713. if (!activeCamera) {
  48714. return;
  48715. }
  48716. // Check extends
  48717. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48718. var tempVector3 = BABYLON.Vector3.Zero();
  48719. this._orthoLeft = Number.MAX_VALUE;
  48720. this._orthoRight = Number.MIN_VALUE;
  48721. this._orthoTop = Number.MIN_VALUE;
  48722. this._orthoBottom = Number.MAX_VALUE;
  48723. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48724. var mesh = renderList[meshIndex];
  48725. if (!mesh) {
  48726. continue;
  48727. }
  48728. var boundingInfo = mesh.getBoundingInfo();
  48729. var boundingBox = boundingInfo.boundingBox;
  48730. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48731. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48732. if (tempVector3.x < this._orthoLeft)
  48733. this._orthoLeft = tempVector3.x;
  48734. if (tempVector3.y < this._orthoBottom)
  48735. this._orthoBottom = tempVector3.y;
  48736. if (tempVector3.x > this._orthoRight)
  48737. this._orthoRight = tempVector3.x;
  48738. if (tempVector3.y > this._orthoTop)
  48739. this._orthoTop = tempVector3.y;
  48740. }
  48741. }
  48742. }
  48743. var xOffset = this._orthoRight - this._orthoLeft;
  48744. var yOffset = this._orthoTop - this._orthoBottom;
  48745. 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);
  48746. };
  48747. DirectionalLight.prototype._buildUniformLayout = function () {
  48748. this._uniformBuffer.addUniform("vLightData", 4);
  48749. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48750. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48751. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48752. this._uniformBuffer.addUniform("depthValues", 2);
  48753. this._uniformBuffer.create();
  48754. };
  48755. /**
  48756. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48757. * @param effect The effect to update
  48758. * @param lightIndex The index of the light in the effect to update
  48759. * @returns The directional light
  48760. */
  48761. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48762. if (this.computeTransformedInformation()) {
  48763. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48764. return this;
  48765. }
  48766. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48767. return this;
  48768. };
  48769. /**
  48770. * Gets the minZ used for shadow according to both the scene and the light.
  48771. *
  48772. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48773. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48774. * @param activeCamera The camera we are returning the min for
  48775. * @returns the depth min z
  48776. */
  48777. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48778. return 1;
  48779. };
  48780. /**
  48781. * Gets the maxZ used for shadow according to both the scene and the light.
  48782. *
  48783. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48784. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48785. * @param activeCamera The camera we are returning the max for
  48786. * @returns the depth max z
  48787. */
  48788. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48789. return 1;
  48790. };
  48791. __decorate([
  48792. BABYLON.serialize()
  48793. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48794. __decorate([
  48795. BABYLON.serialize()
  48796. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48797. __decorate([
  48798. BABYLON.serialize()
  48799. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48800. return DirectionalLight;
  48801. }(BABYLON.ShadowLight));
  48802. BABYLON.DirectionalLight = DirectionalLight;
  48803. })(BABYLON || (BABYLON = {}));
  48804. //# sourceMappingURL=babylon.directionalLight.js.map
  48805. var BABYLON;
  48806. (function (BABYLON) {
  48807. /**
  48808. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48809. * These values define a cone of light starting from the position, emitting toward the direction.
  48810. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48811. * and the exponent defines the speed of the decay of the light with distance (reach).
  48812. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48813. */
  48814. var SpotLight = /** @class */ (function (_super) {
  48815. __extends(SpotLight, _super);
  48816. /**
  48817. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48818. * It can cast shadows.
  48819. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48820. * @param name The light friendly name
  48821. * @param position The position of the spot light in the scene
  48822. * @param direction The direction of the light in the scene
  48823. * @param angle The cone angle of the light in Radians
  48824. * @param exponent The light decay speed with the distance from the emission spot
  48825. * @param scene The scene the lights belongs to
  48826. */
  48827. function SpotLight(name, position, direction, angle, exponent, scene) {
  48828. var _this = _super.call(this, name, scene) || this;
  48829. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48830. _this._projectionTextureLightNear = 1e-6;
  48831. _this._projectionTextureLightFar = 1000.0;
  48832. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48833. _this._projectionTextureViewLightDirty = true;
  48834. _this._projectionTextureProjectionLightDirty = true;
  48835. _this._projectionTextureDirty = true;
  48836. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48837. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48838. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48839. _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);
  48840. _this.position = position;
  48841. _this.direction = direction;
  48842. _this.angle = angle;
  48843. _this.exponent = exponent;
  48844. return _this;
  48845. }
  48846. Object.defineProperty(SpotLight.prototype, "angle", {
  48847. /**
  48848. * Gets the cone angle of the spot light in Radians.
  48849. */
  48850. get: function () {
  48851. return this._angle;
  48852. },
  48853. /**
  48854. * Sets the cone angle of the spot light in Radians.
  48855. */
  48856. set: function (value) {
  48857. this._angle = value;
  48858. this._projectionTextureProjectionLightDirty = true;
  48859. this.forceProjectionMatrixCompute();
  48860. },
  48861. enumerable: true,
  48862. configurable: true
  48863. });
  48864. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48865. /**
  48866. * Allows scaling the angle of the light for shadow generation only.
  48867. */
  48868. get: function () {
  48869. return this._shadowAngleScale;
  48870. },
  48871. /**
  48872. * Allows scaling the angle of the light for shadow generation only.
  48873. */
  48874. set: function (value) {
  48875. this._shadowAngleScale = value;
  48876. this.forceProjectionMatrixCompute();
  48877. },
  48878. enumerable: true,
  48879. configurable: true
  48880. });
  48881. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48882. /**
  48883. * Allows reading the projecton texture
  48884. */
  48885. get: function () {
  48886. return this._projectionTextureMatrix;
  48887. },
  48888. enumerable: true,
  48889. configurable: true
  48890. });
  48891. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48892. /**
  48893. * Gets the near clip of the Spotlight for texture projection.
  48894. */
  48895. get: function () {
  48896. return this._projectionTextureLightNear;
  48897. },
  48898. /**
  48899. * Sets the near clip of the Spotlight for texture projection.
  48900. */
  48901. set: function (value) {
  48902. this._projectionTextureLightNear = value;
  48903. this._projectionTextureProjectionLightDirty = true;
  48904. },
  48905. enumerable: true,
  48906. configurable: true
  48907. });
  48908. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48909. /**
  48910. * Gets the far clip of the Spotlight for texture projection.
  48911. */
  48912. get: function () {
  48913. return this._projectionTextureLightFar;
  48914. },
  48915. /**
  48916. * Sets the far clip of the Spotlight for texture projection.
  48917. */
  48918. set: function (value) {
  48919. this._projectionTextureLightFar = value;
  48920. this._projectionTextureProjectionLightDirty = true;
  48921. },
  48922. enumerable: true,
  48923. configurable: true
  48924. });
  48925. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48926. /**
  48927. * Gets the Up vector of the Spotlight for texture projection.
  48928. */
  48929. get: function () {
  48930. return this._projectionTextureUpDirection;
  48931. },
  48932. /**
  48933. * Sets the Up vector of the Spotlight for texture projection.
  48934. */
  48935. set: function (value) {
  48936. this._projectionTextureUpDirection = value;
  48937. this._projectionTextureProjectionLightDirty = true;
  48938. },
  48939. enumerable: true,
  48940. configurable: true
  48941. });
  48942. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48943. /**
  48944. * Gets the projection texture of the light.
  48945. */
  48946. get: function () {
  48947. return this._projectionTexture;
  48948. },
  48949. /**
  48950. * Sets the projection texture of the light.
  48951. */
  48952. set: function (value) {
  48953. this._projectionTexture = value;
  48954. this._projectionTextureDirty = true;
  48955. },
  48956. enumerable: true,
  48957. configurable: true
  48958. });
  48959. /**
  48960. * Returns the string "SpotLight".
  48961. * @returns the class name
  48962. */
  48963. SpotLight.prototype.getClassName = function () {
  48964. return "SpotLight";
  48965. };
  48966. /**
  48967. * Returns the integer 2.
  48968. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48969. */
  48970. SpotLight.prototype.getTypeID = function () {
  48971. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48972. };
  48973. /**
  48974. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48975. */
  48976. SpotLight.prototype._setDirection = function (value) {
  48977. _super.prototype._setDirection.call(this, value);
  48978. this._projectionTextureViewLightDirty = true;
  48979. };
  48980. /**
  48981. * Overrides the position setter to recompute the projection texture view light Matrix.
  48982. */
  48983. SpotLight.prototype._setPosition = function (value) {
  48984. _super.prototype._setPosition.call(this, value);
  48985. this._projectionTextureViewLightDirty = true;
  48986. };
  48987. /**
  48988. * 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.
  48989. * Returns the SpotLight.
  48990. */
  48991. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48992. var activeCamera = this.getScene().activeCamera;
  48993. if (!activeCamera) {
  48994. return;
  48995. }
  48996. this._shadowAngleScale = this._shadowAngleScale || 1;
  48997. var angle = this._shadowAngleScale * this._angle;
  48998. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48999. };
  49000. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49001. this._projectionTextureViewLightDirty = false;
  49002. this._projectionTextureDirty = true;
  49003. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49004. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49005. };
  49006. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49007. this._projectionTextureProjectionLightDirty = false;
  49008. this._projectionTextureDirty = true;
  49009. var light_far = this.projectionTextureLightFar;
  49010. var light_near = this.projectionTextureLightNear;
  49011. var P = light_far / (light_far - light_near);
  49012. var Q = -P * light_near;
  49013. var S = 1.0 / Math.tan(this._angle / 2.0);
  49014. var A = 1.0;
  49015. 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);
  49016. };
  49017. /**
  49018. * Main function for light texture projection matrix computing.
  49019. */
  49020. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49021. this._projectionTextureDirty = false;
  49022. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49023. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49024. };
  49025. SpotLight.prototype._buildUniformLayout = function () {
  49026. this._uniformBuffer.addUniform("vLightData", 4);
  49027. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49028. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49029. this._uniformBuffer.addUniform("vLightDirection", 3);
  49030. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49031. this._uniformBuffer.addUniform("depthValues", 2);
  49032. this._uniformBuffer.create();
  49033. };
  49034. /**
  49035. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49036. * @param effect The effect to update
  49037. * @param lightIndex The index of the light in the effect to update
  49038. * @returns The spot light
  49039. */
  49040. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49041. var normalizeDirection;
  49042. if (this.computeTransformedInformation()) {
  49043. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49044. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49045. }
  49046. else {
  49047. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49048. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49049. }
  49050. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49051. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49052. if (this._projectionTextureViewLightDirty) {
  49053. this._computeProjectionTextureViewLightMatrix();
  49054. }
  49055. if (this._projectionTextureProjectionLightDirty) {
  49056. this._computeProjectionTextureProjectionLightMatrix();
  49057. }
  49058. if (this._projectionTextureDirty) {
  49059. this._computeProjectionTextureMatrix();
  49060. }
  49061. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49062. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49063. }
  49064. return this;
  49065. };
  49066. /**
  49067. * Disposes the light and the associated resources.
  49068. */
  49069. SpotLight.prototype.dispose = function () {
  49070. _super.prototype.dispose.call(this);
  49071. if (this._projectionTexture) {
  49072. this._projectionTexture.dispose();
  49073. }
  49074. };
  49075. __decorate([
  49076. BABYLON.serialize()
  49077. ], SpotLight.prototype, "angle", null);
  49078. __decorate([
  49079. BABYLON.serialize()
  49080. ], SpotLight.prototype, "shadowAngleScale", null);
  49081. __decorate([
  49082. BABYLON.serialize()
  49083. ], SpotLight.prototype, "exponent", void 0);
  49084. __decorate([
  49085. BABYLON.serialize()
  49086. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49087. __decorate([
  49088. BABYLON.serialize()
  49089. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49090. __decorate([
  49091. BABYLON.serialize()
  49092. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49093. __decorate([
  49094. BABYLON.serializeAsTexture("projectedLightTexture")
  49095. ], SpotLight.prototype, "_projectionTexture", void 0);
  49096. return SpotLight;
  49097. }(BABYLON.ShadowLight));
  49098. BABYLON.SpotLight = SpotLight;
  49099. })(BABYLON || (BABYLON = {}));
  49100. //# sourceMappingURL=babylon.spotLight.js.map
  49101. var BABYLON;
  49102. (function (BABYLON) {
  49103. /**
  49104. * Class used to override all child animations of a given target
  49105. */
  49106. var AnimationPropertiesOverride = /** @class */ (function () {
  49107. function AnimationPropertiesOverride() {
  49108. /**
  49109. * Gets or sets a value indicating if animation blending must be used
  49110. */
  49111. this.enableBlending = false;
  49112. /**
  49113. * Gets or sets the blending speed to use when enableBlending is true
  49114. */
  49115. this.blendingSpeed = 0.01;
  49116. /**
  49117. * Gets or sets the default loop mode to use
  49118. */
  49119. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49120. }
  49121. return AnimationPropertiesOverride;
  49122. }());
  49123. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49124. })(BABYLON || (BABYLON = {}));
  49125. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49126. var BABYLON;
  49127. (function (BABYLON) {
  49128. /**
  49129. * Represents the range of an animation
  49130. */
  49131. var AnimationRange = /** @class */ (function () {
  49132. /**
  49133. * Initializes the range of an animation
  49134. * @param name The name of the animation range
  49135. * @param from The starting frame of the animation
  49136. * @param to The ending frame of the animation
  49137. */
  49138. function AnimationRange(
  49139. /**The name of the animation range**/
  49140. name,
  49141. /**The starting frame of the animation */
  49142. from,
  49143. /**The ending frame of the animation*/
  49144. to) {
  49145. this.name = name;
  49146. this.from = from;
  49147. this.to = to;
  49148. }
  49149. /**
  49150. * Makes a copy of the animation range
  49151. * @returns A copy of the animation range
  49152. */
  49153. AnimationRange.prototype.clone = function () {
  49154. return new AnimationRange(this.name, this.from, this.to);
  49155. };
  49156. return AnimationRange;
  49157. }());
  49158. BABYLON.AnimationRange = AnimationRange;
  49159. /**
  49160. * Composed of a frame, and an action function
  49161. */
  49162. var AnimationEvent = /** @class */ (function () {
  49163. /**
  49164. * Initializes the animation event
  49165. * @param frame The frame for which the event is triggered
  49166. * @param action The event to perform when triggered
  49167. * @param onlyOnce Specifies if the event should be triggered only once
  49168. */
  49169. function AnimationEvent(
  49170. /** The frame for which the event is triggered **/
  49171. frame,
  49172. /** The event to perform when triggered **/
  49173. action,
  49174. /** Specifies if the event should be triggered only once**/
  49175. onlyOnce) {
  49176. this.frame = frame;
  49177. this.action = action;
  49178. this.onlyOnce = onlyOnce;
  49179. /**
  49180. * Specifies if the animation event is done
  49181. */
  49182. this.isDone = false;
  49183. }
  49184. /** @hidden */
  49185. AnimationEvent.prototype._clone = function () {
  49186. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49187. };
  49188. return AnimationEvent;
  49189. }());
  49190. BABYLON.AnimationEvent = AnimationEvent;
  49191. /**
  49192. * A cursor which tracks a point on a path
  49193. */
  49194. var PathCursor = /** @class */ (function () {
  49195. /**
  49196. * Initializes the path cursor
  49197. * @param path The path to track
  49198. */
  49199. function PathCursor(path) {
  49200. this.path = path;
  49201. /**
  49202. * Stores path cursor callbacks for when an onchange event is triggered
  49203. */
  49204. this._onchange = new Array();
  49205. /**
  49206. * The value of the path cursor
  49207. */
  49208. this.value = 0;
  49209. /**
  49210. * The animation array of the path cursor
  49211. */
  49212. this.animations = new Array();
  49213. }
  49214. /**
  49215. * Gets the cursor point on the path
  49216. * @returns A point on the path cursor at the cursor location
  49217. */
  49218. PathCursor.prototype.getPoint = function () {
  49219. var point = this.path.getPointAtLengthPosition(this.value);
  49220. return new BABYLON.Vector3(point.x, 0, point.y);
  49221. };
  49222. /**
  49223. * Moves the cursor ahead by the step amount
  49224. * @param step The amount to move the cursor forward
  49225. * @returns This path cursor
  49226. */
  49227. PathCursor.prototype.moveAhead = function (step) {
  49228. if (step === void 0) { step = 0.002; }
  49229. this.move(step);
  49230. return this;
  49231. };
  49232. /**
  49233. * Moves the cursor behind by the step amount
  49234. * @param step The amount to move the cursor back
  49235. * @returns This path cursor
  49236. */
  49237. PathCursor.prototype.moveBack = function (step) {
  49238. if (step === void 0) { step = 0.002; }
  49239. this.move(-step);
  49240. return this;
  49241. };
  49242. /**
  49243. * Moves the cursor by the step amount
  49244. * If the step amount is greater than one, an exception is thrown
  49245. * @param step The amount to move the cursor
  49246. * @returns This path cursor
  49247. */
  49248. PathCursor.prototype.move = function (step) {
  49249. if (Math.abs(step) > 1) {
  49250. throw "step size should be less than 1.";
  49251. }
  49252. this.value += step;
  49253. this.ensureLimits();
  49254. this.raiseOnChange();
  49255. return this;
  49256. };
  49257. /**
  49258. * Ensures that the value is limited between zero and one
  49259. * @returns This path cursor
  49260. */
  49261. PathCursor.prototype.ensureLimits = function () {
  49262. while (this.value > 1) {
  49263. this.value -= 1;
  49264. }
  49265. while (this.value < 0) {
  49266. this.value += 1;
  49267. }
  49268. return this;
  49269. };
  49270. /**
  49271. * Runs onchange callbacks on change (used by the animation engine)
  49272. * @returns This path cursor
  49273. */
  49274. PathCursor.prototype.raiseOnChange = function () {
  49275. var _this = this;
  49276. this._onchange.forEach(function (f) { return f(_this); });
  49277. return this;
  49278. };
  49279. /**
  49280. * Executes a function on change
  49281. * @param f A path cursor onchange callback
  49282. * @returns This path cursor
  49283. */
  49284. PathCursor.prototype.onchange = function (f) {
  49285. this._onchange.push(f);
  49286. return this;
  49287. };
  49288. return PathCursor;
  49289. }());
  49290. BABYLON.PathCursor = PathCursor;
  49291. /**
  49292. * Enum for the animation key frame interpolation type
  49293. */
  49294. var AnimationKeyInterpolation;
  49295. (function (AnimationKeyInterpolation) {
  49296. /**
  49297. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49298. */
  49299. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49300. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49301. /**
  49302. * Class used to store any kind of animation
  49303. */
  49304. var Animation = /** @class */ (function () {
  49305. /**
  49306. * Initializes the animation
  49307. * @param name Name of the animation
  49308. * @param targetProperty Property to animate
  49309. * @param framePerSecond The frames per second of the animation
  49310. * @param dataType The data type of the animation
  49311. * @param loopMode The loop mode of the animation
  49312. * @param enableBlendings Specifies if blending should be enabled
  49313. */
  49314. function Animation(
  49315. /**Name of the animation */
  49316. name,
  49317. /**Property to animate */
  49318. targetProperty,
  49319. /**The frames per second of the animation */
  49320. framePerSecond,
  49321. /**The data type of the animation */
  49322. dataType,
  49323. /**The loop mode of the animation */
  49324. loopMode,
  49325. /**Specifies if blending should be enabled */
  49326. enableBlending) {
  49327. this.name = name;
  49328. this.targetProperty = targetProperty;
  49329. this.framePerSecond = framePerSecond;
  49330. this.dataType = dataType;
  49331. this.loopMode = loopMode;
  49332. this.enableBlending = enableBlending;
  49333. /**
  49334. * @hidden Internal use only
  49335. */
  49336. this._runtimeAnimations = new Array();
  49337. /**
  49338. * The set of event that will be linked to this animation
  49339. */
  49340. this._events = new Array();
  49341. /**
  49342. * Stores the blending speed of the animation
  49343. */
  49344. this.blendingSpeed = 0.01;
  49345. /**
  49346. * Stores the animation ranges for the animation
  49347. */
  49348. this._ranges = {};
  49349. this.targetPropertyPath = targetProperty.split(".");
  49350. this.dataType = dataType;
  49351. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49352. }
  49353. /**
  49354. * @hidden Internal use
  49355. */
  49356. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49357. var dataType = undefined;
  49358. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49359. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49360. }
  49361. else if (from instanceof BABYLON.Quaternion) {
  49362. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49363. }
  49364. else if (from instanceof BABYLON.Vector3) {
  49365. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49366. }
  49367. else if (from instanceof BABYLON.Vector2) {
  49368. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49369. }
  49370. else if (from instanceof BABYLON.Color3) {
  49371. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49372. }
  49373. else if (from instanceof BABYLON.Size) {
  49374. dataType = Animation.ANIMATIONTYPE_SIZE;
  49375. }
  49376. if (dataType == undefined) {
  49377. return null;
  49378. }
  49379. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49380. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49381. animation.setKeys(keys);
  49382. if (easingFunction !== undefined) {
  49383. animation.setEasingFunction(easingFunction);
  49384. }
  49385. return animation;
  49386. };
  49387. /**
  49388. * Sets up an animation
  49389. * @param property The property to animate
  49390. * @param animationType The animation type to apply
  49391. * @param framePerSecond The frames per second of the animation
  49392. * @param easingFunction The easing function used in the animation
  49393. * @returns The created animation
  49394. */
  49395. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49396. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49397. animation.setEasingFunction(easingFunction);
  49398. return animation;
  49399. };
  49400. /**
  49401. * Create and start an animation on a node
  49402. * @param name defines the name of the global animation that will be run on all nodes
  49403. * @param node defines the root node where the animation will take place
  49404. * @param targetProperty defines property to animate
  49405. * @param framePerSecond defines the number of frame per second yo use
  49406. * @param totalFrame defines the number of frames in total
  49407. * @param from defines the initial value
  49408. * @param to defines the final value
  49409. * @param loopMode defines which loop mode you want to use (off by default)
  49410. * @param easingFunction defines the easing function to use (linear by default)
  49411. * @param onAnimationEnd defines the callback to call when animation end
  49412. * @returns the animatable created for this animation
  49413. */
  49414. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49415. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49416. if (!animation) {
  49417. return null;
  49418. }
  49419. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49420. };
  49421. /**
  49422. * Create and start an animation on a node and its descendants
  49423. * @param name defines the name of the global animation that will be run on all nodes
  49424. * @param node defines the root node where the animation will take place
  49425. * @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
  49426. * @param targetProperty defines property to animate
  49427. * @param framePerSecond defines the number of frame per second to use
  49428. * @param totalFrame defines the number of frames in total
  49429. * @param from defines the initial value
  49430. * @param to defines the final value
  49431. * @param loopMode defines which loop mode you want to use (off by default)
  49432. * @param easingFunction defines the easing function to use (linear by default)
  49433. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49434. * @returns the list of animatables created for all nodes
  49435. * @example https://www.babylonjs-playground.com/#MH0VLI
  49436. */
  49437. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49438. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49439. if (!animation) {
  49440. return null;
  49441. }
  49442. var scene = node.getScene();
  49443. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49444. };
  49445. /**
  49446. * Creates a new animation, merges it with the existing animations and starts it
  49447. * @param name Name of the animation
  49448. * @param node Node which contains the scene that begins the animations
  49449. * @param targetProperty Specifies which property to animate
  49450. * @param framePerSecond The frames per second of the animation
  49451. * @param totalFrame The total number of frames
  49452. * @param from The frame at the beginning of the animation
  49453. * @param to The frame at the end of the animation
  49454. * @param loopMode Specifies the loop mode of the animation
  49455. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49456. * @param onAnimationEnd Callback to run once the animation is complete
  49457. * @returns Nullable animation
  49458. */
  49459. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49460. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49461. if (!animation) {
  49462. return null;
  49463. }
  49464. node.animations.push(animation);
  49465. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49466. };
  49467. /**
  49468. * Transition property of an host to the target Value
  49469. * @param property The property to transition
  49470. * @param targetValue The target Value of the property
  49471. * @param host The object where the property to animate belongs
  49472. * @param scene Scene used to run the animation
  49473. * @param frameRate Framerate (in frame/s) to use
  49474. * @param transition The transition type we want to use
  49475. * @param duration The duration of the animation, in milliseconds
  49476. * @param onAnimationEnd Callback trigger at the end of the animation
  49477. * @returns Nullable animation
  49478. */
  49479. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49480. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49481. if (duration <= 0) {
  49482. host[property] = targetValue;
  49483. if (onAnimationEnd) {
  49484. onAnimationEnd();
  49485. }
  49486. return null;
  49487. }
  49488. var endFrame = frameRate * (duration / 1000);
  49489. transition.setKeys([{
  49490. frame: 0,
  49491. value: host[property].clone ? host[property].clone() : host[property]
  49492. },
  49493. {
  49494. frame: endFrame,
  49495. value: targetValue
  49496. }]);
  49497. if (!host.animations) {
  49498. host.animations = [];
  49499. }
  49500. host.animations.push(transition);
  49501. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49502. animation.onAnimationEnd = onAnimationEnd;
  49503. return animation;
  49504. };
  49505. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49506. /**
  49507. * Return the array of runtime animations currently using this animation
  49508. */
  49509. get: function () {
  49510. return this._runtimeAnimations;
  49511. },
  49512. enumerable: true,
  49513. configurable: true
  49514. });
  49515. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49516. /**
  49517. * Specifies if any of the runtime animations are currently running
  49518. */
  49519. get: function () {
  49520. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49521. var runtimeAnimation = _a[_i];
  49522. if (!runtimeAnimation.isStopped) {
  49523. return true;
  49524. }
  49525. }
  49526. return false;
  49527. },
  49528. enumerable: true,
  49529. configurable: true
  49530. });
  49531. // Methods
  49532. /**
  49533. * Converts the animation to a string
  49534. * @param fullDetails support for multiple levels of logging within scene loading
  49535. * @returns String form of the animation
  49536. */
  49537. Animation.prototype.toString = function (fullDetails) {
  49538. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49539. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49540. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49541. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49542. if (fullDetails) {
  49543. ret += ", Ranges: {";
  49544. var first = true;
  49545. for (var name in this._ranges) {
  49546. if (first) {
  49547. ret += ", ";
  49548. first = false;
  49549. }
  49550. ret += name;
  49551. }
  49552. ret += "}";
  49553. }
  49554. return ret;
  49555. };
  49556. /**
  49557. * Add an event to this animation
  49558. * @param event Event to add
  49559. */
  49560. Animation.prototype.addEvent = function (event) {
  49561. this._events.push(event);
  49562. };
  49563. /**
  49564. * Remove all events found at the given frame
  49565. * @param frame The frame to remove events from
  49566. */
  49567. Animation.prototype.removeEvents = function (frame) {
  49568. for (var index = 0; index < this._events.length; index++) {
  49569. if (this._events[index].frame === frame) {
  49570. this._events.splice(index, 1);
  49571. index--;
  49572. }
  49573. }
  49574. };
  49575. /**
  49576. * Retrieves all the events from the animation
  49577. * @returns Events from the animation
  49578. */
  49579. Animation.prototype.getEvents = function () {
  49580. return this._events;
  49581. };
  49582. /**
  49583. * Creates an animation range
  49584. * @param name Name of the animation range
  49585. * @param from Starting frame of the animation range
  49586. * @param to Ending frame of the animation
  49587. */
  49588. Animation.prototype.createRange = function (name, from, to) {
  49589. // check name not already in use; could happen for bones after serialized
  49590. if (!this._ranges[name]) {
  49591. this._ranges[name] = new AnimationRange(name, from, to);
  49592. }
  49593. };
  49594. /**
  49595. * Deletes an animation range by name
  49596. * @param name Name of the animation range to delete
  49597. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49598. */
  49599. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49600. if (deleteFrames === void 0) { deleteFrames = true; }
  49601. var range = this._ranges[name];
  49602. if (!range) {
  49603. return;
  49604. }
  49605. if (deleteFrames) {
  49606. var from = range.from;
  49607. var to = range.to;
  49608. // this loop MUST go high to low for multiple splices to work
  49609. for (var key = this._keys.length - 1; key >= 0; key--) {
  49610. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49611. this._keys.splice(key, 1);
  49612. }
  49613. }
  49614. }
  49615. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49616. };
  49617. /**
  49618. * Gets the animation range by name, or null if not defined
  49619. * @param name Name of the animation range
  49620. * @returns Nullable animation range
  49621. */
  49622. Animation.prototype.getRange = function (name) {
  49623. return this._ranges[name];
  49624. };
  49625. /**
  49626. * Gets the key frames from the animation
  49627. * @returns The key frames of the animation
  49628. */
  49629. Animation.prototype.getKeys = function () {
  49630. return this._keys;
  49631. };
  49632. /**
  49633. * Gets the highest frame rate of the animation
  49634. * @returns Highest frame rate of the animation
  49635. */
  49636. Animation.prototype.getHighestFrame = function () {
  49637. var ret = 0;
  49638. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49639. if (ret < this._keys[key].frame) {
  49640. ret = this._keys[key].frame;
  49641. }
  49642. }
  49643. return ret;
  49644. };
  49645. /**
  49646. * Gets the easing function of the animation
  49647. * @returns Easing function of the animation
  49648. */
  49649. Animation.prototype.getEasingFunction = function () {
  49650. return this._easingFunction;
  49651. };
  49652. /**
  49653. * Sets the easing function of the animation
  49654. * @param easingFunction A custom mathematical formula for animation
  49655. */
  49656. Animation.prototype.setEasingFunction = function (easingFunction) {
  49657. this._easingFunction = easingFunction;
  49658. };
  49659. /**
  49660. * Interpolates a scalar linearly
  49661. * @param startValue Start value of the animation curve
  49662. * @param endValue End value of the animation curve
  49663. * @param gradient Scalar amount to interpolate
  49664. * @returns Interpolated scalar value
  49665. */
  49666. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49667. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49668. };
  49669. /**
  49670. * Interpolates a scalar cubically
  49671. * @param startValue Start value of the animation curve
  49672. * @param outTangent End tangent of the animation
  49673. * @param endValue End value of the animation curve
  49674. * @param inTangent Start tangent of the animation curve
  49675. * @param gradient Scalar amount to interpolate
  49676. * @returns Interpolated scalar value
  49677. */
  49678. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49679. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49680. };
  49681. /**
  49682. * Interpolates a quaternion using a spherical linear interpolation
  49683. * @param startValue Start value of the animation curve
  49684. * @param endValue End value of the animation curve
  49685. * @param gradient Scalar amount to interpolate
  49686. * @returns Interpolated quaternion value
  49687. */
  49688. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49689. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49690. };
  49691. /**
  49692. * Interpolates a quaternion cubically
  49693. * @param startValue Start value of the animation curve
  49694. * @param outTangent End tangent of the animation curve
  49695. * @param endValue End value of the animation curve
  49696. * @param inTangent Start tangent of the animation curve
  49697. * @param gradient Scalar amount to interpolate
  49698. * @returns Interpolated quaternion value
  49699. */
  49700. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49701. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49702. };
  49703. /**
  49704. * Interpolates a Vector3 linearl
  49705. * @param startValue Start value of the animation curve
  49706. * @param endValue End value of the animation curve
  49707. * @param gradient Scalar amount to interpolate
  49708. * @returns Interpolated scalar value
  49709. */
  49710. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49711. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49712. };
  49713. /**
  49714. * Interpolates a Vector3 cubically
  49715. * @param startValue Start value of the animation curve
  49716. * @param outTangent End tangent of the animation
  49717. * @param endValue End value of the animation curve
  49718. * @param inTangent Start tangent of the animation curve
  49719. * @param gradient Scalar amount to interpolate
  49720. * @returns InterpolatedVector3 value
  49721. */
  49722. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49723. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49724. };
  49725. /**
  49726. * Interpolates a Vector2 linearly
  49727. * @param startValue Start value of the animation curve
  49728. * @param endValue End value of the animation curve
  49729. * @param gradient Scalar amount to interpolate
  49730. * @returns Interpolated Vector2 value
  49731. */
  49732. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49733. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49734. };
  49735. /**
  49736. * Interpolates a Vector2 cubically
  49737. * @param startValue Start value of the animation curve
  49738. * @param outTangent End tangent of the animation
  49739. * @param endValue End value of the animation curve
  49740. * @param inTangent Start tangent of the animation curve
  49741. * @param gradient Scalar amount to interpolate
  49742. * @returns Interpolated Vector2 value
  49743. */
  49744. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49745. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49746. };
  49747. /**
  49748. * Interpolates a size linearly
  49749. * @param startValue Start value of the animation curve
  49750. * @param endValue End value of the animation curve
  49751. * @param gradient Scalar amount to interpolate
  49752. * @returns Interpolated Size value
  49753. */
  49754. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49755. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49756. };
  49757. /**
  49758. * Interpolates a Color3 linearly
  49759. * @param startValue Start value of the animation curve
  49760. * @param endValue End value of the animation curve
  49761. * @param gradient Scalar amount to interpolate
  49762. * @returns Interpolated Color3 value
  49763. */
  49764. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49765. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49766. };
  49767. /**
  49768. * @hidden Internal use only
  49769. */
  49770. Animation.prototype._getKeyValue = function (value) {
  49771. if (typeof value === "function") {
  49772. return value();
  49773. }
  49774. return value;
  49775. };
  49776. /**
  49777. * @hidden Internal use only
  49778. */
  49779. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49780. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49781. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49782. }
  49783. var keys = this.getKeys();
  49784. // Try to get a hash to find the right key
  49785. 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));
  49786. if (keys[startKeyIndex].frame >= currentFrame) {
  49787. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49788. startKeyIndex--;
  49789. }
  49790. }
  49791. for (var key = startKeyIndex; key < keys.length; key++) {
  49792. var endKey = keys[key + 1];
  49793. if (endKey.frame >= currentFrame) {
  49794. var startKey = keys[key];
  49795. var startValue = this._getKeyValue(startKey.value);
  49796. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49797. return startValue;
  49798. }
  49799. var endValue = this._getKeyValue(endKey.value);
  49800. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49801. var frameDelta = endKey.frame - startKey.frame;
  49802. // gradient : percent of currentFrame between the frame inf and the frame sup
  49803. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49804. // check for easingFunction and correction of gradient
  49805. var easingFunction = this.getEasingFunction();
  49806. if (easingFunction != null) {
  49807. gradient = easingFunction.ease(gradient);
  49808. }
  49809. switch (this.dataType) {
  49810. // Float
  49811. case Animation.ANIMATIONTYPE_FLOAT:
  49812. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49813. switch (loopMode) {
  49814. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49815. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49816. return floatValue;
  49817. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49818. return offsetValue * repeatCount + floatValue;
  49819. }
  49820. break;
  49821. // Quaternion
  49822. case Animation.ANIMATIONTYPE_QUATERNION:
  49823. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49824. switch (loopMode) {
  49825. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49826. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49827. return quatValue;
  49828. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49829. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49830. }
  49831. return quatValue;
  49832. // Vector3
  49833. case Animation.ANIMATIONTYPE_VECTOR3:
  49834. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49835. switch (loopMode) {
  49836. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49837. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49838. return vec3Value;
  49839. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49840. return vec3Value.add(offsetValue.scale(repeatCount));
  49841. }
  49842. // Vector2
  49843. case Animation.ANIMATIONTYPE_VECTOR2:
  49844. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49845. switch (loopMode) {
  49846. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49847. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49848. return vec2Value;
  49849. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49850. return vec2Value.add(offsetValue.scale(repeatCount));
  49851. }
  49852. // Size
  49853. case Animation.ANIMATIONTYPE_SIZE:
  49854. switch (loopMode) {
  49855. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49856. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49857. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49858. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49859. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49860. }
  49861. // Color3
  49862. case Animation.ANIMATIONTYPE_COLOR3:
  49863. switch (loopMode) {
  49864. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49865. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49866. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49867. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49868. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49869. }
  49870. // Matrix
  49871. case Animation.ANIMATIONTYPE_MATRIX:
  49872. switch (loopMode) {
  49873. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49874. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49875. if (Animation.AllowMatricesInterpolation) {
  49876. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49877. }
  49878. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49879. return startValue;
  49880. }
  49881. default:
  49882. break;
  49883. }
  49884. break;
  49885. }
  49886. }
  49887. return this._getKeyValue(keys[keys.length - 1].value);
  49888. };
  49889. /**
  49890. * Defines the function to use to interpolate matrices
  49891. * @param startValue defines the start matrix
  49892. * @param endValue defines the end matrix
  49893. * @param gradient defines the gradient between both matrices
  49894. * @param result defines an optional target matrix where to store the interpolation
  49895. * @returns the interpolated matrix
  49896. */
  49897. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49898. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49899. if (result) {
  49900. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49901. return result;
  49902. }
  49903. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49904. }
  49905. if (result) {
  49906. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49907. return result;
  49908. }
  49909. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49910. };
  49911. /**
  49912. * Makes a copy of the animation
  49913. * @returns Cloned animation
  49914. */
  49915. Animation.prototype.clone = function () {
  49916. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49917. clone.enableBlending = this.enableBlending;
  49918. clone.blendingSpeed = this.blendingSpeed;
  49919. if (this._keys) {
  49920. clone.setKeys(this._keys);
  49921. }
  49922. if (this._ranges) {
  49923. clone._ranges = {};
  49924. for (var name in this._ranges) {
  49925. var range = this._ranges[name];
  49926. if (!range) {
  49927. continue;
  49928. }
  49929. clone._ranges[name] = range.clone();
  49930. }
  49931. }
  49932. return clone;
  49933. };
  49934. /**
  49935. * Sets the key frames of the animation
  49936. * @param values The animation key frames to set
  49937. */
  49938. Animation.prototype.setKeys = function (values) {
  49939. this._keys = values.slice(0);
  49940. };
  49941. /**
  49942. * Serializes the animation to an object
  49943. * @returns Serialized object
  49944. */
  49945. Animation.prototype.serialize = function () {
  49946. var serializationObject = {};
  49947. serializationObject.name = this.name;
  49948. serializationObject.property = this.targetProperty;
  49949. serializationObject.framePerSecond = this.framePerSecond;
  49950. serializationObject.dataType = this.dataType;
  49951. serializationObject.loopBehavior = this.loopMode;
  49952. serializationObject.enableBlending = this.enableBlending;
  49953. serializationObject.blendingSpeed = this.blendingSpeed;
  49954. var dataType = this.dataType;
  49955. serializationObject.keys = [];
  49956. var keys = this.getKeys();
  49957. for (var index = 0; index < keys.length; index++) {
  49958. var animationKey = keys[index];
  49959. var key = {};
  49960. key.frame = animationKey.frame;
  49961. switch (dataType) {
  49962. case Animation.ANIMATIONTYPE_FLOAT:
  49963. key.values = [animationKey.value];
  49964. break;
  49965. case Animation.ANIMATIONTYPE_QUATERNION:
  49966. case Animation.ANIMATIONTYPE_MATRIX:
  49967. case Animation.ANIMATIONTYPE_VECTOR3:
  49968. case Animation.ANIMATIONTYPE_COLOR3:
  49969. key.values = animationKey.value.asArray();
  49970. break;
  49971. }
  49972. serializationObject.keys.push(key);
  49973. }
  49974. serializationObject.ranges = [];
  49975. for (var name in this._ranges) {
  49976. var source = this._ranges[name];
  49977. if (!source) {
  49978. continue;
  49979. }
  49980. var range = {};
  49981. range.name = name;
  49982. range.from = source.from;
  49983. range.to = source.to;
  49984. serializationObject.ranges.push(range);
  49985. }
  49986. return serializationObject;
  49987. };
  49988. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49989. /**
  49990. * Get the float animation type
  49991. */
  49992. get: function () {
  49993. return Animation._ANIMATIONTYPE_FLOAT;
  49994. },
  49995. enumerable: true,
  49996. configurable: true
  49997. });
  49998. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49999. /**
  50000. * Get the Vector3 animation type
  50001. */
  50002. get: function () {
  50003. return Animation._ANIMATIONTYPE_VECTOR3;
  50004. },
  50005. enumerable: true,
  50006. configurable: true
  50007. });
  50008. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50009. /**
  50010. * Get the Vectpr2 animation type
  50011. */
  50012. get: function () {
  50013. return Animation._ANIMATIONTYPE_VECTOR2;
  50014. },
  50015. enumerable: true,
  50016. configurable: true
  50017. });
  50018. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50019. /**
  50020. * Get the Size animation type
  50021. */
  50022. get: function () {
  50023. return Animation._ANIMATIONTYPE_SIZE;
  50024. },
  50025. enumerable: true,
  50026. configurable: true
  50027. });
  50028. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50029. /**
  50030. * Get the Quaternion animation type
  50031. */
  50032. get: function () {
  50033. return Animation._ANIMATIONTYPE_QUATERNION;
  50034. },
  50035. enumerable: true,
  50036. configurable: true
  50037. });
  50038. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50039. /**
  50040. * Get the Matrix animation type
  50041. */
  50042. get: function () {
  50043. return Animation._ANIMATIONTYPE_MATRIX;
  50044. },
  50045. enumerable: true,
  50046. configurable: true
  50047. });
  50048. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50049. /**
  50050. * Get the Color3 animation type
  50051. */
  50052. get: function () {
  50053. return Animation._ANIMATIONTYPE_COLOR3;
  50054. },
  50055. enumerable: true,
  50056. configurable: true
  50057. });
  50058. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50059. /**
  50060. * Get the Relative Loop Mode
  50061. */
  50062. get: function () {
  50063. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50064. },
  50065. enumerable: true,
  50066. configurable: true
  50067. });
  50068. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50069. /**
  50070. * Get the Cycle Loop Mode
  50071. */
  50072. get: function () {
  50073. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50074. },
  50075. enumerable: true,
  50076. configurable: true
  50077. });
  50078. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50079. /**
  50080. * Get the Constant Loop Mode
  50081. */
  50082. get: function () {
  50083. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50084. },
  50085. enumerable: true,
  50086. configurable: true
  50087. });
  50088. /** @hidden */
  50089. Animation._UniversalLerp = function (left, right, amount) {
  50090. var constructor = left.constructor;
  50091. if (constructor.Lerp) { // Lerp supported
  50092. return constructor.Lerp(left, right, amount);
  50093. }
  50094. else if (constructor.Slerp) { // Slerp supported
  50095. return constructor.Slerp(left, right, amount);
  50096. }
  50097. else if (left.toFixed) { // Number
  50098. return left * (1.0 - amount) + amount * right;
  50099. }
  50100. else { // Blending not supported
  50101. return right;
  50102. }
  50103. };
  50104. /**
  50105. * Parses an animation object and creates an animation
  50106. * @param parsedAnimation Parsed animation object
  50107. * @returns Animation object
  50108. */
  50109. Animation.Parse = function (parsedAnimation) {
  50110. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50111. var dataType = parsedAnimation.dataType;
  50112. var keys = [];
  50113. var data;
  50114. var index;
  50115. if (parsedAnimation.enableBlending) {
  50116. animation.enableBlending = parsedAnimation.enableBlending;
  50117. }
  50118. if (parsedAnimation.blendingSpeed) {
  50119. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50120. }
  50121. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50122. var key = parsedAnimation.keys[index];
  50123. var inTangent;
  50124. var outTangent;
  50125. switch (dataType) {
  50126. case Animation.ANIMATIONTYPE_FLOAT:
  50127. data = key.values[0];
  50128. if (key.values.length >= 1) {
  50129. inTangent = key.values[1];
  50130. }
  50131. if (key.values.length >= 2) {
  50132. outTangent = key.values[2];
  50133. }
  50134. break;
  50135. case Animation.ANIMATIONTYPE_QUATERNION:
  50136. data = BABYLON.Quaternion.FromArray(key.values);
  50137. if (key.values.length >= 8) {
  50138. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50139. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50140. inTangent = _inTangent;
  50141. }
  50142. }
  50143. if (key.values.length >= 12) {
  50144. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50145. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50146. outTangent = _outTangent;
  50147. }
  50148. }
  50149. break;
  50150. case Animation.ANIMATIONTYPE_MATRIX:
  50151. data = BABYLON.Matrix.FromArray(key.values);
  50152. break;
  50153. case Animation.ANIMATIONTYPE_COLOR3:
  50154. data = BABYLON.Color3.FromArray(key.values);
  50155. break;
  50156. case Animation.ANIMATIONTYPE_VECTOR3:
  50157. default:
  50158. data = BABYLON.Vector3.FromArray(key.values);
  50159. break;
  50160. }
  50161. var keyData = {};
  50162. keyData.frame = key.frame;
  50163. keyData.value = data;
  50164. if (inTangent != undefined) {
  50165. keyData.inTangent = inTangent;
  50166. }
  50167. if (outTangent != undefined) {
  50168. keyData.outTangent = outTangent;
  50169. }
  50170. keys.push(keyData);
  50171. }
  50172. animation.setKeys(keys);
  50173. if (parsedAnimation.ranges) {
  50174. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50175. data = parsedAnimation.ranges[index];
  50176. animation.createRange(data.name, data.from, data.to);
  50177. }
  50178. }
  50179. return animation;
  50180. };
  50181. /**
  50182. * Appends the serialized animations from the source animations
  50183. * @param source Source containing the animations
  50184. * @param destination Target to store the animations
  50185. */
  50186. Animation.AppendSerializedAnimations = function (source, destination) {
  50187. if (source.animations) {
  50188. destination.animations = [];
  50189. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50190. var animation = source.animations[animationIndex];
  50191. destination.animations.push(animation.serialize());
  50192. }
  50193. }
  50194. };
  50195. /**
  50196. * Use matrix interpolation instead of using direct key value when animating matrices
  50197. */
  50198. Animation.AllowMatricesInterpolation = false;
  50199. /**
  50200. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50201. */
  50202. Animation.AllowMatrixDecomposeForInterpolation = true;
  50203. // Statics
  50204. /**
  50205. * Float animation type
  50206. */
  50207. Animation._ANIMATIONTYPE_FLOAT = 0;
  50208. /**
  50209. * Vector3 animation type
  50210. */
  50211. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50212. /**
  50213. * Quaternion animation type
  50214. */
  50215. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50216. /**
  50217. * Matrix animation type
  50218. */
  50219. Animation._ANIMATIONTYPE_MATRIX = 3;
  50220. /**
  50221. * Color3 animation type
  50222. */
  50223. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50224. /**
  50225. * Vector2 animation type
  50226. */
  50227. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50228. /**
  50229. * Size animation type
  50230. */
  50231. Animation._ANIMATIONTYPE_SIZE = 6;
  50232. /**
  50233. * Relative Loop Mode
  50234. */
  50235. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50236. /**
  50237. * Cycle Loop Mode
  50238. */
  50239. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50240. /**
  50241. * Constant Loop Mode
  50242. */
  50243. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50244. return Animation;
  50245. }());
  50246. BABYLON.Animation = Animation;
  50247. })(BABYLON || (BABYLON = {}));
  50248. //# sourceMappingURL=babylon.animation.js.map
  50249. var BABYLON;
  50250. (function (BABYLON) {
  50251. /**
  50252. * This class defines the direct association between an animation and a target
  50253. */
  50254. var TargetedAnimation = /** @class */ (function () {
  50255. function TargetedAnimation() {
  50256. }
  50257. return TargetedAnimation;
  50258. }());
  50259. BABYLON.TargetedAnimation = TargetedAnimation;
  50260. /**
  50261. * Use this class to create coordinated animations on multiple targets
  50262. */
  50263. var AnimationGroup = /** @class */ (function () {
  50264. function AnimationGroup(name, scene) {
  50265. if (scene === void 0) { scene = null; }
  50266. this.name = name;
  50267. this._targetedAnimations = new Array();
  50268. this._animatables = new Array();
  50269. this._from = Number.MAX_VALUE;
  50270. this._to = -Number.MAX_VALUE;
  50271. this._speedRatio = 1;
  50272. this.onAnimationEndObservable = new BABYLON.Observable();
  50273. /**
  50274. * This observable will notify when all animations have ended.
  50275. */
  50276. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50277. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50278. this._scene.animationGroups.push(this);
  50279. }
  50280. Object.defineProperty(AnimationGroup.prototype, "from", {
  50281. /**
  50282. * Gets the first frame
  50283. */
  50284. get: function () {
  50285. return this._from;
  50286. },
  50287. enumerable: true,
  50288. configurable: true
  50289. });
  50290. Object.defineProperty(AnimationGroup.prototype, "to", {
  50291. /**
  50292. * Gets the last frame
  50293. */
  50294. get: function () {
  50295. return this._to;
  50296. },
  50297. enumerable: true,
  50298. configurable: true
  50299. });
  50300. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50301. /**
  50302. * Define if the animations are started
  50303. */
  50304. get: function () {
  50305. return this._isStarted;
  50306. },
  50307. enumerable: true,
  50308. configurable: true
  50309. });
  50310. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50311. /**
  50312. * Gets or sets the speed ratio to use for all animations
  50313. */
  50314. get: function () {
  50315. return this._speedRatio;
  50316. },
  50317. /**
  50318. * Gets or sets the speed ratio to use for all animations
  50319. */
  50320. set: function (value) {
  50321. if (this._speedRatio === value) {
  50322. return;
  50323. }
  50324. this._speedRatio = value;
  50325. for (var index = 0; index < this._animatables.length; index++) {
  50326. var animatable = this._animatables[index];
  50327. animatable.speedRatio = this._speedRatio;
  50328. }
  50329. },
  50330. enumerable: true,
  50331. configurable: true
  50332. });
  50333. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50334. /**
  50335. * Gets the targeted animations for this animation group
  50336. */
  50337. get: function () {
  50338. return this._targetedAnimations;
  50339. },
  50340. enumerable: true,
  50341. configurable: true
  50342. });
  50343. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50344. /**
  50345. * returning the list of animatables controlled by this animation group.
  50346. */
  50347. get: function () {
  50348. return this._animatables;
  50349. },
  50350. enumerable: true,
  50351. configurable: true
  50352. });
  50353. /**
  50354. * Add an animation (with its target) in the group
  50355. * @param animation defines the animation we want to add
  50356. * @param target defines the target of the animation
  50357. * @returns the {BABYLON.TargetedAnimation} object
  50358. */
  50359. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50360. var targetedAnimation = {
  50361. animation: animation,
  50362. target: target
  50363. };
  50364. var keys = animation.getKeys();
  50365. if (this._from > keys[0].frame) {
  50366. this._from = keys[0].frame;
  50367. }
  50368. if (this._to < keys[keys.length - 1].frame) {
  50369. this._to = keys[keys.length - 1].frame;
  50370. }
  50371. this._targetedAnimations.push(targetedAnimation);
  50372. return targetedAnimation;
  50373. };
  50374. /**
  50375. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50376. * It can add constant keys at begin or end
  50377. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50378. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50379. */
  50380. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50381. if (beginFrame === void 0) { beginFrame = null; }
  50382. if (endFrame === void 0) { endFrame = null; }
  50383. if (beginFrame == null)
  50384. beginFrame = this._from;
  50385. if (endFrame == null)
  50386. endFrame = this._to;
  50387. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50388. var targetedAnimation = this._targetedAnimations[index];
  50389. var keys = targetedAnimation.animation.getKeys();
  50390. var startKey = keys[0];
  50391. var endKey = keys[keys.length - 1];
  50392. if (startKey.frame > beginFrame) {
  50393. var newKey = {
  50394. frame: beginFrame,
  50395. value: startKey.value,
  50396. inTangent: startKey.inTangent,
  50397. outTangent: startKey.outTangent,
  50398. interpolation: startKey.interpolation
  50399. };
  50400. keys.splice(0, 0, newKey);
  50401. }
  50402. if (endKey.frame < endFrame) {
  50403. var newKey = {
  50404. frame: endFrame,
  50405. value: endKey.value,
  50406. inTangent: endKey.outTangent,
  50407. outTangent: endKey.outTangent,
  50408. interpolation: endKey.interpolation
  50409. };
  50410. keys.push(newKey);
  50411. }
  50412. }
  50413. this._from = beginFrame;
  50414. this._to = endFrame;
  50415. return this;
  50416. };
  50417. /**
  50418. * Start all animations on given targets
  50419. * @param loop defines if animations must loop
  50420. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50421. * @param from defines the from key (optional)
  50422. * @param to defines the to key (optional)
  50423. * @returns the current animation group
  50424. */
  50425. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50426. var _this = this;
  50427. if (loop === void 0) { loop = false; }
  50428. if (speedRatio === void 0) { speedRatio = 1; }
  50429. if (this._isStarted || this._targetedAnimations.length === 0) {
  50430. return this;
  50431. }
  50432. var _loop_1 = function (targetedAnimation) {
  50433. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50434. animatable.onAnimationEnd = function () {
  50435. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50436. _this._checkAnimationGroupEnded(animatable);
  50437. };
  50438. this_1._animatables.push(animatable);
  50439. };
  50440. var this_1 = this;
  50441. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50442. var targetedAnimation = _a[_i];
  50443. _loop_1(targetedAnimation);
  50444. }
  50445. this._speedRatio = speedRatio;
  50446. this._isStarted = true;
  50447. return this;
  50448. };
  50449. /**
  50450. * Pause all animations
  50451. */
  50452. AnimationGroup.prototype.pause = function () {
  50453. if (!this._isStarted) {
  50454. return this;
  50455. }
  50456. for (var index = 0; index < this._animatables.length; index++) {
  50457. var animatable = this._animatables[index];
  50458. animatable.pause();
  50459. }
  50460. return this;
  50461. };
  50462. /**
  50463. * Play all animations to initial state
  50464. * This function will start() the animations if they were not started or will restart() them if they were paused
  50465. * @param loop defines if animations must loop
  50466. */
  50467. AnimationGroup.prototype.play = function (loop) {
  50468. // only if all animatables are ready and exist
  50469. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50470. if (loop !== undefined) {
  50471. for (var index = 0; index < this._animatables.length; index++) {
  50472. var animatable = this._animatables[index];
  50473. animatable.loopAnimation = loop;
  50474. }
  50475. }
  50476. this.restart();
  50477. }
  50478. else {
  50479. this.stop();
  50480. this.start(loop, this._speedRatio);
  50481. }
  50482. return this;
  50483. };
  50484. /**
  50485. * Reset all animations to initial state
  50486. */
  50487. AnimationGroup.prototype.reset = function () {
  50488. if (!this._isStarted) {
  50489. return this;
  50490. }
  50491. for (var index = 0; index < this._animatables.length; index++) {
  50492. var animatable = this._animatables[index];
  50493. animatable.reset();
  50494. }
  50495. return this;
  50496. };
  50497. /**
  50498. * Restart animations from key 0
  50499. */
  50500. AnimationGroup.prototype.restart = function () {
  50501. if (!this._isStarted) {
  50502. return this;
  50503. }
  50504. for (var index = 0; index < this._animatables.length; index++) {
  50505. var animatable = this._animatables[index];
  50506. animatable.restart();
  50507. }
  50508. return this;
  50509. };
  50510. /**
  50511. * Stop all animations
  50512. */
  50513. AnimationGroup.prototype.stop = function () {
  50514. if (!this._isStarted) {
  50515. return this;
  50516. }
  50517. var list = this._animatables.slice();
  50518. for (var index = 0; index < list.length; index++) {
  50519. list[index].stop();
  50520. }
  50521. this._isStarted = false;
  50522. return this;
  50523. };
  50524. /**
  50525. * Set animation weight for all animatables
  50526. * @param weight defines the weight to use
  50527. * @return the animationGroup
  50528. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50529. */
  50530. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50531. for (var index = 0; index < this._animatables.length; index++) {
  50532. var animatable = this._animatables[index];
  50533. animatable.weight = weight;
  50534. }
  50535. return this;
  50536. };
  50537. /**
  50538. * Synchronize and normalize all animatables with a source animatable
  50539. * @param root defines the root animatable to synchronize with
  50540. * @return the animationGroup
  50541. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50542. */
  50543. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50544. for (var index = 0; index < this._animatables.length; index++) {
  50545. var animatable = this._animatables[index];
  50546. animatable.syncWith(root);
  50547. }
  50548. return this;
  50549. };
  50550. /**
  50551. * Goes to a specific frame in this animation group
  50552. * @param frame the frame number to go to
  50553. * @return the animationGroup
  50554. */
  50555. AnimationGroup.prototype.goToFrame = function (frame) {
  50556. if (!this._isStarted) {
  50557. return this;
  50558. }
  50559. for (var index = 0; index < this._animatables.length; index++) {
  50560. var animatable = this._animatables[index];
  50561. animatable.goToFrame(frame);
  50562. }
  50563. return this;
  50564. };
  50565. /**
  50566. * Dispose all associated resources
  50567. */
  50568. AnimationGroup.prototype.dispose = function () {
  50569. this._targetedAnimations = [];
  50570. this._animatables = [];
  50571. var index = this._scene.animationGroups.indexOf(this);
  50572. if (index > -1) {
  50573. this._scene.animationGroups.splice(index, 1);
  50574. }
  50575. };
  50576. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50577. // animatable should be taken out of the array
  50578. var idx = this._animatables.indexOf(animatable);
  50579. if (idx > -1) {
  50580. this._animatables.splice(idx, 1);
  50581. }
  50582. // all animatables were removed? animation group ended!
  50583. if (this._animatables.length === 0) {
  50584. this._isStarted = false;
  50585. this.onAnimationGroupEndObservable.notifyObservers(this);
  50586. }
  50587. };
  50588. return AnimationGroup;
  50589. }());
  50590. BABYLON.AnimationGroup = AnimationGroup;
  50591. })(BABYLON || (BABYLON = {}));
  50592. //# sourceMappingURL=babylon.animationGroup.js.map
  50593. var BABYLON;
  50594. (function (BABYLON) {
  50595. /**
  50596. * Defines a runtime animation
  50597. */
  50598. var RuntimeAnimation = /** @class */ (function () {
  50599. /**
  50600. * Create a new RuntimeAnimation object
  50601. * @param target defines the target of the animation
  50602. * @param animation defines the source animation object
  50603. * @param scene defines the hosting scene
  50604. * @param host defines the initiating Animatable
  50605. */
  50606. function RuntimeAnimation(target, animation, scene, host) {
  50607. var _this = this;
  50608. this._events = new Array();
  50609. /**
  50610. * The current frame of the runtime animation
  50611. */
  50612. this._currentFrame = 0;
  50613. /**
  50614. * The original value of the runtime animation
  50615. */
  50616. this._originalValue = new Array();
  50617. /**
  50618. * The offsets cache of the runtime animation
  50619. */
  50620. this._offsetsCache = {};
  50621. /**
  50622. * The high limits cache of the runtime animation
  50623. */
  50624. this._highLimitsCache = {};
  50625. /**
  50626. * Specifies if the runtime animation has been stopped
  50627. */
  50628. this._stopped = false;
  50629. /**
  50630. * The blending factor of the runtime animation
  50631. */
  50632. this._blendingFactor = 0;
  50633. /**
  50634. * The target path of the runtime animation
  50635. */
  50636. this._targetPath = "";
  50637. /**
  50638. * The weight of the runtime animation
  50639. */
  50640. this._weight = 1.0;
  50641. /**
  50642. * The ratio offset of the runtime animation
  50643. */
  50644. this._ratioOffset = 0;
  50645. /**
  50646. * The previous delay of the runtime animation
  50647. */
  50648. this._previousDelay = 0;
  50649. /**
  50650. * The previous ratio of the runtime animation
  50651. */
  50652. this._previousRatio = 0;
  50653. this._animation = animation;
  50654. this._target = target;
  50655. this._scene = scene;
  50656. this._host = host;
  50657. animation._runtimeAnimations.push(this);
  50658. // Cloning events locally
  50659. var events = animation.getEvents();
  50660. if (events && events.length > 0) {
  50661. events.forEach(function (e) {
  50662. _this._events.push(e._clone());
  50663. });
  50664. }
  50665. }
  50666. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50667. /**
  50668. * Gets the current frame of the runtime animation
  50669. */
  50670. get: function () {
  50671. return this._currentFrame;
  50672. },
  50673. enumerable: true,
  50674. configurable: true
  50675. });
  50676. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50677. /**
  50678. * Gets the weight of the runtime animation
  50679. */
  50680. get: function () {
  50681. return this._weight;
  50682. },
  50683. enumerable: true,
  50684. configurable: true
  50685. });
  50686. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50687. /**
  50688. * Gets the current value of the runtime animation
  50689. */
  50690. get: function () {
  50691. return this._currentValue;
  50692. },
  50693. enumerable: true,
  50694. configurable: true
  50695. });
  50696. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50697. /**
  50698. * Gets the target path of the runtime animation
  50699. */
  50700. get: function () {
  50701. return this._targetPath;
  50702. },
  50703. enumerable: true,
  50704. configurable: true
  50705. });
  50706. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50707. /**
  50708. * Gets the actual target of the runtime animation
  50709. */
  50710. get: function () {
  50711. return this._activeTarget;
  50712. },
  50713. enumerable: true,
  50714. configurable: true
  50715. });
  50716. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50717. /**
  50718. * Gets the animation from the runtime animation
  50719. */
  50720. get: function () {
  50721. return this._animation;
  50722. },
  50723. enumerable: true,
  50724. configurable: true
  50725. });
  50726. /**
  50727. * Resets the runtime animation to the beginning
  50728. * @param restoreOriginal defines whether to restore the target property to the original value
  50729. */
  50730. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50731. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50732. if (restoreOriginal) {
  50733. if (this._target instanceof Array) {
  50734. var index = 0;
  50735. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50736. var target = _a[_i];
  50737. if (this._originalValue[index] !== undefined) {
  50738. this._setValue(target, this._originalValue[index], -1);
  50739. }
  50740. index++;
  50741. }
  50742. }
  50743. else {
  50744. if (this._originalValue[0] !== undefined) {
  50745. this._setValue(this._target, this._originalValue[0], -1);
  50746. }
  50747. }
  50748. }
  50749. this._offsetsCache = {};
  50750. this._highLimitsCache = {};
  50751. this._currentFrame = 0;
  50752. this._blendingFactor = 0;
  50753. this._originalValue = new Array();
  50754. // Events
  50755. for (var index = 0; index < this._events.length; index++) {
  50756. this._events[index].isDone = false;
  50757. }
  50758. };
  50759. /**
  50760. * Specifies if the runtime animation is stopped
  50761. * @returns Boolean specifying if the runtime animation is stopped
  50762. */
  50763. RuntimeAnimation.prototype.isStopped = function () {
  50764. return this._stopped;
  50765. };
  50766. /**
  50767. * Disposes of the runtime animation
  50768. */
  50769. RuntimeAnimation.prototype.dispose = function () {
  50770. var index = this._animation.runtimeAnimations.indexOf(this);
  50771. if (index > -1) {
  50772. this._animation.runtimeAnimations.splice(index, 1);
  50773. }
  50774. };
  50775. /**
  50776. * Interpolates the animation from the current frame
  50777. * @param currentFrame The frame to interpolate the animation to
  50778. * @param repeatCount The number of times that the animation should loop
  50779. * @param loopMode The type of looping mode to use
  50780. * @param offsetValue Animation offset value
  50781. * @param highLimitValue The high limit value
  50782. * @returns The interpolated value
  50783. */
  50784. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50785. this._currentFrame = currentFrame;
  50786. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50787. this._workValue = BABYLON.Matrix.Zero();
  50788. }
  50789. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50790. };
  50791. /**
  50792. * Apply the interpolated value to the target
  50793. * @param currentValue defines the value computed by the animation
  50794. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50795. */
  50796. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50797. if (weight === void 0) { weight = 1.0; }
  50798. if (this._target instanceof Array) {
  50799. var index = 0;
  50800. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50801. var target = _a[_i];
  50802. this._setValue(target, currentValue, weight, index);
  50803. index++;
  50804. }
  50805. }
  50806. else {
  50807. this._setValue(this._target, currentValue, weight);
  50808. }
  50809. };
  50810. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50811. if (targetIndex === void 0) { targetIndex = 0; }
  50812. // Set value
  50813. var path;
  50814. var destination;
  50815. var targetPropertyPath = this._animation.targetPropertyPath;
  50816. if (targetPropertyPath.length > 1) {
  50817. var property = target[targetPropertyPath[0]];
  50818. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50819. property = property[targetPropertyPath[index]];
  50820. }
  50821. path = targetPropertyPath[targetPropertyPath.length - 1];
  50822. destination = property;
  50823. }
  50824. else {
  50825. path = targetPropertyPath[0];
  50826. destination = target;
  50827. }
  50828. this._targetPath = path;
  50829. this._activeTarget = destination;
  50830. this._weight = weight;
  50831. if (this._originalValue[targetIndex] === undefined) {
  50832. var originalValue = void 0;
  50833. if (destination.getRestPose && path === "_matrix") { // For bones
  50834. originalValue = destination.getRestPose();
  50835. }
  50836. else {
  50837. originalValue = destination[path];
  50838. }
  50839. if (originalValue && originalValue.clone) {
  50840. this._originalValue[targetIndex] = originalValue.clone();
  50841. }
  50842. else {
  50843. this._originalValue[targetIndex] = originalValue;
  50844. }
  50845. }
  50846. // Blending
  50847. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50848. if (enableBlending && this._blendingFactor <= 1.0) {
  50849. if (!this._originalBlendValue) {
  50850. var originalValue = destination[path];
  50851. if (originalValue.clone) {
  50852. this._originalBlendValue = originalValue.clone();
  50853. }
  50854. else {
  50855. this._originalBlendValue = originalValue;
  50856. }
  50857. }
  50858. if (this._originalBlendValue.m) { // Matrix
  50859. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50860. if (this._currentValue) {
  50861. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50862. }
  50863. else {
  50864. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50865. }
  50866. }
  50867. else {
  50868. if (this._currentValue) {
  50869. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50870. }
  50871. else {
  50872. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50873. }
  50874. }
  50875. }
  50876. else {
  50877. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50878. }
  50879. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50880. this._blendingFactor += blendingSpeed;
  50881. }
  50882. else {
  50883. this._currentValue = currentValue;
  50884. }
  50885. if (weight !== -1.0) {
  50886. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50887. }
  50888. else {
  50889. destination[path] = this._currentValue;
  50890. }
  50891. if (target.markAsDirty) {
  50892. target.markAsDirty(this._animation.targetProperty);
  50893. }
  50894. };
  50895. /**
  50896. * Gets the loop pmode of the runtime animation
  50897. * @returns Loop Mode
  50898. */
  50899. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50900. if (this._target && this._target.animationPropertiesOverride) {
  50901. return this._target.animationPropertiesOverride.loopMode;
  50902. }
  50903. return this._animation.loopMode;
  50904. };
  50905. /**
  50906. * Move the current animation to a given frame
  50907. * @param frame defines the frame to move to
  50908. */
  50909. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50910. var keys = this._animation.getKeys();
  50911. if (frame < keys[0].frame) {
  50912. frame = keys[0].frame;
  50913. }
  50914. else if (frame > keys[keys.length - 1].frame) {
  50915. frame = keys[keys.length - 1].frame;
  50916. }
  50917. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50918. this.setValue(currentValue, -1);
  50919. };
  50920. /**
  50921. * @hidden Internal use only
  50922. */
  50923. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50924. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50925. this._ratioOffset = this._previousRatio - newRatio;
  50926. };
  50927. /**
  50928. * Execute the current animation
  50929. * @param delay defines the delay to add to the current frame
  50930. * @param from defines the lower bound of the animation range
  50931. * @param to defines the upper bound of the animation range
  50932. * @param loop defines if the current animation must loop
  50933. * @param speedRatio defines the current speed ratio
  50934. * @param weight defines the weight of the animation (default is -1 so no weight)
  50935. * @returns a boolean indicating if the animation has ended
  50936. */
  50937. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50938. if (weight === void 0) { weight = -1.0; }
  50939. var targetPropertyPath = this._animation.targetPropertyPath;
  50940. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50941. this._stopped = true;
  50942. return false;
  50943. }
  50944. var keys = this._animation.getKeys();
  50945. // Return immediately if there is only one key frame.
  50946. if (keys.length === 1) {
  50947. this.setValue(keys[0].value, weight);
  50948. return !loop;
  50949. }
  50950. var returnValue = true;
  50951. // Adding a start key at frame 0 if missing
  50952. if (keys[0].frame !== 0) {
  50953. var newKey = { frame: 0, value: keys[0].value };
  50954. keys.splice(0, 0, newKey);
  50955. }
  50956. // Check limits
  50957. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50958. from = keys[0].frame;
  50959. }
  50960. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50961. to = keys[keys.length - 1].frame;
  50962. }
  50963. //to and from cannot be the same key
  50964. if (from === to) {
  50965. if (from > keys[0].frame) {
  50966. from--;
  50967. }
  50968. else if (to < keys[keys.length - 1].frame) {
  50969. to++;
  50970. }
  50971. }
  50972. // Compute ratio
  50973. var range = to - from;
  50974. var offsetValue;
  50975. // ratio represents the frame delta between from and to
  50976. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50977. var highLimitValue = 0;
  50978. this._previousDelay = delay;
  50979. this._previousRatio = ratio;
  50980. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50981. returnValue = false;
  50982. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50983. }
  50984. else {
  50985. // Get max value if required
  50986. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50987. var keyOffset = to.toString() + from.toString();
  50988. if (!this._offsetsCache[keyOffset]) {
  50989. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50990. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50991. switch (this._animation.dataType) {
  50992. // Float
  50993. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50994. this._offsetsCache[keyOffset] = toValue - fromValue;
  50995. break;
  50996. // Quaternion
  50997. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50998. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50999. break;
  51000. // Vector3
  51001. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51002. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51003. // Vector2
  51004. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51005. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51006. // Size
  51007. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51008. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51009. // Color3
  51010. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51011. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51012. default:
  51013. break;
  51014. }
  51015. this._highLimitsCache[keyOffset] = toValue;
  51016. }
  51017. highLimitValue = this._highLimitsCache[keyOffset];
  51018. offsetValue = this._offsetsCache[keyOffset];
  51019. }
  51020. }
  51021. if (offsetValue === undefined) {
  51022. switch (this._animation.dataType) {
  51023. // Float
  51024. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51025. offsetValue = 0;
  51026. break;
  51027. // Quaternion
  51028. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51029. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51030. break;
  51031. // Vector3
  51032. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51033. offsetValue = BABYLON.Vector3.Zero();
  51034. break;
  51035. // Vector2
  51036. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51037. offsetValue = BABYLON.Vector2.Zero();
  51038. break;
  51039. // Size
  51040. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51041. offsetValue = BABYLON.Size.Zero();
  51042. break;
  51043. // Color3
  51044. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51045. offsetValue = BABYLON.Color3.Black();
  51046. }
  51047. }
  51048. // Compute value
  51049. var repeatCount = (ratio / range) >> 0;
  51050. var currentFrame = returnValue ? from + ratio % range : to;
  51051. // Need to normalize?
  51052. if (this._host && this._host.syncRoot) {
  51053. var syncRoot = this._host.syncRoot;
  51054. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51055. currentFrame = from + (to - from) * hostNormalizedFrame;
  51056. }
  51057. // Reset events if looping
  51058. var events = this._events;
  51059. if (range > 0 && this.currentFrame > currentFrame ||
  51060. range < 0 && this.currentFrame < currentFrame) {
  51061. // Need to reset animation events
  51062. for (var index = 0; index < events.length; index++) {
  51063. if (!events[index].onlyOnce) {
  51064. // reset event, the animation is looping
  51065. events[index].isDone = false;
  51066. }
  51067. }
  51068. }
  51069. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51070. // Set value
  51071. this.setValue(currentValue, weight);
  51072. // Check events
  51073. for (var index = 0; index < events.length; index++) {
  51074. // Make sure current frame has passed event frame and that event frame is within the current range
  51075. // Also, handle both forward and reverse animations
  51076. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51077. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51078. var event = events[index];
  51079. if (!event.isDone) {
  51080. // If event should be done only once, remove it.
  51081. if (event.onlyOnce) {
  51082. events.splice(index, 1);
  51083. index--;
  51084. }
  51085. event.isDone = true;
  51086. event.action();
  51087. } // Don't do anything if the event has already be done.
  51088. }
  51089. }
  51090. if (!returnValue) {
  51091. this._stopped = true;
  51092. }
  51093. return returnValue;
  51094. };
  51095. return RuntimeAnimation;
  51096. }());
  51097. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51098. })(BABYLON || (BABYLON = {}));
  51099. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51100. var BABYLON;
  51101. (function (BABYLON) {
  51102. /**
  51103. * Class used to store an actual running animation
  51104. */
  51105. var Animatable = /** @class */ (function () {
  51106. /**
  51107. * Creates a new Animatable
  51108. * @param scene defines the hosting scene
  51109. * @param target defines the target object
  51110. * @param fromFrame defines the starting frame number (default is 0)
  51111. * @param toFrame defines the ending frame number (default is 100)
  51112. * @param loopAnimation defines if the animation must loop (default is false)
  51113. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51114. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51115. * @param animations defines a group of animation to add to the new Animatable
  51116. */
  51117. function Animatable(scene,
  51118. /** defines the target object */
  51119. target,
  51120. /** defines the starting frame number (default is 0) */
  51121. fromFrame,
  51122. /** defines the ending frame number (default is 100) */
  51123. toFrame,
  51124. /** defines if the animation must loop (default is false) */
  51125. loopAnimation, speedRatio,
  51126. /** defines a callback to call when animation ends if it is not looping */
  51127. onAnimationEnd, animations) {
  51128. if (fromFrame === void 0) { fromFrame = 0; }
  51129. if (toFrame === void 0) { toFrame = 100; }
  51130. if (loopAnimation === void 0) { loopAnimation = false; }
  51131. if (speedRatio === void 0) { speedRatio = 1.0; }
  51132. this.target = target;
  51133. this.fromFrame = fromFrame;
  51134. this.toFrame = toFrame;
  51135. this.loopAnimation = loopAnimation;
  51136. this.onAnimationEnd = onAnimationEnd;
  51137. this._localDelayOffset = null;
  51138. this._pausedDelay = null;
  51139. this._runtimeAnimations = new Array();
  51140. this._paused = false;
  51141. this._speedRatio = 1;
  51142. this._weight = -1.0;
  51143. /**
  51144. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51145. * This will only apply for non looping animation (default is true)
  51146. */
  51147. this.disposeOnEnd = true;
  51148. /**
  51149. * Gets a boolean indicating if the animation has started
  51150. */
  51151. this.animationStarted = false;
  51152. /**
  51153. * Observer raised when the animation ends
  51154. */
  51155. this.onAnimationEndObservable = new BABYLON.Observable();
  51156. this._scene = scene;
  51157. if (animations) {
  51158. this.appendAnimations(target, animations);
  51159. }
  51160. this._speedRatio = speedRatio;
  51161. scene._activeAnimatables.push(this);
  51162. }
  51163. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51164. /**
  51165. * Gets the root Animatable used to synchronize and normalize animations
  51166. */
  51167. get: function () {
  51168. return this._syncRoot;
  51169. },
  51170. enumerable: true,
  51171. configurable: true
  51172. });
  51173. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51174. /**
  51175. * Gets the current frame of the first RuntimeAnimation
  51176. * Used to synchronize Animatables
  51177. */
  51178. get: function () {
  51179. if (this._runtimeAnimations.length === 0) {
  51180. return 0;
  51181. }
  51182. return this._runtimeAnimations[0].currentFrame;
  51183. },
  51184. enumerable: true,
  51185. configurable: true
  51186. });
  51187. Object.defineProperty(Animatable.prototype, "weight", {
  51188. /**
  51189. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51190. */
  51191. get: function () {
  51192. return this._weight;
  51193. },
  51194. set: function (value) {
  51195. if (value === -1) { // -1 is ok and means no weight
  51196. this._weight = -1;
  51197. return;
  51198. }
  51199. // Else weight must be in [0, 1] range
  51200. this._weight = Math.min(Math.max(value, 0), 1.0);
  51201. },
  51202. enumerable: true,
  51203. configurable: true
  51204. });
  51205. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51206. /**
  51207. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51208. */
  51209. get: function () {
  51210. return this._speedRatio;
  51211. },
  51212. set: function (value) {
  51213. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51214. var animation = this._runtimeAnimations[index];
  51215. animation._prepareForSpeedRatioChange(value);
  51216. }
  51217. this._speedRatio = value;
  51218. },
  51219. enumerable: true,
  51220. configurable: true
  51221. });
  51222. // Methods
  51223. /**
  51224. * Synchronize and normalize current Animatable with a source Animatable
  51225. * This is useful when using animation weights and when animations are not of the same length
  51226. * @param root defines the root Animatable to synchronize with
  51227. * @returns the current Animatable
  51228. */
  51229. Animatable.prototype.syncWith = function (root) {
  51230. this._syncRoot = root;
  51231. if (root) {
  51232. // Make sure this animatable will animate after the root
  51233. var index = this._scene._activeAnimatables.indexOf(this);
  51234. if (index > -1) {
  51235. this._scene._activeAnimatables.splice(index, 1);
  51236. this._scene._activeAnimatables.push(this);
  51237. }
  51238. }
  51239. return this;
  51240. };
  51241. /**
  51242. * Gets the list of runtime animations
  51243. * @returns an array of RuntimeAnimation
  51244. */
  51245. Animatable.prototype.getAnimations = function () {
  51246. return this._runtimeAnimations;
  51247. };
  51248. /**
  51249. * Adds more animations to the current animatable
  51250. * @param target defines the target of the animations
  51251. * @param animations defines the new animations to add
  51252. */
  51253. Animatable.prototype.appendAnimations = function (target, animations) {
  51254. for (var index = 0; index < animations.length; index++) {
  51255. var animation = animations[index];
  51256. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51257. }
  51258. };
  51259. /**
  51260. * Gets the source animation for a specific property
  51261. * @param property defines the propertyu to look for
  51262. * @returns null or the source animation for the given property
  51263. */
  51264. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51265. var runtimeAnimations = this._runtimeAnimations;
  51266. for (var index = 0; index < runtimeAnimations.length; index++) {
  51267. if (runtimeAnimations[index].animation.targetProperty === property) {
  51268. return runtimeAnimations[index].animation;
  51269. }
  51270. }
  51271. return null;
  51272. };
  51273. /**
  51274. * Gets the runtime animation for a specific property
  51275. * @param property defines the propertyu to look for
  51276. * @returns null or the runtime animation for the given property
  51277. */
  51278. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51279. var runtimeAnimations = this._runtimeAnimations;
  51280. for (var index = 0; index < runtimeAnimations.length; index++) {
  51281. if (runtimeAnimations[index].animation.targetProperty === property) {
  51282. return runtimeAnimations[index];
  51283. }
  51284. }
  51285. return null;
  51286. };
  51287. /**
  51288. * Resets the animatable to its original state
  51289. */
  51290. Animatable.prototype.reset = function () {
  51291. var runtimeAnimations = this._runtimeAnimations;
  51292. for (var index = 0; index < runtimeAnimations.length; index++) {
  51293. runtimeAnimations[index].reset(true);
  51294. }
  51295. this._localDelayOffset = null;
  51296. this._pausedDelay = null;
  51297. };
  51298. /**
  51299. * Allows the animatable to blend with current running animations
  51300. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51301. * @param blendingSpeed defines the blending speed to use
  51302. */
  51303. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51304. var runtimeAnimations = this._runtimeAnimations;
  51305. for (var index = 0; index < runtimeAnimations.length; index++) {
  51306. runtimeAnimations[index].animation.enableBlending = true;
  51307. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51308. }
  51309. };
  51310. /**
  51311. * Disable animation blending
  51312. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51313. */
  51314. Animatable.prototype.disableBlending = function () {
  51315. var runtimeAnimations = this._runtimeAnimations;
  51316. for (var index = 0; index < runtimeAnimations.length; index++) {
  51317. runtimeAnimations[index].animation.enableBlending = false;
  51318. }
  51319. };
  51320. /**
  51321. * Jump directly to a given frame
  51322. * @param frame defines the frame to jump to
  51323. */
  51324. Animatable.prototype.goToFrame = function (frame) {
  51325. var runtimeAnimations = this._runtimeAnimations;
  51326. if (runtimeAnimations[0]) {
  51327. var fps = runtimeAnimations[0].animation.framePerSecond;
  51328. var currentFrame = runtimeAnimations[0].currentFrame;
  51329. var adjustTime = frame - currentFrame;
  51330. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51331. if (this._localDelayOffset === null) {
  51332. this._localDelayOffset = 0;
  51333. }
  51334. this._localDelayOffset -= delay;
  51335. }
  51336. for (var index = 0; index < runtimeAnimations.length; index++) {
  51337. runtimeAnimations[index].goToFrame(frame);
  51338. }
  51339. };
  51340. /**
  51341. * Pause the animation
  51342. */
  51343. Animatable.prototype.pause = function () {
  51344. if (this._paused) {
  51345. return;
  51346. }
  51347. this._paused = true;
  51348. };
  51349. /**
  51350. * Restart the animation
  51351. */
  51352. Animatable.prototype.restart = function () {
  51353. this._paused = false;
  51354. };
  51355. Animatable.prototype._raiseOnAnimationEnd = function () {
  51356. if (this.onAnimationEnd) {
  51357. this.onAnimationEnd();
  51358. }
  51359. this.onAnimationEndObservable.notifyObservers(this);
  51360. };
  51361. /**
  51362. * Stop and delete the current animation
  51363. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51364. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51365. */
  51366. Animatable.prototype.stop = function (animationName, targetMask) {
  51367. if (animationName || targetMask) {
  51368. var idx = this._scene._activeAnimatables.indexOf(this);
  51369. if (idx > -1) {
  51370. var runtimeAnimations = this._runtimeAnimations;
  51371. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51372. var runtimeAnimation = runtimeAnimations[index];
  51373. if (animationName && runtimeAnimation.animation.name != animationName) {
  51374. continue;
  51375. }
  51376. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51377. continue;
  51378. }
  51379. runtimeAnimation.dispose();
  51380. runtimeAnimations.splice(index, 1);
  51381. }
  51382. if (runtimeAnimations.length == 0) {
  51383. this._scene._activeAnimatables.splice(idx, 1);
  51384. this._raiseOnAnimationEnd();
  51385. }
  51386. }
  51387. }
  51388. else {
  51389. var index = this._scene._activeAnimatables.indexOf(this);
  51390. if (index > -1) {
  51391. this._scene._activeAnimatables.splice(index, 1);
  51392. var runtimeAnimations = this._runtimeAnimations;
  51393. for (var index = 0; index < runtimeAnimations.length; index++) {
  51394. runtimeAnimations[index].dispose();
  51395. }
  51396. this._raiseOnAnimationEnd();
  51397. }
  51398. }
  51399. };
  51400. /**
  51401. * Wait asynchronously for the animation to end
  51402. * @returns a promise which will be fullfilled when the animation ends
  51403. */
  51404. Animatable.prototype.waitAsync = function () {
  51405. var _this = this;
  51406. return new Promise(function (resolve, reject) {
  51407. _this.onAnimationEndObservable.add(function () {
  51408. resolve(_this);
  51409. }, undefined, undefined, _this, true);
  51410. });
  51411. };
  51412. /** @hidden */
  51413. Animatable.prototype._animate = function (delay) {
  51414. if (this._paused) {
  51415. this.animationStarted = false;
  51416. if (this._pausedDelay === null) {
  51417. this._pausedDelay = delay;
  51418. }
  51419. return true;
  51420. }
  51421. if (this._localDelayOffset === null) {
  51422. this._localDelayOffset = delay;
  51423. this._pausedDelay = null;
  51424. }
  51425. else if (this._pausedDelay !== null) {
  51426. this._localDelayOffset += delay - this._pausedDelay;
  51427. this._pausedDelay = null;
  51428. }
  51429. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51430. return true;
  51431. }
  51432. // Animating
  51433. var running = false;
  51434. var runtimeAnimations = this._runtimeAnimations;
  51435. var index;
  51436. for (index = 0; index < runtimeAnimations.length; index++) {
  51437. var animation = runtimeAnimations[index];
  51438. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51439. running = running || isRunning;
  51440. }
  51441. this.animationStarted = running;
  51442. if (!running) {
  51443. if (this.disposeOnEnd) {
  51444. // Remove from active animatables
  51445. index = this._scene._activeAnimatables.indexOf(this);
  51446. this._scene._activeAnimatables.splice(index, 1);
  51447. // Dispose all runtime animations
  51448. for (index = 0; index < runtimeAnimations.length; index++) {
  51449. runtimeAnimations[index].dispose();
  51450. }
  51451. }
  51452. this._raiseOnAnimationEnd();
  51453. if (this.disposeOnEnd) {
  51454. this.onAnimationEnd = null;
  51455. this.onAnimationEndObservable.clear();
  51456. }
  51457. }
  51458. return running;
  51459. };
  51460. return Animatable;
  51461. }());
  51462. BABYLON.Animatable = Animatable;
  51463. })(BABYLON || (BABYLON = {}));
  51464. //# sourceMappingURL=babylon.animatable.js.map
  51465. var BABYLON;
  51466. (function (BABYLON) {
  51467. var EasingFunction = /** @class */ (function () {
  51468. function EasingFunction() {
  51469. // Properties
  51470. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51471. }
  51472. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51473. get: function () {
  51474. return EasingFunction._EASINGMODE_EASEIN;
  51475. },
  51476. enumerable: true,
  51477. configurable: true
  51478. });
  51479. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51480. get: function () {
  51481. return EasingFunction._EASINGMODE_EASEOUT;
  51482. },
  51483. enumerable: true,
  51484. configurable: true
  51485. });
  51486. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51487. get: function () {
  51488. return EasingFunction._EASINGMODE_EASEINOUT;
  51489. },
  51490. enumerable: true,
  51491. configurable: true
  51492. });
  51493. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51494. var n = Math.min(Math.max(easingMode, 0), 2);
  51495. this._easingMode = n;
  51496. };
  51497. EasingFunction.prototype.getEasingMode = function () {
  51498. return this._easingMode;
  51499. };
  51500. EasingFunction.prototype.easeInCore = function (gradient) {
  51501. throw new Error('You must implement this method');
  51502. };
  51503. EasingFunction.prototype.ease = function (gradient) {
  51504. switch (this._easingMode) {
  51505. case EasingFunction.EASINGMODE_EASEIN:
  51506. return this.easeInCore(gradient);
  51507. case EasingFunction.EASINGMODE_EASEOUT:
  51508. return (1 - this.easeInCore(1 - gradient));
  51509. }
  51510. if (gradient >= 0.5) {
  51511. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51512. }
  51513. return (this.easeInCore(gradient * 2) * 0.5);
  51514. };
  51515. //Statics
  51516. EasingFunction._EASINGMODE_EASEIN = 0;
  51517. EasingFunction._EASINGMODE_EASEOUT = 1;
  51518. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51519. return EasingFunction;
  51520. }());
  51521. BABYLON.EasingFunction = EasingFunction;
  51522. var CircleEase = /** @class */ (function (_super) {
  51523. __extends(CircleEase, _super);
  51524. function CircleEase() {
  51525. return _super !== null && _super.apply(this, arguments) || this;
  51526. }
  51527. CircleEase.prototype.easeInCore = function (gradient) {
  51528. gradient = Math.max(0, Math.min(1, gradient));
  51529. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51530. };
  51531. return CircleEase;
  51532. }(EasingFunction));
  51533. BABYLON.CircleEase = CircleEase;
  51534. var BackEase = /** @class */ (function (_super) {
  51535. __extends(BackEase, _super);
  51536. function BackEase(amplitude) {
  51537. if (amplitude === void 0) { amplitude = 1; }
  51538. var _this = _super.call(this) || this;
  51539. _this.amplitude = amplitude;
  51540. return _this;
  51541. }
  51542. BackEase.prototype.easeInCore = function (gradient) {
  51543. var num = Math.max(0, this.amplitude);
  51544. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51545. };
  51546. return BackEase;
  51547. }(EasingFunction));
  51548. BABYLON.BackEase = BackEase;
  51549. var BounceEase = /** @class */ (function (_super) {
  51550. __extends(BounceEase, _super);
  51551. function BounceEase(bounces, bounciness) {
  51552. if (bounces === void 0) { bounces = 3; }
  51553. if (bounciness === void 0) { bounciness = 2; }
  51554. var _this = _super.call(this) || this;
  51555. _this.bounces = bounces;
  51556. _this.bounciness = bounciness;
  51557. return _this;
  51558. }
  51559. BounceEase.prototype.easeInCore = function (gradient) {
  51560. var y = Math.max(0.0, this.bounces);
  51561. var bounciness = this.bounciness;
  51562. if (bounciness <= 1.0) {
  51563. bounciness = 1.001;
  51564. }
  51565. var num9 = Math.pow(bounciness, y);
  51566. var num5 = 1.0 - bounciness;
  51567. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51568. var num15 = gradient * num4;
  51569. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51570. var num3 = Math.floor(num65);
  51571. var num13 = num3 + 1.0;
  51572. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51573. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51574. var num7 = (num8 + num12) * 0.5;
  51575. var num6 = gradient - num7;
  51576. var num2 = num7 - num8;
  51577. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51578. };
  51579. return BounceEase;
  51580. }(EasingFunction));
  51581. BABYLON.BounceEase = BounceEase;
  51582. var CubicEase = /** @class */ (function (_super) {
  51583. __extends(CubicEase, _super);
  51584. function CubicEase() {
  51585. return _super !== null && _super.apply(this, arguments) || this;
  51586. }
  51587. CubicEase.prototype.easeInCore = function (gradient) {
  51588. return (gradient * gradient * gradient);
  51589. };
  51590. return CubicEase;
  51591. }(EasingFunction));
  51592. BABYLON.CubicEase = CubicEase;
  51593. var ElasticEase = /** @class */ (function (_super) {
  51594. __extends(ElasticEase, _super);
  51595. function ElasticEase(oscillations, springiness) {
  51596. if (oscillations === void 0) { oscillations = 3; }
  51597. if (springiness === void 0) { springiness = 3; }
  51598. var _this = _super.call(this) || this;
  51599. _this.oscillations = oscillations;
  51600. _this.springiness = springiness;
  51601. return _this;
  51602. }
  51603. ElasticEase.prototype.easeInCore = function (gradient) {
  51604. var num2;
  51605. var num3 = Math.max(0.0, this.oscillations);
  51606. var num = Math.max(0.0, this.springiness);
  51607. if (num == 0) {
  51608. num2 = gradient;
  51609. }
  51610. else {
  51611. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51612. }
  51613. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51614. };
  51615. return ElasticEase;
  51616. }(EasingFunction));
  51617. BABYLON.ElasticEase = ElasticEase;
  51618. var ExponentialEase = /** @class */ (function (_super) {
  51619. __extends(ExponentialEase, _super);
  51620. function ExponentialEase(exponent) {
  51621. if (exponent === void 0) { exponent = 2; }
  51622. var _this = _super.call(this) || this;
  51623. _this.exponent = exponent;
  51624. return _this;
  51625. }
  51626. ExponentialEase.prototype.easeInCore = function (gradient) {
  51627. if (this.exponent <= 0) {
  51628. return gradient;
  51629. }
  51630. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51631. };
  51632. return ExponentialEase;
  51633. }(EasingFunction));
  51634. BABYLON.ExponentialEase = ExponentialEase;
  51635. var PowerEase = /** @class */ (function (_super) {
  51636. __extends(PowerEase, _super);
  51637. function PowerEase(power) {
  51638. if (power === void 0) { power = 2; }
  51639. var _this = _super.call(this) || this;
  51640. _this.power = power;
  51641. return _this;
  51642. }
  51643. PowerEase.prototype.easeInCore = function (gradient) {
  51644. var y = Math.max(0.0, this.power);
  51645. return Math.pow(gradient, y);
  51646. };
  51647. return PowerEase;
  51648. }(EasingFunction));
  51649. BABYLON.PowerEase = PowerEase;
  51650. var QuadraticEase = /** @class */ (function (_super) {
  51651. __extends(QuadraticEase, _super);
  51652. function QuadraticEase() {
  51653. return _super !== null && _super.apply(this, arguments) || this;
  51654. }
  51655. QuadraticEase.prototype.easeInCore = function (gradient) {
  51656. return (gradient * gradient);
  51657. };
  51658. return QuadraticEase;
  51659. }(EasingFunction));
  51660. BABYLON.QuadraticEase = QuadraticEase;
  51661. var QuarticEase = /** @class */ (function (_super) {
  51662. __extends(QuarticEase, _super);
  51663. function QuarticEase() {
  51664. return _super !== null && _super.apply(this, arguments) || this;
  51665. }
  51666. QuarticEase.prototype.easeInCore = function (gradient) {
  51667. return (gradient * gradient * gradient * gradient);
  51668. };
  51669. return QuarticEase;
  51670. }(EasingFunction));
  51671. BABYLON.QuarticEase = QuarticEase;
  51672. var QuinticEase = /** @class */ (function (_super) {
  51673. __extends(QuinticEase, _super);
  51674. function QuinticEase() {
  51675. return _super !== null && _super.apply(this, arguments) || this;
  51676. }
  51677. QuinticEase.prototype.easeInCore = function (gradient) {
  51678. return (gradient * gradient * gradient * gradient * gradient);
  51679. };
  51680. return QuinticEase;
  51681. }(EasingFunction));
  51682. BABYLON.QuinticEase = QuinticEase;
  51683. var SineEase = /** @class */ (function (_super) {
  51684. __extends(SineEase, _super);
  51685. function SineEase() {
  51686. return _super !== null && _super.apply(this, arguments) || this;
  51687. }
  51688. SineEase.prototype.easeInCore = function (gradient) {
  51689. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51690. };
  51691. return SineEase;
  51692. }(EasingFunction));
  51693. BABYLON.SineEase = SineEase;
  51694. var BezierCurveEase = /** @class */ (function (_super) {
  51695. __extends(BezierCurveEase, _super);
  51696. function BezierCurveEase(x1, y1, x2, y2) {
  51697. if (x1 === void 0) { x1 = 0; }
  51698. if (y1 === void 0) { y1 = 0; }
  51699. if (x2 === void 0) { x2 = 1; }
  51700. if (y2 === void 0) { y2 = 1; }
  51701. var _this = _super.call(this) || this;
  51702. _this.x1 = x1;
  51703. _this.y1 = y1;
  51704. _this.x2 = x2;
  51705. _this.y2 = y2;
  51706. return _this;
  51707. }
  51708. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51709. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51710. };
  51711. return BezierCurveEase;
  51712. }(EasingFunction));
  51713. BABYLON.BezierCurveEase = BezierCurveEase;
  51714. })(BABYLON || (BABYLON = {}));
  51715. //# sourceMappingURL=babylon.easing.js.map
  51716. var BABYLON;
  51717. (function (BABYLON) {
  51718. /**
  51719. * A Condition applied to an Action
  51720. */
  51721. var Condition = /** @class */ (function () {
  51722. /**
  51723. * Creates a new Condition
  51724. * @param actionManager the manager of the action the condition is applied to
  51725. */
  51726. function Condition(actionManager) {
  51727. this._actionManager = actionManager;
  51728. }
  51729. /**
  51730. * Check if the current condition is valid
  51731. * @returns a boolean
  51732. */
  51733. Condition.prototype.isValid = function () {
  51734. return true;
  51735. };
  51736. /**
  51737. * Internal only
  51738. * @hidden
  51739. */
  51740. Condition.prototype._getProperty = function (propertyPath) {
  51741. return this._actionManager._getProperty(propertyPath);
  51742. };
  51743. /**
  51744. * Internal only
  51745. * @hidden
  51746. */
  51747. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51748. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51749. };
  51750. /**
  51751. * Serialize placeholder for child classes
  51752. * @returns the serialized object
  51753. */
  51754. Condition.prototype.serialize = function () {
  51755. };
  51756. /**
  51757. * Internal only
  51758. * @hidden
  51759. */
  51760. Condition.prototype._serialize = function (serializedCondition) {
  51761. return {
  51762. type: 2,
  51763. children: [],
  51764. name: serializedCondition.name,
  51765. properties: serializedCondition.properties
  51766. };
  51767. };
  51768. return Condition;
  51769. }());
  51770. BABYLON.Condition = Condition;
  51771. /**
  51772. * Defines specific conditional operators as extensions of Condition
  51773. */
  51774. var ValueCondition = /** @class */ (function (_super) {
  51775. __extends(ValueCondition, _super);
  51776. /**
  51777. * Creates a new ValueCondition
  51778. * @param actionManager manager for the action the condition applies to
  51779. * @param target for the action
  51780. * @param propertyPath path to specify the property of the target the conditional operator uses
  51781. * @param value the value compared by the conditional operator against the current value of the property
  51782. * @param operator the conditional operator, default ValueCondition.IsEqual
  51783. */
  51784. function ValueCondition(actionManager, target,
  51785. /** path to specify the property of the target the conditional operator uses */
  51786. propertyPath,
  51787. /** the value compared by the conditional operator against the current value of the property */
  51788. value,
  51789. /** the conditional operator, default ValueCondition.IsEqual */
  51790. operator) {
  51791. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51792. var _this = _super.call(this, actionManager) || this;
  51793. _this.propertyPath = propertyPath;
  51794. _this.value = value;
  51795. _this.operator = operator;
  51796. _this._target = target;
  51797. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51798. _this._property = _this._getProperty(_this.propertyPath);
  51799. return _this;
  51800. }
  51801. Object.defineProperty(ValueCondition, "IsEqual", {
  51802. /**
  51803. * returns the number for IsEqual
  51804. */
  51805. get: function () {
  51806. return ValueCondition._IsEqual;
  51807. },
  51808. enumerable: true,
  51809. configurable: true
  51810. });
  51811. Object.defineProperty(ValueCondition, "IsDifferent", {
  51812. /**
  51813. * Returns the number for IsDifferent
  51814. */
  51815. get: function () {
  51816. return ValueCondition._IsDifferent;
  51817. },
  51818. enumerable: true,
  51819. configurable: true
  51820. });
  51821. Object.defineProperty(ValueCondition, "IsGreater", {
  51822. /**
  51823. * Returns the number for IsGreater
  51824. */
  51825. get: function () {
  51826. return ValueCondition._IsGreater;
  51827. },
  51828. enumerable: true,
  51829. configurable: true
  51830. });
  51831. Object.defineProperty(ValueCondition, "IsLesser", {
  51832. /**
  51833. * Returns the number for IsLesser
  51834. */
  51835. get: function () {
  51836. return ValueCondition._IsLesser;
  51837. },
  51838. enumerable: true,
  51839. configurable: true
  51840. });
  51841. /**
  51842. * Compares the given value with the property value for the specified conditional operator
  51843. * @returns the result of the comparison
  51844. */
  51845. ValueCondition.prototype.isValid = function () {
  51846. switch (this.operator) {
  51847. case ValueCondition.IsGreater:
  51848. return this._effectiveTarget[this._property] > this.value;
  51849. case ValueCondition.IsLesser:
  51850. return this._effectiveTarget[this._property] < this.value;
  51851. case ValueCondition.IsEqual:
  51852. case ValueCondition.IsDifferent:
  51853. var check;
  51854. if (this.value.equals) {
  51855. check = this.value.equals(this._effectiveTarget[this._property]);
  51856. }
  51857. else {
  51858. check = this.value === this._effectiveTarget[this._property];
  51859. }
  51860. return this.operator === ValueCondition.IsEqual ? check : !check;
  51861. }
  51862. return false;
  51863. };
  51864. /**
  51865. * Serialize the ValueCondition into a JSON compatible object
  51866. * @returns serialization object
  51867. */
  51868. ValueCondition.prototype.serialize = function () {
  51869. return this._serialize({
  51870. name: "ValueCondition",
  51871. properties: [
  51872. BABYLON.Action._GetTargetProperty(this._target),
  51873. { name: "propertyPath", value: this.propertyPath },
  51874. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51875. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51876. ]
  51877. });
  51878. };
  51879. /**
  51880. * Gets the name of the conditional operator for the ValueCondition
  51881. * @param operator the conditional operator
  51882. * @returns the name
  51883. */
  51884. ValueCondition.GetOperatorName = function (operator) {
  51885. switch (operator) {
  51886. case ValueCondition._IsEqual: return "IsEqual";
  51887. case ValueCondition._IsDifferent: return "IsDifferent";
  51888. case ValueCondition._IsGreater: return "IsGreater";
  51889. case ValueCondition._IsLesser: return "IsLesser";
  51890. default: return "";
  51891. }
  51892. };
  51893. /**
  51894. * Internal only
  51895. * @hidden
  51896. */
  51897. ValueCondition._IsEqual = 0;
  51898. /**
  51899. * Internal only
  51900. * @hidden
  51901. */
  51902. ValueCondition._IsDifferent = 1;
  51903. /**
  51904. * Internal only
  51905. * @hidden
  51906. */
  51907. ValueCondition._IsGreater = 2;
  51908. /**
  51909. * Internal only
  51910. * @hidden
  51911. */
  51912. ValueCondition._IsLesser = 3;
  51913. return ValueCondition;
  51914. }(Condition));
  51915. BABYLON.ValueCondition = ValueCondition;
  51916. /**
  51917. * Defines a predicate condition as an extension of Condition
  51918. */
  51919. var PredicateCondition = /** @class */ (function (_super) {
  51920. __extends(PredicateCondition, _super);
  51921. /**
  51922. * Creates a new PredicateCondition
  51923. * @param actionManager manager for the action the condition applies to
  51924. * @param predicate defines the predicate function used to validate the condition
  51925. */
  51926. function PredicateCondition(actionManager,
  51927. /** defines the predicate function used to validate the condition */
  51928. predicate) {
  51929. var _this = _super.call(this, actionManager) || this;
  51930. _this.predicate = predicate;
  51931. return _this;
  51932. }
  51933. /**
  51934. * @returns the validity of the predicate condition
  51935. */
  51936. PredicateCondition.prototype.isValid = function () {
  51937. return this.predicate();
  51938. };
  51939. return PredicateCondition;
  51940. }(Condition));
  51941. BABYLON.PredicateCondition = PredicateCondition;
  51942. /**
  51943. * Defines a state condition as an extension of Condition
  51944. */
  51945. var StateCondition = /** @class */ (function (_super) {
  51946. __extends(StateCondition, _super);
  51947. /**
  51948. * Creates a new StateCondition
  51949. * @param actionManager manager for the action the condition applies to
  51950. * @param target of the condition
  51951. * @param value to compare with target state
  51952. */
  51953. function StateCondition(actionManager, target, value) {
  51954. var _this = _super.call(this, actionManager) || this;
  51955. _this.value = value;
  51956. _this._target = target;
  51957. return _this;
  51958. }
  51959. /**
  51960. * @returns the validity of the state
  51961. */
  51962. StateCondition.prototype.isValid = function () {
  51963. return this._target.state === this.value;
  51964. };
  51965. /**
  51966. * Serialize the StateCondition into a JSON compatible object
  51967. * @returns serialization object
  51968. */
  51969. StateCondition.prototype.serialize = function () {
  51970. return this._serialize({
  51971. name: "StateCondition",
  51972. properties: [
  51973. BABYLON.Action._GetTargetProperty(this._target),
  51974. { name: "value", value: this.value }
  51975. ]
  51976. });
  51977. };
  51978. return StateCondition;
  51979. }(Condition));
  51980. BABYLON.StateCondition = StateCondition;
  51981. })(BABYLON || (BABYLON = {}));
  51982. //# sourceMappingURL=babylon.condition.js.map
  51983. var BABYLON;
  51984. (function (BABYLON) {
  51985. /**
  51986. * The action to be carried out following a trigger
  51987. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51988. */
  51989. var Action = /** @class */ (function () {
  51990. /**
  51991. * Creates a new Action
  51992. * @param triggerOptions the trigger, with or without parameters, for the action
  51993. * @param condition an optional determinant of action
  51994. */
  51995. function Action(
  51996. /** the trigger, with or without parameters, for the action */
  51997. triggerOptions, condition) {
  51998. this.triggerOptions = triggerOptions;
  51999. /**
  52000. * An event triggered prior to action being executed.
  52001. */
  52002. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52003. if (triggerOptions.parameter) {
  52004. this.trigger = triggerOptions.trigger;
  52005. this._triggerParameter = triggerOptions.parameter;
  52006. }
  52007. else {
  52008. this.trigger = triggerOptions;
  52009. }
  52010. this._nextActiveAction = this;
  52011. this._condition = condition;
  52012. }
  52013. /**
  52014. * Internal only
  52015. * @hidden
  52016. */
  52017. Action.prototype._prepare = function () {
  52018. };
  52019. /**
  52020. * Gets the trigger parameters
  52021. * @returns the trigger parameters
  52022. */
  52023. Action.prototype.getTriggerParameter = function () {
  52024. return this._triggerParameter;
  52025. };
  52026. /**
  52027. * Internal only - executes current action event
  52028. * @hidden
  52029. */
  52030. Action.prototype._executeCurrent = function (evt) {
  52031. if (this._nextActiveAction._condition) {
  52032. var condition = this._nextActiveAction._condition;
  52033. var currentRenderId = this._actionManager.getScene().getRenderId();
  52034. // We cache the current evaluation for the current frame
  52035. if (condition._evaluationId === currentRenderId) {
  52036. if (!condition._currentResult) {
  52037. return;
  52038. }
  52039. }
  52040. else {
  52041. condition._evaluationId = currentRenderId;
  52042. if (!condition.isValid()) {
  52043. condition._currentResult = false;
  52044. return;
  52045. }
  52046. condition._currentResult = true;
  52047. }
  52048. }
  52049. this.onBeforeExecuteObservable.notifyObservers(this);
  52050. this._nextActiveAction.execute(evt);
  52051. this.skipToNextActiveAction();
  52052. };
  52053. /**
  52054. * Execute placeholder for child classes
  52055. * @param evt optional action event
  52056. */
  52057. Action.prototype.execute = function (evt) {
  52058. };
  52059. /**
  52060. * Skips to next active action
  52061. */
  52062. Action.prototype.skipToNextActiveAction = function () {
  52063. if (this._nextActiveAction._child) {
  52064. if (!this._nextActiveAction._child._actionManager) {
  52065. this._nextActiveAction._child._actionManager = this._actionManager;
  52066. }
  52067. this._nextActiveAction = this._nextActiveAction._child;
  52068. }
  52069. else {
  52070. this._nextActiveAction = this;
  52071. }
  52072. };
  52073. /**
  52074. * Adds action to chain of actions, may be a DoNothingAction
  52075. * @param action defines the next action to execute
  52076. * @returns The action passed in
  52077. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52078. */
  52079. Action.prototype.then = function (action) {
  52080. this._child = action;
  52081. action._actionManager = this._actionManager;
  52082. action._prepare();
  52083. return action;
  52084. };
  52085. /**
  52086. * Internal only
  52087. * @hidden
  52088. */
  52089. Action.prototype._getProperty = function (propertyPath) {
  52090. return this._actionManager._getProperty(propertyPath);
  52091. };
  52092. /**
  52093. * Internal only
  52094. * @hidden
  52095. */
  52096. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52097. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52098. };
  52099. /**
  52100. * Serialize placeholder for child classes
  52101. * @param parent of child
  52102. * @returns the serialized object
  52103. */
  52104. Action.prototype.serialize = function (parent) {
  52105. };
  52106. /**
  52107. * Internal only called by serialize
  52108. * @hidden
  52109. */
  52110. Action.prototype._serialize = function (serializedAction, parent) {
  52111. var serializationObject = {
  52112. type: 1,
  52113. children: [],
  52114. name: serializedAction.name,
  52115. properties: serializedAction.properties || []
  52116. };
  52117. // Serialize child
  52118. if (this._child) {
  52119. this._child.serialize(serializationObject);
  52120. }
  52121. // Check if "this" has a condition
  52122. if (this._condition) {
  52123. var serializedCondition = this._condition.serialize();
  52124. serializedCondition.children.push(serializationObject);
  52125. if (parent) {
  52126. parent.children.push(serializedCondition);
  52127. }
  52128. return serializedCondition;
  52129. }
  52130. if (parent) {
  52131. parent.children.push(serializationObject);
  52132. }
  52133. return serializationObject;
  52134. };
  52135. /**
  52136. * Internal only
  52137. * @hidden
  52138. */
  52139. Action._SerializeValueAsString = function (value) {
  52140. if (typeof value === "number") {
  52141. return value.toString();
  52142. }
  52143. if (typeof value === "boolean") {
  52144. return value ? "true" : "false";
  52145. }
  52146. if (value instanceof BABYLON.Vector2) {
  52147. return value.x + ", " + value.y;
  52148. }
  52149. if (value instanceof BABYLON.Vector3) {
  52150. return value.x + ", " + value.y + ", " + value.z;
  52151. }
  52152. if (value instanceof BABYLON.Color3) {
  52153. return value.r + ", " + value.g + ", " + value.b;
  52154. }
  52155. if (value instanceof BABYLON.Color4) {
  52156. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52157. }
  52158. return value; // string
  52159. };
  52160. /**
  52161. * Internal only
  52162. * @hidden
  52163. */
  52164. Action._GetTargetProperty = function (target) {
  52165. return {
  52166. name: "target",
  52167. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52168. : target instanceof BABYLON.Light ? "LightProperties"
  52169. : target instanceof BABYLON.Camera ? "CameraProperties"
  52170. : "SceneProperties",
  52171. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52172. };
  52173. };
  52174. return Action;
  52175. }());
  52176. BABYLON.Action = Action;
  52177. })(BABYLON || (BABYLON = {}));
  52178. //# sourceMappingURL=babylon.action.js.map
  52179. var BABYLON;
  52180. (function (BABYLON) {
  52181. /**
  52182. * ActionEvent is the event being sent when an action is triggered.
  52183. */
  52184. var ActionEvent = /** @class */ (function () {
  52185. /**
  52186. * Creates a new ActionEvent
  52187. * @param source The mesh or sprite that triggered the action
  52188. * @param pointerX The X mouse cursor position at the time of the event
  52189. * @param pointerY The Y mouse cursor position at the time of the event
  52190. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52191. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52192. * @param additionalData additional data for the event
  52193. */
  52194. function ActionEvent(
  52195. /** The mesh or sprite that triggered the action */
  52196. source,
  52197. /** The X mouse cursor position at the time of the event */
  52198. pointerX,
  52199. /** The Y mouse cursor position at the time of the event */
  52200. pointerY,
  52201. /** The mesh that is currently pointed at (can be null) */
  52202. meshUnderPointer,
  52203. /** the original (browser) event that triggered the ActionEvent */
  52204. sourceEvent,
  52205. /** additional data for the event */
  52206. additionalData) {
  52207. this.source = source;
  52208. this.pointerX = pointerX;
  52209. this.pointerY = pointerY;
  52210. this.meshUnderPointer = meshUnderPointer;
  52211. this.sourceEvent = sourceEvent;
  52212. this.additionalData = additionalData;
  52213. }
  52214. /**
  52215. * Helper function to auto-create an ActionEvent from a source mesh.
  52216. * @param source The source mesh that triggered the event
  52217. * @param evt The original (browser) event
  52218. * @param additionalData additional data for the event
  52219. * @returns the new ActionEvent
  52220. */
  52221. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52222. var scene = source.getScene();
  52223. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52224. };
  52225. /**
  52226. * Helper function to auto-create an ActionEvent from a source sprite
  52227. * @param source The source sprite that triggered the event
  52228. * @param scene Scene associated with the sprite
  52229. * @param evt The original (browser) event
  52230. * @param additionalData additional data for the event
  52231. * @returns the new ActionEvent
  52232. */
  52233. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52234. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52235. };
  52236. /**
  52237. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52238. * @param scene the scene where the event occurred
  52239. * @param evt The original (browser) event
  52240. * @returns the new ActionEvent
  52241. */
  52242. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52243. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52244. };
  52245. /**
  52246. * Helper function to auto-create an ActionEvent from a primitive
  52247. * @param prim defines the target primitive
  52248. * @param pointerPos defines the pointer position
  52249. * @param evt The original (browser) event
  52250. * @param additionalData additional data for the event
  52251. * @returns the new ActionEvent
  52252. */
  52253. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52254. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52255. };
  52256. return ActionEvent;
  52257. }());
  52258. BABYLON.ActionEvent = ActionEvent;
  52259. /**
  52260. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52261. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52262. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52263. */
  52264. var ActionManager = /** @class */ (function () {
  52265. /**
  52266. * Creates a new action manager
  52267. * @param scene defines the hosting scene
  52268. */
  52269. function ActionManager(scene) {
  52270. // Members
  52271. /** Gets the list of actions */
  52272. this.actions = new Array();
  52273. /** Gets the cursor to use when hovering items */
  52274. this.hoverCursor = '';
  52275. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52276. scene.actionManagers.push(this);
  52277. }
  52278. Object.defineProperty(ActionManager, "NothingTrigger", {
  52279. /**
  52280. * Nothing
  52281. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52282. */
  52283. get: function () {
  52284. return ActionManager._NothingTrigger;
  52285. },
  52286. enumerable: true,
  52287. configurable: true
  52288. });
  52289. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52290. /**
  52291. * On pick
  52292. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52293. */
  52294. get: function () {
  52295. return ActionManager._OnPickTrigger;
  52296. },
  52297. enumerable: true,
  52298. configurable: true
  52299. });
  52300. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52301. /**
  52302. * On left pick
  52303. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52304. */
  52305. get: function () {
  52306. return ActionManager._OnLeftPickTrigger;
  52307. },
  52308. enumerable: true,
  52309. configurable: true
  52310. });
  52311. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52312. /**
  52313. * On right pick
  52314. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52315. */
  52316. get: function () {
  52317. return ActionManager._OnRightPickTrigger;
  52318. },
  52319. enumerable: true,
  52320. configurable: true
  52321. });
  52322. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52323. /**
  52324. * On center pick
  52325. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52326. */
  52327. get: function () {
  52328. return ActionManager._OnCenterPickTrigger;
  52329. },
  52330. enumerable: true,
  52331. configurable: true
  52332. });
  52333. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52334. /**
  52335. * On pick down
  52336. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52337. */
  52338. get: function () {
  52339. return ActionManager._OnPickDownTrigger;
  52340. },
  52341. enumerable: true,
  52342. configurable: true
  52343. });
  52344. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52345. /**
  52346. * On double pick
  52347. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52348. */
  52349. get: function () {
  52350. return ActionManager._OnDoublePickTrigger;
  52351. },
  52352. enumerable: true,
  52353. configurable: true
  52354. });
  52355. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52356. /**
  52357. * On pick up
  52358. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52359. */
  52360. get: function () {
  52361. return ActionManager._OnPickUpTrigger;
  52362. },
  52363. enumerable: true,
  52364. configurable: true
  52365. });
  52366. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52367. /**
  52368. * On pick out.
  52369. * This trigger will only be raised if you also declared a OnPickDown
  52370. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52371. */
  52372. get: function () {
  52373. return ActionManager._OnPickOutTrigger;
  52374. },
  52375. enumerable: true,
  52376. configurable: true
  52377. });
  52378. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52379. /**
  52380. * On long press
  52381. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52382. */
  52383. get: function () {
  52384. return ActionManager._OnLongPressTrigger;
  52385. },
  52386. enumerable: true,
  52387. configurable: true
  52388. });
  52389. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52390. /**
  52391. * On pointer over
  52392. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52393. */
  52394. get: function () {
  52395. return ActionManager._OnPointerOverTrigger;
  52396. },
  52397. enumerable: true,
  52398. configurable: true
  52399. });
  52400. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52401. /**
  52402. * On pointer out
  52403. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52404. */
  52405. get: function () {
  52406. return ActionManager._OnPointerOutTrigger;
  52407. },
  52408. enumerable: true,
  52409. configurable: true
  52410. });
  52411. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52412. /**
  52413. * On every frame
  52414. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52415. */
  52416. get: function () {
  52417. return ActionManager._OnEveryFrameTrigger;
  52418. },
  52419. enumerable: true,
  52420. configurable: true
  52421. });
  52422. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52423. /**
  52424. * On intersection enter
  52425. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52426. */
  52427. get: function () {
  52428. return ActionManager._OnIntersectionEnterTrigger;
  52429. },
  52430. enumerable: true,
  52431. configurable: true
  52432. });
  52433. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52434. /**
  52435. * On intersection exit
  52436. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52437. */
  52438. get: function () {
  52439. return ActionManager._OnIntersectionExitTrigger;
  52440. },
  52441. enumerable: true,
  52442. configurable: true
  52443. });
  52444. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52445. /**
  52446. * On key down
  52447. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52448. */
  52449. get: function () {
  52450. return ActionManager._OnKeyDownTrigger;
  52451. },
  52452. enumerable: true,
  52453. configurable: true
  52454. });
  52455. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52456. /**
  52457. * On key up
  52458. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52459. */
  52460. get: function () {
  52461. return ActionManager._OnKeyUpTrigger;
  52462. },
  52463. enumerable: true,
  52464. configurable: true
  52465. });
  52466. // Methods
  52467. /**
  52468. * Releases all associated resources
  52469. */
  52470. ActionManager.prototype.dispose = function () {
  52471. var index = this._scene.actionManagers.indexOf(this);
  52472. for (var i = 0; i < this.actions.length; i++) {
  52473. var action = this.actions[i];
  52474. ActionManager.Triggers[action.trigger]--;
  52475. if (ActionManager.Triggers[action.trigger] === 0) {
  52476. delete ActionManager.Triggers[action.trigger];
  52477. }
  52478. }
  52479. if (index > -1) {
  52480. this._scene.actionManagers.splice(index, 1);
  52481. }
  52482. };
  52483. /**
  52484. * Gets hosting scene
  52485. * @returns the hosting scene
  52486. */
  52487. ActionManager.prototype.getScene = function () {
  52488. return this._scene;
  52489. };
  52490. /**
  52491. * Does this action manager handles actions of any of the given triggers
  52492. * @param triggers defines the triggers to be tested
  52493. * @return a boolean indicating whether one (or more) of the triggers is handled
  52494. */
  52495. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52496. for (var index = 0; index < this.actions.length; index++) {
  52497. var action = this.actions[index];
  52498. if (triggers.indexOf(action.trigger) > -1) {
  52499. return true;
  52500. }
  52501. }
  52502. return false;
  52503. };
  52504. /**
  52505. * Does this action manager handles actions of a given trigger
  52506. * @param trigger defines the trigger to be tested
  52507. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52508. * @return whether the trigger is handled
  52509. */
  52510. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52511. for (var index = 0; index < this.actions.length; index++) {
  52512. var action = this.actions[index];
  52513. if (action.trigger === trigger) {
  52514. if (parameterPredicate) {
  52515. if (parameterPredicate(action.getTriggerParameter())) {
  52516. return true;
  52517. }
  52518. }
  52519. else {
  52520. return true;
  52521. }
  52522. }
  52523. }
  52524. return false;
  52525. };
  52526. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52527. /**
  52528. * Does this action manager has pointer triggers
  52529. */
  52530. get: function () {
  52531. for (var index = 0; index < this.actions.length; index++) {
  52532. var action = this.actions[index];
  52533. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52534. return true;
  52535. }
  52536. }
  52537. return false;
  52538. },
  52539. enumerable: true,
  52540. configurable: true
  52541. });
  52542. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52543. /**
  52544. * Does this action manager has pick triggers
  52545. */
  52546. get: function () {
  52547. for (var index = 0; index < this.actions.length; index++) {
  52548. var action = this.actions[index];
  52549. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52550. return true;
  52551. }
  52552. }
  52553. return false;
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. Object.defineProperty(ActionManager, "HasTriggers", {
  52559. /**
  52560. * Does exist one action manager with at least one trigger
  52561. **/
  52562. get: function () {
  52563. for (var t in ActionManager.Triggers) {
  52564. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52565. return true;
  52566. }
  52567. }
  52568. return false;
  52569. },
  52570. enumerable: true,
  52571. configurable: true
  52572. });
  52573. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52574. /**
  52575. * Does exist one action manager with at least one pick trigger
  52576. **/
  52577. get: function () {
  52578. for (var t in ActionManager.Triggers) {
  52579. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52580. var t_int = parseInt(t);
  52581. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52582. return true;
  52583. }
  52584. }
  52585. }
  52586. return false;
  52587. },
  52588. enumerable: true,
  52589. configurable: true
  52590. });
  52591. /**
  52592. * Does exist one action manager that handles actions of a given trigger
  52593. * @param trigger defines the trigger to be tested
  52594. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52595. **/
  52596. ActionManager.HasSpecificTrigger = function (trigger) {
  52597. for (var t in ActionManager.Triggers) {
  52598. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52599. var t_int = parseInt(t);
  52600. if (t_int === trigger) {
  52601. return true;
  52602. }
  52603. }
  52604. }
  52605. return false;
  52606. };
  52607. /**
  52608. * Registers an action to this action manager
  52609. * @param action defines the action to be registered
  52610. * @return the action amended (prepared) after registration
  52611. */
  52612. ActionManager.prototype.registerAction = function (action) {
  52613. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52614. if (this.getScene().actionManager !== this) {
  52615. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52616. return null;
  52617. }
  52618. }
  52619. this.actions.push(action);
  52620. if (ActionManager.Triggers[action.trigger]) {
  52621. ActionManager.Triggers[action.trigger]++;
  52622. }
  52623. else {
  52624. ActionManager.Triggers[action.trigger] = 1;
  52625. }
  52626. action._actionManager = this;
  52627. action._prepare();
  52628. return action;
  52629. };
  52630. /**
  52631. * Unregisters an action to this action manager
  52632. * @param action defines the action to be unregistered
  52633. * @return a boolean indicating whether the action has been unregistered
  52634. */
  52635. ActionManager.prototype.unregisterAction = function (action) {
  52636. var index = this.actions.indexOf(action);
  52637. if (index !== -1) {
  52638. this.actions.splice(index, 1);
  52639. ActionManager.Triggers[action.trigger] -= 1;
  52640. if (ActionManager.Triggers[action.trigger] === 0) {
  52641. delete ActionManager.Triggers[action.trigger];
  52642. }
  52643. delete action._actionManager;
  52644. return true;
  52645. }
  52646. return false;
  52647. };
  52648. /**
  52649. * Process a specific trigger
  52650. * @param trigger defines the trigger to process
  52651. * @param evt defines the event details to be processed
  52652. */
  52653. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52654. for (var index = 0; index < this.actions.length; index++) {
  52655. var action = this.actions[index];
  52656. if (action.trigger === trigger) {
  52657. if (evt) {
  52658. if (trigger === ActionManager.OnKeyUpTrigger
  52659. || trigger === ActionManager.OnKeyDownTrigger) {
  52660. var parameter = action.getTriggerParameter();
  52661. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52662. if (!parameter.toLowerCase) {
  52663. continue;
  52664. }
  52665. var lowerCase = parameter.toLowerCase();
  52666. if (lowerCase !== evt.sourceEvent.key) {
  52667. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52668. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52669. if (actualkey !== lowerCase) {
  52670. continue;
  52671. }
  52672. }
  52673. }
  52674. }
  52675. }
  52676. action._executeCurrent(evt);
  52677. }
  52678. }
  52679. };
  52680. /** @hidden */
  52681. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52682. var properties = propertyPath.split(".");
  52683. for (var index = 0; index < properties.length - 1; index++) {
  52684. target = target[properties[index]];
  52685. }
  52686. return target;
  52687. };
  52688. /** @hidden */
  52689. ActionManager.prototype._getProperty = function (propertyPath) {
  52690. var properties = propertyPath.split(".");
  52691. return properties[properties.length - 1];
  52692. };
  52693. /**
  52694. * Serialize this manager to a JSON object
  52695. * @param name defines the property name to store this manager
  52696. * @returns a JSON representation of this manager
  52697. */
  52698. ActionManager.prototype.serialize = function (name) {
  52699. var root = {
  52700. children: new Array(),
  52701. name: name,
  52702. type: 3,
  52703. properties: new Array() // Empty for root but required
  52704. };
  52705. for (var i = 0; i < this.actions.length; i++) {
  52706. var triggerObject = {
  52707. type: 0,
  52708. children: new Array(),
  52709. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52710. properties: new Array()
  52711. };
  52712. var triggerOptions = this.actions[i].triggerOptions;
  52713. if (triggerOptions && typeof triggerOptions !== "number") {
  52714. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52715. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52716. }
  52717. else {
  52718. var parameter = {};
  52719. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52720. if (triggerOptions.parameter.mesh) {
  52721. parameter._meshId = triggerOptions.parameter.mesh.id;
  52722. }
  52723. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52724. }
  52725. }
  52726. // Serialize child action, recursively
  52727. this.actions[i].serialize(triggerObject);
  52728. // Add serialized trigger
  52729. root.children.push(triggerObject);
  52730. }
  52731. return root;
  52732. };
  52733. /**
  52734. * Creates a new ActionManager from a JSON data
  52735. * @param parsedActions defines the JSON data to read from
  52736. * @param object defines the hosting mesh
  52737. * @param scene defines the hosting scene
  52738. */
  52739. ActionManager.Parse = function (parsedActions, object, scene) {
  52740. var actionManager = new ActionManager(scene);
  52741. if (object === null)
  52742. scene.actionManager = actionManager;
  52743. else
  52744. object.actionManager = actionManager;
  52745. // instanciate a new object
  52746. var instanciate = function (name, params) {
  52747. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52748. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52749. newInstance.constructor.apply(newInstance, params);
  52750. return newInstance;
  52751. };
  52752. var parseParameter = function (name, value, target, propertyPath) {
  52753. if (propertyPath === null) {
  52754. // String, boolean or float
  52755. var floatValue = parseFloat(value);
  52756. if (value === "true" || value === "false")
  52757. return value === "true";
  52758. else
  52759. return isNaN(floatValue) ? value : floatValue;
  52760. }
  52761. var effectiveTarget = propertyPath.split(".");
  52762. var values = value.split(",");
  52763. // Get effective Target
  52764. for (var i = 0; i < effectiveTarget.length; i++) {
  52765. target = target[effectiveTarget[i]];
  52766. }
  52767. // Return appropriate value with its type
  52768. if (typeof (target) === "boolean")
  52769. return values[0] === "true";
  52770. if (typeof (target) === "string")
  52771. return values[0];
  52772. // Parameters with multiple values such as Vector3 etc.
  52773. var split = new Array();
  52774. for (var i = 0; i < values.length; i++)
  52775. split.push(parseFloat(values[i]));
  52776. if (target instanceof BABYLON.Vector3)
  52777. return BABYLON.Vector3.FromArray(split);
  52778. if (target instanceof BABYLON.Vector4)
  52779. return BABYLON.Vector4.FromArray(split);
  52780. if (target instanceof BABYLON.Color3)
  52781. return BABYLON.Color3.FromArray(split);
  52782. if (target instanceof BABYLON.Color4)
  52783. return BABYLON.Color4.FromArray(split);
  52784. return parseFloat(values[0]);
  52785. };
  52786. // traverse graph per trigger
  52787. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52788. if (combineArray === void 0) { combineArray = null; }
  52789. if (parsedAction.detached)
  52790. return;
  52791. var parameters = new Array();
  52792. var target = null;
  52793. var propertyPath = null;
  52794. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52795. // Parameters
  52796. if (parsedAction.type === 2)
  52797. parameters.push(actionManager);
  52798. else
  52799. parameters.push(trigger);
  52800. if (combine) {
  52801. var actions = new Array();
  52802. for (var j = 0; j < parsedAction.combine.length; j++) {
  52803. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52804. }
  52805. parameters.push(actions);
  52806. }
  52807. else {
  52808. for (var i = 0; i < parsedAction.properties.length; i++) {
  52809. var value = parsedAction.properties[i].value;
  52810. var name = parsedAction.properties[i].name;
  52811. var targetType = parsedAction.properties[i].targetType;
  52812. if (name === "target")
  52813. if (targetType !== null && targetType === "SceneProperties")
  52814. value = target = scene;
  52815. else
  52816. value = target = scene.getNodeByName(value);
  52817. else if (name === "parent")
  52818. value = scene.getNodeByName(value);
  52819. else if (name === "sound")
  52820. value = scene.getSoundByName(value);
  52821. else if (name !== "propertyPath") {
  52822. if (parsedAction.type === 2 && name === "operator")
  52823. value = BABYLON.ValueCondition[value];
  52824. else
  52825. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52826. }
  52827. else {
  52828. propertyPath = value;
  52829. }
  52830. parameters.push(value);
  52831. }
  52832. }
  52833. if (combineArray === null) {
  52834. parameters.push(condition);
  52835. }
  52836. else {
  52837. parameters.push(null);
  52838. }
  52839. // If interpolate value action
  52840. if (parsedAction.name === "InterpolateValueAction") {
  52841. var param = parameters[parameters.length - 2];
  52842. parameters[parameters.length - 1] = param;
  52843. parameters[parameters.length - 2] = condition;
  52844. }
  52845. // Action or condition(s) and not CombineAction
  52846. var newAction = instanciate(parsedAction.name, parameters);
  52847. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52848. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52849. if (action)
  52850. action.then(nothing);
  52851. else
  52852. actionManager.registerAction(nothing);
  52853. action = nothing;
  52854. }
  52855. if (combineArray === null) {
  52856. if (newAction instanceof BABYLON.Condition) {
  52857. condition = newAction;
  52858. newAction = action;
  52859. }
  52860. else {
  52861. condition = null;
  52862. if (action)
  52863. action.then(newAction);
  52864. else
  52865. actionManager.registerAction(newAction);
  52866. }
  52867. }
  52868. else {
  52869. combineArray.push(newAction);
  52870. }
  52871. for (var i = 0; i < parsedAction.children.length; i++)
  52872. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52873. };
  52874. // triggers
  52875. for (var i = 0; i < parsedActions.children.length; i++) {
  52876. var triggerParams;
  52877. var trigger = parsedActions.children[i];
  52878. if (trigger.properties.length > 0) {
  52879. var param = trigger.properties[0].value;
  52880. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52881. if (value._meshId) {
  52882. value.mesh = scene.getMeshByID(value._meshId);
  52883. }
  52884. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52885. }
  52886. else
  52887. triggerParams = ActionManager[trigger.name];
  52888. for (var j = 0; j < trigger.children.length; j++) {
  52889. if (!trigger.detached)
  52890. traverse(trigger.children[j], triggerParams, null, null);
  52891. }
  52892. }
  52893. };
  52894. /**
  52895. * Get a trigger name by index
  52896. * @param trigger defines the trigger index
  52897. * @returns a trigger name
  52898. */
  52899. ActionManager.GetTriggerName = function (trigger) {
  52900. switch (trigger) {
  52901. case 0: return "NothingTrigger";
  52902. case 1: return "OnPickTrigger";
  52903. case 2: return "OnLeftPickTrigger";
  52904. case 3: return "OnRightPickTrigger";
  52905. case 4: return "OnCenterPickTrigger";
  52906. case 5: return "OnPickDownTrigger";
  52907. case 6: return "OnPickUpTrigger";
  52908. case 7: return "OnLongPressTrigger";
  52909. case 8: return "OnPointerOverTrigger";
  52910. case 9: return "OnPointerOutTrigger";
  52911. case 10: return "OnEveryFrameTrigger";
  52912. case 11: return "OnIntersectionEnterTrigger";
  52913. case 12: return "OnIntersectionExitTrigger";
  52914. case 13: return "OnKeyDownTrigger";
  52915. case 14: return "OnKeyUpTrigger";
  52916. case 15: return "OnPickOutTrigger";
  52917. default: return "";
  52918. }
  52919. };
  52920. // Statics
  52921. ActionManager._NothingTrigger = 0;
  52922. ActionManager._OnPickTrigger = 1;
  52923. ActionManager._OnLeftPickTrigger = 2;
  52924. ActionManager._OnRightPickTrigger = 3;
  52925. ActionManager._OnCenterPickTrigger = 4;
  52926. ActionManager._OnPickDownTrigger = 5;
  52927. ActionManager._OnDoublePickTrigger = 6;
  52928. ActionManager._OnPickUpTrigger = 7;
  52929. ActionManager._OnLongPressTrigger = 8;
  52930. ActionManager._OnPointerOverTrigger = 9;
  52931. ActionManager._OnPointerOutTrigger = 10;
  52932. ActionManager._OnEveryFrameTrigger = 11;
  52933. ActionManager._OnIntersectionEnterTrigger = 12;
  52934. ActionManager._OnIntersectionExitTrigger = 13;
  52935. ActionManager._OnKeyDownTrigger = 14;
  52936. ActionManager._OnKeyUpTrigger = 15;
  52937. ActionManager._OnPickOutTrigger = 16;
  52938. /** Gets the list of active triggers */
  52939. ActionManager.Triggers = {};
  52940. return ActionManager;
  52941. }());
  52942. BABYLON.ActionManager = ActionManager;
  52943. })(BABYLON || (BABYLON = {}));
  52944. //# sourceMappingURL=babylon.actionManager.js.map
  52945. var BABYLON;
  52946. (function (BABYLON) {
  52947. var InterpolateValueAction = /** @class */ (function (_super) {
  52948. __extends(InterpolateValueAction, _super);
  52949. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52950. if (duration === void 0) { duration = 1000; }
  52951. var _this = _super.call(this, triggerOptions, condition) || this;
  52952. _this.propertyPath = propertyPath;
  52953. _this.value = value;
  52954. _this.duration = duration;
  52955. _this.stopOtherAnimations = stopOtherAnimations;
  52956. _this.onInterpolationDone = onInterpolationDone;
  52957. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52958. _this._target = _this._effectiveTarget = target;
  52959. return _this;
  52960. }
  52961. InterpolateValueAction.prototype._prepare = function () {
  52962. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52963. this._property = this._getProperty(this.propertyPath);
  52964. };
  52965. InterpolateValueAction.prototype.execute = function () {
  52966. var _this = this;
  52967. var scene = this._actionManager.getScene();
  52968. var keys = [
  52969. {
  52970. frame: 0,
  52971. value: this._effectiveTarget[this._property]
  52972. }, {
  52973. frame: 100,
  52974. value: this.value
  52975. }
  52976. ];
  52977. var dataType;
  52978. if (typeof this.value === "number") {
  52979. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52980. }
  52981. else if (this.value instanceof BABYLON.Color3) {
  52982. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52983. }
  52984. else if (this.value instanceof BABYLON.Vector3) {
  52985. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52986. }
  52987. else if (this.value instanceof BABYLON.Matrix) {
  52988. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52989. }
  52990. else if (this.value instanceof BABYLON.Quaternion) {
  52991. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52992. }
  52993. else {
  52994. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52995. return;
  52996. }
  52997. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52998. animation.setKeys(keys);
  52999. if (this.stopOtherAnimations) {
  53000. scene.stopAnimation(this._effectiveTarget);
  53001. }
  53002. var wrapper = function () {
  53003. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53004. if (_this.onInterpolationDone) {
  53005. _this.onInterpolationDone();
  53006. }
  53007. };
  53008. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53009. };
  53010. InterpolateValueAction.prototype.serialize = function (parent) {
  53011. return _super.prototype._serialize.call(this, {
  53012. name: "InterpolateValueAction",
  53013. properties: [
  53014. BABYLON.Action._GetTargetProperty(this._target),
  53015. { name: "propertyPath", value: this.propertyPath },
  53016. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53017. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53018. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53019. ]
  53020. }, parent);
  53021. };
  53022. return InterpolateValueAction;
  53023. }(BABYLON.Action));
  53024. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53025. })(BABYLON || (BABYLON = {}));
  53026. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53027. var BABYLON;
  53028. (function (BABYLON) {
  53029. var SwitchBooleanAction = /** @class */ (function (_super) {
  53030. __extends(SwitchBooleanAction, _super);
  53031. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53032. var _this = _super.call(this, triggerOptions, condition) || this;
  53033. _this.propertyPath = propertyPath;
  53034. _this._target = _this._effectiveTarget = target;
  53035. return _this;
  53036. }
  53037. SwitchBooleanAction.prototype._prepare = function () {
  53038. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53039. this._property = this._getProperty(this.propertyPath);
  53040. };
  53041. SwitchBooleanAction.prototype.execute = function () {
  53042. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53043. };
  53044. SwitchBooleanAction.prototype.serialize = function (parent) {
  53045. return _super.prototype._serialize.call(this, {
  53046. name: "SwitchBooleanAction",
  53047. properties: [
  53048. BABYLON.Action._GetTargetProperty(this._target),
  53049. { name: "propertyPath", value: this.propertyPath }
  53050. ]
  53051. }, parent);
  53052. };
  53053. return SwitchBooleanAction;
  53054. }(BABYLON.Action));
  53055. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53056. var SetStateAction = /** @class */ (function (_super) {
  53057. __extends(SetStateAction, _super);
  53058. function SetStateAction(triggerOptions, target, value, condition) {
  53059. var _this = _super.call(this, triggerOptions, condition) || this;
  53060. _this.value = value;
  53061. _this._target = target;
  53062. return _this;
  53063. }
  53064. SetStateAction.prototype.execute = function () {
  53065. this._target.state = this.value;
  53066. };
  53067. SetStateAction.prototype.serialize = function (parent) {
  53068. return _super.prototype._serialize.call(this, {
  53069. name: "SetStateAction",
  53070. properties: [
  53071. BABYLON.Action._GetTargetProperty(this._target),
  53072. { name: "value", value: this.value }
  53073. ]
  53074. }, parent);
  53075. };
  53076. return SetStateAction;
  53077. }(BABYLON.Action));
  53078. BABYLON.SetStateAction = SetStateAction;
  53079. var SetValueAction = /** @class */ (function (_super) {
  53080. __extends(SetValueAction, _super);
  53081. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53082. var _this = _super.call(this, triggerOptions, condition) || this;
  53083. _this.propertyPath = propertyPath;
  53084. _this.value = value;
  53085. _this._target = _this._effectiveTarget = target;
  53086. return _this;
  53087. }
  53088. SetValueAction.prototype._prepare = function () {
  53089. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53090. this._property = this._getProperty(this.propertyPath);
  53091. };
  53092. SetValueAction.prototype.execute = function () {
  53093. this._effectiveTarget[this._property] = this.value;
  53094. if (this._target.markAsDirty) {
  53095. this._target.markAsDirty(this._property);
  53096. }
  53097. };
  53098. SetValueAction.prototype.serialize = function (parent) {
  53099. return _super.prototype._serialize.call(this, {
  53100. name: "SetValueAction",
  53101. properties: [
  53102. BABYLON.Action._GetTargetProperty(this._target),
  53103. { name: "propertyPath", value: this.propertyPath },
  53104. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53105. ]
  53106. }, parent);
  53107. };
  53108. return SetValueAction;
  53109. }(BABYLON.Action));
  53110. BABYLON.SetValueAction = SetValueAction;
  53111. var IncrementValueAction = /** @class */ (function (_super) {
  53112. __extends(IncrementValueAction, _super);
  53113. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53114. var _this = _super.call(this, triggerOptions, condition) || this;
  53115. _this.propertyPath = propertyPath;
  53116. _this.value = value;
  53117. _this._target = _this._effectiveTarget = target;
  53118. return _this;
  53119. }
  53120. IncrementValueAction.prototype._prepare = function () {
  53121. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53122. this._property = this._getProperty(this.propertyPath);
  53123. if (typeof this._effectiveTarget[this._property] !== "number") {
  53124. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53125. }
  53126. };
  53127. IncrementValueAction.prototype.execute = function () {
  53128. this._effectiveTarget[this._property] += this.value;
  53129. if (this._target.markAsDirty) {
  53130. this._target.markAsDirty(this._property);
  53131. }
  53132. };
  53133. IncrementValueAction.prototype.serialize = function (parent) {
  53134. return _super.prototype._serialize.call(this, {
  53135. name: "IncrementValueAction",
  53136. properties: [
  53137. BABYLON.Action._GetTargetProperty(this._target),
  53138. { name: "propertyPath", value: this.propertyPath },
  53139. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53140. ]
  53141. }, parent);
  53142. };
  53143. return IncrementValueAction;
  53144. }(BABYLON.Action));
  53145. BABYLON.IncrementValueAction = IncrementValueAction;
  53146. var PlayAnimationAction = /** @class */ (function (_super) {
  53147. __extends(PlayAnimationAction, _super);
  53148. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53149. var _this = _super.call(this, triggerOptions, condition) || this;
  53150. _this.from = from;
  53151. _this.to = to;
  53152. _this.loop = loop;
  53153. _this._target = target;
  53154. return _this;
  53155. }
  53156. PlayAnimationAction.prototype._prepare = function () {
  53157. };
  53158. PlayAnimationAction.prototype.execute = function () {
  53159. var scene = this._actionManager.getScene();
  53160. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53161. };
  53162. PlayAnimationAction.prototype.serialize = function (parent) {
  53163. return _super.prototype._serialize.call(this, {
  53164. name: "PlayAnimationAction",
  53165. properties: [
  53166. BABYLON.Action._GetTargetProperty(this._target),
  53167. { name: "from", value: String(this.from) },
  53168. { name: "to", value: String(this.to) },
  53169. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53170. ]
  53171. }, parent);
  53172. };
  53173. return PlayAnimationAction;
  53174. }(BABYLON.Action));
  53175. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53176. var StopAnimationAction = /** @class */ (function (_super) {
  53177. __extends(StopAnimationAction, _super);
  53178. function StopAnimationAction(triggerOptions, target, condition) {
  53179. var _this = _super.call(this, triggerOptions, condition) || this;
  53180. _this._target = target;
  53181. return _this;
  53182. }
  53183. StopAnimationAction.prototype._prepare = function () {
  53184. };
  53185. StopAnimationAction.prototype.execute = function () {
  53186. var scene = this._actionManager.getScene();
  53187. scene.stopAnimation(this._target);
  53188. };
  53189. StopAnimationAction.prototype.serialize = function (parent) {
  53190. return _super.prototype._serialize.call(this, {
  53191. name: "StopAnimationAction",
  53192. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53193. }, parent);
  53194. };
  53195. return StopAnimationAction;
  53196. }(BABYLON.Action));
  53197. BABYLON.StopAnimationAction = StopAnimationAction;
  53198. var DoNothingAction = /** @class */ (function (_super) {
  53199. __extends(DoNothingAction, _super);
  53200. function DoNothingAction(triggerOptions, condition) {
  53201. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53202. return _super.call(this, triggerOptions, condition) || this;
  53203. }
  53204. DoNothingAction.prototype.execute = function () {
  53205. };
  53206. DoNothingAction.prototype.serialize = function (parent) {
  53207. return _super.prototype._serialize.call(this, {
  53208. name: "DoNothingAction",
  53209. properties: []
  53210. }, parent);
  53211. };
  53212. return DoNothingAction;
  53213. }(BABYLON.Action));
  53214. BABYLON.DoNothingAction = DoNothingAction;
  53215. var CombineAction = /** @class */ (function (_super) {
  53216. __extends(CombineAction, _super);
  53217. function CombineAction(triggerOptions, children, condition) {
  53218. var _this = _super.call(this, triggerOptions, condition) || this;
  53219. _this.children = children;
  53220. return _this;
  53221. }
  53222. CombineAction.prototype._prepare = function () {
  53223. for (var index = 0; index < this.children.length; index++) {
  53224. this.children[index]._actionManager = this._actionManager;
  53225. this.children[index]._prepare();
  53226. }
  53227. };
  53228. CombineAction.prototype.execute = function (evt) {
  53229. for (var index = 0; index < this.children.length; index++) {
  53230. this.children[index].execute(evt);
  53231. }
  53232. };
  53233. CombineAction.prototype.serialize = function (parent) {
  53234. var serializationObject = _super.prototype._serialize.call(this, {
  53235. name: "CombineAction",
  53236. properties: [],
  53237. combine: []
  53238. }, parent);
  53239. for (var i = 0; i < this.children.length; i++) {
  53240. serializationObject.combine.push(this.children[i].serialize(null));
  53241. }
  53242. return serializationObject;
  53243. };
  53244. return CombineAction;
  53245. }(BABYLON.Action));
  53246. BABYLON.CombineAction = CombineAction;
  53247. var ExecuteCodeAction = /** @class */ (function (_super) {
  53248. __extends(ExecuteCodeAction, _super);
  53249. function ExecuteCodeAction(triggerOptions, func, condition) {
  53250. var _this = _super.call(this, triggerOptions, condition) || this;
  53251. _this.func = func;
  53252. return _this;
  53253. }
  53254. ExecuteCodeAction.prototype.execute = function (evt) {
  53255. this.func(evt);
  53256. };
  53257. return ExecuteCodeAction;
  53258. }(BABYLON.Action));
  53259. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53260. var SetParentAction = /** @class */ (function (_super) {
  53261. __extends(SetParentAction, _super);
  53262. function SetParentAction(triggerOptions, target, parent, condition) {
  53263. var _this = _super.call(this, triggerOptions, condition) || this;
  53264. _this._target = target;
  53265. _this._parent = parent;
  53266. return _this;
  53267. }
  53268. SetParentAction.prototype._prepare = function () {
  53269. };
  53270. SetParentAction.prototype.execute = function () {
  53271. if (this._target.parent === this._parent) {
  53272. return;
  53273. }
  53274. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53275. invertParentWorldMatrix.invert();
  53276. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53277. this._target.parent = this._parent;
  53278. };
  53279. SetParentAction.prototype.serialize = function (parent) {
  53280. return _super.prototype._serialize.call(this, {
  53281. name: "SetParentAction",
  53282. properties: [
  53283. BABYLON.Action._GetTargetProperty(this._target),
  53284. BABYLON.Action._GetTargetProperty(this._parent),
  53285. ]
  53286. }, parent);
  53287. };
  53288. return SetParentAction;
  53289. }(BABYLON.Action));
  53290. BABYLON.SetParentAction = SetParentAction;
  53291. var PlaySoundAction = /** @class */ (function (_super) {
  53292. __extends(PlaySoundAction, _super);
  53293. function PlaySoundAction(triggerOptions, sound, condition) {
  53294. var _this = _super.call(this, triggerOptions, condition) || this;
  53295. _this._sound = sound;
  53296. return _this;
  53297. }
  53298. PlaySoundAction.prototype._prepare = function () {
  53299. };
  53300. PlaySoundAction.prototype.execute = function () {
  53301. if (this._sound !== undefined)
  53302. this._sound.play();
  53303. };
  53304. PlaySoundAction.prototype.serialize = function (parent) {
  53305. return _super.prototype._serialize.call(this, {
  53306. name: "PlaySoundAction",
  53307. properties: [{ name: "sound", value: this._sound.name }]
  53308. }, parent);
  53309. };
  53310. return PlaySoundAction;
  53311. }(BABYLON.Action));
  53312. BABYLON.PlaySoundAction = PlaySoundAction;
  53313. var StopSoundAction = /** @class */ (function (_super) {
  53314. __extends(StopSoundAction, _super);
  53315. function StopSoundAction(triggerOptions, sound, condition) {
  53316. var _this = _super.call(this, triggerOptions, condition) || this;
  53317. _this._sound = sound;
  53318. return _this;
  53319. }
  53320. StopSoundAction.prototype._prepare = function () {
  53321. };
  53322. StopSoundAction.prototype.execute = function () {
  53323. if (this._sound !== undefined)
  53324. this._sound.stop();
  53325. };
  53326. StopSoundAction.prototype.serialize = function (parent) {
  53327. return _super.prototype._serialize.call(this, {
  53328. name: "StopSoundAction",
  53329. properties: [{ name: "sound", value: this._sound.name }]
  53330. }, parent);
  53331. };
  53332. return StopSoundAction;
  53333. }(BABYLON.Action));
  53334. BABYLON.StopSoundAction = StopSoundAction;
  53335. })(BABYLON || (BABYLON = {}));
  53336. //# sourceMappingURL=babylon.directActions.js.map
  53337. var BABYLON;
  53338. (function (BABYLON) {
  53339. var SpriteManager = /** @class */ (function () {
  53340. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53341. if (epsilon === void 0) { epsilon = 0.01; }
  53342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53343. this.name = name;
  53344. this.sprites = new Array();
  53345. this.renderingGroupId = 0;
  53346. this.layerMask = 0x0FFFFFFF;
  53347. this.fogEnabled = true;
  53348. this.isPickable = false;
  53349. /**
  53350. * An event triggered when the manager is disposed.
  53351. */
  53352. this.onDisposeObservable = new BABYLON.Observable();
  53353. this._vertexBuffers = {};
  53354. this._capacity = capacity;
  53355. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53356. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53357. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53358. if (cellSize.width && cellSize.height) {
  53359. this.cellWidth = cellSize.width;
  53360. this.cellHeight = cellSize.height;
  53361. }
  53362. else if (cellSize !== undefined) {
  53363. this.cellWidth = cellSize;
  53364. this.cellHeight = cellSize;
  53365. }
  53366. else {
  53367. return;
  53368. }
  53369. this._epsilon = epsilon;
  53370. this._scene = scene;
  53371. this._scene.spriteManagers.push(this);
  53372. var indices = [];
  53373. var index = 0;
  53374. for (var count = 0; count < capacity; count++) {
  53375. indices.push(index);
  53376. indices.push(index + 1);
  53377. indices.push(index + 2);
  53378. indices.push(index);
  53379. indices.push(index + 2);
  53380. indices.push(index + 3);
  53381. index += 4;
  53382. }
  53383. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53384. // VBO
  53385. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53386. this._vertexData = new Float32Array(capacity * 16 * 4);
  53387. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53388. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53389. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53390. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53391. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53392. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53393. this._vertexBuffers["options"] = options;
  53394. this._vertexBuffers["cellInfo"] = cellInfo;
  53395. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53396. // Effects
  53397. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53398. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53399. }
  53400. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53401. set: function (callback) {
  53402. if (this._onDisposeObserver) {
  53403. this.onDisposeObservable.remove(this._onDisposeObserver);
  53404. }
  53405. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53406. },
  53407. enumerable: true,
  53408. configurable: true
  53409. });
  53410. Object.defineProperty(SpriteManager.prototype, "texture", {
  53411. get: function () {
  53412. return this._spriteTexture;
  53413. },
  53414. set: function (value) {
  53415. this._spriteTexture = value;
  53416. },
  53417. enumerable: true,
  53418. configurable: true
  53419. });
  53420. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53421. var arrayOffset = index * 16;
  53422. if (offsetX === 0)
  53423. offsetX = this._epsilon;
  53424. else if (offsetX === 1)
  53425. offsetX = 1 - this._epsilon;
  53426. if (offsetY === 0)
  53427. offsetY = this._epsilon;
  53428. else if (offsetY === 1)
  53429. offsetY = 1 - this._epsilon;
  53430. this._vertexData[arrayOffset] = sprite.position.x;
  53431. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53432. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53433. this._vertexData[arrayOffset + 3] = sprite.angle;
  53434. this._vertexData[arrayOffset + 4] = sprite.width;
  53435. this._vertexData[arrayOffset + 5] = sprite.height;
  53436. this._vertexData[arrayOffset + 6] = offsetX;
  53437. this._vertexData[arrayOffset + 7] = offsetY;
  53438. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53439. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53440. var offset = (sprite.cellIndex / rowSize) >> 0;
  53441. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53442. this._vertexData[arrayOffset + 11] = offset;
  53443. // Color
  53444. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53445. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53446. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53447. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53448. };
  53449. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53450. var count = Math.min(this._capacity, this.sprites.length);
  53451. var min = BABYLON.Vector3.Zero();
  53452. var max = BABYLON.Vector3.Zero();
  53453. var distance = Number.MAX_VALUE;
  53454. var currentSprite = null;
  53455. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53456. var cameraView = camera.getViewMatrix();
  53457. for (var index = 0; index < count; index++) {
  53458. var sprite = this.sprites[index];
  53459. if (!sprite) {
  53460. continue;
  53461. }
  53462. if (predicate) {
  53463. if (!predicate(sprite)) {
  53464. continue;
  53465. }
  53466. }
  53467. else if (!sprite.isPickable) {
  53468. continue;
  53469. }
  53470. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53471. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53472. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53473. if (ray.intersectsBoxMinMax(min, max)) {
  53474. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53475. if (distance > currentDistance) {
  53476. distance = currentDistance;
  53477. currentSprite = sprite;
  53478. if (fastCheck) {
  53479. break;
  53480. }
  53481. }
  53482. }
  53483. }
  53484. if (currentSprite) {
  53485. var result = new BABYLON.PickingInfo();
  53486. result.hit = true;
  53487. result.pickedSprite = currentSprite;
  53488. result.distance = distance;
  53489. return result;
  53490. }
  53491. return null;
  53492. };
  53493. SpriteManager.prototype.render = function () {
  53494. // Check
  53495. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53496. return;
  53497. var engine = this._scene.getEngine();
  53498. var baseSize = this._spriteTexture.getBaseSize();
  53499. // Sprites
  53500. var deltaTime = engine.getDeltaTime();
  53501. var max = Math.min(this._capacity, this.sprites.length);
  53502. var rowSize = baseSize.width / this.cellWidth;
  53503. var offset = 0;
  53504. for (var index = 0; index < max; index++) {
  53505. var sprite = this.sprites[index];
  53506. if (!sprite || !sprite.isVisible) {
  53507. continue;
  53508. }
  53509. sprite._animate(deltaTime);
  53510. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53511. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53512. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53513. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53514. }
  53515. this._buffer.update(this._vertexData);
  53516. // Render
  53517. var effect = this._effectBase;
  53518. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53519. effect = this._effectFog;
  53520. }
  53521. engine.enableEffect(effect);
  53522. var viewMatrix = this._scene.getViewMatrix();
  53523. effect.setTexture("diffuseSampler", this._spriteTexture);
  53524. effect.setMatrix("view", viewMatrix);
  53525. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53526. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53527. // Fog
  53528. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53529. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53530. effect.setColor3("vFogColor", this._scene.fogColor);
  53531. }
  53532. // VBOs
  53533. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53534. // Draw order
  53535. engine.setDepthFunctionToLessOrEqual();
  53536. effect.setBool("alphaTest", true);
  53537. engine.setColorWrite(false);
  53538. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53539. engine.setColorWrite(true);
  53540. effect.setBool("alphaTest", false);
  53541. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53542. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53543. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53544. };
  53545. SpriteManager.prototype.dispose = function () {
  53546. if (this._buffer) {
  53547. this._buffer.dispose();
  53548. this._buffer = null;
  53549. }
  53550. if (this._indexBuffer) {
  53551. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53552. this._indexBuffer = null;
  53553. }
  53554. if (this._spriteTexture) {
  53555. this._spriteTexture.dispose();
  53556. this._spriteTexture = null;
  53557. }
  53558. // Remove from scene
  53559. var index = this._scene.spriteManagers.indexOf(this);
  53560. this._scene.spriteManagers.splice(index, 1);
  53561. // Callback
  53562. this.onDisposeObservable.notifyObservers(this);
  53563. this.onDisposeObservable.clear();
  53564. };
  53565. return SpriteManager;
  53566. }());
  53567. BABYLON.SpriteManager = SpriteManager;
  53568. })(BABYLON || (BABYLON = {}));
  53569. //# sourceMappingURL=babylon.spriteManager.js.map
  53570. var BABYLON;
  53571. (function (BABYLON) {
  53572. var Sprite = /** @class */ (function () {
  53573. function Sprite(name, manager) {
  53574. this.name = name;
  53575. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53576. this.width = 1.0;
  53577. this.height = 1.0;
  53578. this.angle = 0;
  53579. this.cellIndex = 0;
  53580. this.invertU = 0;
  53581. this.invertV = 0;
  53582. this.animations = new Array();
  53583. this.isPickable = false;
  53584. this._animationStarted = false;
  53585. this._loopAnimation = false;
  53586. this._fromIndex = 0;
  53587. this._toIndex = 0;
  53588. this._delay = 0;
  53589. this._direction = 1;
  53590. this._time = 0;
  53591. /**
  53592. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53593. */
  53594. this.isVisible = true;
  53595. this._manager = manager;
  53596. this._manager.sprites.push(this);
  53597. this.position = BABYLON.Vector3.Zero();
  53598. }
  53599. Object.defineProperty(Sprite.prototype, "size", {
  53600. get: function () {
  53601. return this.width;
  53602. },
  53603. set: function (value) {
  53604. this.width = value;
  53605. this.height = value;
  53606. },
  53607. enumerable: true,
  53608. configurable: true
  53609. });
  53610. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53611. this._fromIndex = from;
  53612. this._toIndex = to;
  53613. this._loopAnimation = loop;
  53614. this._delay = delay;
  53615. this._animationStarted = true;
  53616. this._direction = from < to ? 1 : -1;
  53617. this.cellIndex = from;
  53618. this._time = 0;
  53619. this._onAnimationEnd = onAnimationEnd;
  53620. };
  53621. Sprite.prototype.stopAnimation = function () {
  53622. this._animationStarted = false;
  53623. };
  53624. Sprite.prototype._animate = function (deltaTime) {
  53625. if (!this._animationStarted)
  53626. return;
  53627. this._time += deltaTime;
  53628. if (this._time > this._delay) {
  53629. this._time = this._time % this._delay;
  53630. this.cellIndex += this._direction;
  53631. if (this.cellIndex > this._toIndex) {
  53632. if (this._loopAnimation) {
  53633. this.cellIndex = this._fromIndex;
  53634. }
  53635. else {
  53636. this.cellIndex = this._toIndex;
  53637. this._animationStarted = false;
  53638. if (this._onAnimationEnd) {
  53639. this._onAnimationEnd();
  53640. }
  53641. if (this.disposeWhenFinishedAnimating) {
  53642. this.dispose();
  53643. }
  53644. }
  53645. }
  53646. }
  53647. };
  53648. Sprite.prototype.dispose = function () {
  53649. for (var i = 0; i < this._manager.sprites.length; i++) {
  53650. if (this._manager.sprites[i] == this) {
  53651. this._manager.sprites.splice(i, 1);
  53652. }
  53653. }
  53654. };
  53655. return Sprite;
  53656. }());
  53657. BABYLON.Sprite = Sprite;
  53658. })(BABYLON || (BABYLON = {}));
  53659. //# sourceMappingURL=babylon.sprite.js.map
  53660. var BABYLON;
  53661. (function (BABYLON) {
  53662. var IntersectionInfo = /** @class */ (function () {
  53663. function IntersectionInfo(bu, bv, distance) {
  53664. this.bu = bu;
  53665. this.bv = bv;
  53666. this.distance = distance;
  53667. this.faceId = 0;
  53668. this.subMeshId = 0;
  53669. }
  53670. return IntersectionInfo;
  53671. }());
  53672. BABYLON.IntersectionInfo = IntersectionInfo;
  53673. /**
  53674. * Information about the result of picking within a scene
  53675. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53676. */
  53677. var PickingInfo = /** @class */ (function () {
  53678. function PickingInfo() {
  53679. /**
  53680. * If the pick collided with an object
  53681. */
  53682. this.hit = false;
  53683. /**
  53684. * Distance away where the pick collided
  53685. */
  53686. this.distance = 0;
  53687. /**
  53688. * The location of pick collision
  53689. */
  53690. this.pickedPoint = null;
  53691. /**
  53692. * The mesh corrisponding the the pick collision
  53693. */
  53694. this.pickedMesh = null;
  53695. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53696. this.bu = 0;
  53697. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53698. this.bv = 0;
  53699. /** The id of the face on the mesh that was picked */
  53700. this.faceId = -1;
  53701. /** Id of the the submesh that was picked */
  53702. this.subMeshId = 0;
  53703. /** If a sprite was picked, this will be the sprite the pick collided with */
  53704. this.pickedSprite = null;
  53705. /**
  53706. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53707. */
  53708. this.originMesh = null;
  53709. /**
  53710. * The ray that was used to perform the picking.
  53711. */
  53712. this.ray = null;
  53713. }
  53714. /**
  53715. * Gets the normal corrispodning to the face the pick collided with
  53716. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53717. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53718. * @returns The normal corrispodning to the face the pick collided with
  53719. */
  53720. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53721. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53722. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53723. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53724. return null;
  53725. }
  53726. var indices = this.pickedMesh.getIndices();
  53727. if (!indices) {
  53728. return null;
  53729. }
  53730. var result;
  53731. if (useVerticesNormals) {
  53732. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53733. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53734. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53735. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53736. normal0 = normal0.scale(this.bu);
  53737. normal1 = normal1.scale(this.bv);
  53738. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53739. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53740. }
  53741. else {
  53742. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53743. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53744. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53745. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53746. var p1p2 = vertex1.subtract(vertex2);
  53747. var p3p2 = vertex3.subtract(vertex2);
  53748. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53749. }
  53750. if (useWorldCoordinates) {
  53751. var wm = this.pickedMesh.getWorldMatrix();
  53752. if (this.pickedMesh.nonUniformScaling) {
  53753. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53754. wm = BABYLON.Tmp.Matrix[0];
  53755. wm.setTranslationFromFloats(0, 0, 0);
  53756. wm.invert();
  53757. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53758. wm = BABYLON.Tmp.Matrix[1];
  53759. }
  53760. result = BABYLON.Vector3.TransformNormal(result, wm);
  53761. }
  53762. result.normalize();
  53763. return result;
  53764. };
  53765. /**
  53766. * Gets the texture coordinates of where the pick occured
  53767. * @returns the vector containing the coordnates of the texture
  53768. */
  53769. PickingInfo.prototype.getTextureCoordinates = function () {
  53770. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53771. return null;
  53772. }
  53773. var indices = this.pickedMesh.getIndices();
  53774. if (!indices) {
  53775. return null;
  53776. }
  53777. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53778. if (!uvs) {
  53779. return null;
  53780. }
  53781. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53782. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53783. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53784. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53785. uv1 = uv1.scale(this.bu);
  53786. uv2 = uv2.scale(this.bv);
  53787. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53788. };
  53789. return PickingInfo;
  53790. }());
  53791. BABYLON.PickingInfo = PickingInfo;
  53792. })(BABYLON || (BABYLON = {}));
  53793. //# sourceMappingURL=babylon.pickingInfo.js.map
  53794. var BABYLON;
  53795. (function (BABYLON) {
  53796. var Ray = /** @class */ (function () {
  53797. function Ray(origin, direction, length) {
  53798. if (length === void 0) { length = Number.MAX_VALUE; }
  53799. this.origin = origin;
  53800. this.direction = direction;
  53801. this.length = length;
  53802. }
  53803. // Methods
  53804. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53805. var d = 0.0;
  53806. var maxValue = Number.MAX_VALUE;
  53807. var inv;
  53808. var min;
  53809. var max;
  53810. var temp;
  53811. if (Math.abs(this.direction.x) < 0.0000001) {
  53812. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53813. return false;
  53814. }
  53815. }
  53816. else {
  53817. inv = 1.0 / this.direction.x;
  53818. min = (minimum.x - this.origin.x) * inv;
  53819. max = (maximum.x - this.origin.x) * inv;
  53820. if (max === -Infinity) {
  53821. max = Infinity;
  53822. }
  53823. if (min > max) {
  53824. temp = min;
  53825. min = max;
  53826. max = temp;
  53827. }
  53828. d = Math.max(min, d);
  53829. maxValue = Math.min(max, maxValue);
  53830. if (d > maxValue) {
  53831. return false;
  53832. }
  53833. }
  53834. if (Math.abs(this.direction.y) < 0.0000001) {
  53835. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53836. return false;
  53837. }
  53838. }
  53839. else {
  53840. inv = 1.0 / this.direction.y;
  53841. min = (minimum.y - this.origin.y) * inv;
  53842. max = (maximum.y - this.origin.y) * inv;
  53843. if (max === -Infinity) {
  53844. max = Infinity;
  53845. }
  53846. if (min > max) {
  53847. temp = min;
  53848. min = max;
  53849. max = temp;
  53850. }
  53851. d = Math.max(min, d);
  53852. maxValue = Math.min(max, maxValue);
  53853. if (d > maxValue) {
  53854. return false;
  53855. }
  53856. }
  53857. if (Math.abs(this.direction.z) < 0.0000001) {
  53858. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53859. return false;
  53860. }
  53861. }
  53862. else {
  53863. inv = 1.0 / this.direction.z;
  53864. min = (minimum.z - this.origin.z) * inv;
  53865. max = (maximum.z - this.origin.z) * inv;
  53866. if (max === -Infinity) {
  53867. max = Infinity;
  53868. }
  53869. if (min > max) {
  53870. temp = min;
  53871. min = max;
  53872. max = temp;
  53873. }
  53874. d = Math.max(min, d);
  53875. maxValue = Math.min(max, maxValue);
  53876. if (d > maxValue) {
  53877. return false;
  53878. }
  53879. }
  53880. return true;
  53881. };
  53882. Ray.prototype.intersectsBox = function (box) {
  53883. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53884. };
  53885. Ray.prototype.intersectsSphere = function (sphere) {
  53886. var x = sphere.center.x - this.origin.x;
  53887. var y = sphere.center.y - this.origin.y;
  53888. var z = sphere.center.z - this.origin.z;
  53889. var pyth = (x * x) + (y * y) + (z * z);
  53890. var rr = sphere.radius * sphere.radius;
  53891. if (pyth <= rr) {
  53892. return true;
  53893. }
  53894. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53895. if (dot < 0.0) {
  53896. return false;
  53897. }
  53898. var temp = pyth - (dot * dot);
  53899. return temp <= rr;
  53900. };
  53901. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53902. if (!this._edge1) {
  53903. this._edge1 = BABYLON.Vector3.Zero();
  53904. this._edge2 = BABYLON.Vector3.Zero();
  53905. this._pvec = BABYLON.Vector3.Zero();
  53906. this._tvec = BABYLON.Vector3.Zero();
  53907. this._qvec = BABYLON.Vector3.Zero();
  53908. }
  53909. vertex1.subtractToRef(vertex0, this._edge1);
  53910. vertex2.subtractToRef(vertex0, this._edge2);
  53911. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53912. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53913. if (det === 0) {
  53914. return null;
  53915. }
  53916. var invdet = 1 / det;
  53917. this.origin.subtractToRef(vertex0, this._tvec);
  53918. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53919. if (bu < 0 || bu > 1.0) {
  53920. return null;
  53921. }
  53922. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53923. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53924. if (bv < 0 || bu + bv > 1.0) {
  53925. return null;
  53926. }
  53927. //check if the distance is longer than the predefined length.
  53928. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53929. if (distance > this.length) {
  53930. return null;
  53931. }
  53932. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53933. };
  53934. Ray.prototype.intersectsPlane = function (plane) {
  53935. var distance;
  53936. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53937. if (Math.abs(result1) < 9.99999997475243E-07) {
  53938. return null;
  53939. }
  53940. else {
  53941. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53942. distance = (-plane.d - result2) / result1;
  53943. if (distance < 0.0) {
  53944. if (distance < -9.99999997475243E-07) {
  53945. return null;
  53946. }
  53947. else {
  53948. return 0;
  53949. }
  53950. }
  53951. return distance;
  53952. }
  53953. };
  53954. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53955. var tm = BABYLON.Tmp.Matrix[0];
  53956. mesh.getWorldMatrix().invertToRef(tm);
  53957. if (this._tmpRay) {
  53958. Ray.TransformToRef(this, tm, this._tmpRay);
  53959. }
  53960. else {
  53961. this._tmpRay = Ray.Transform(this, tm);
  53962. }
  53963. return mesh.intersects(this._tmpRay, fastCheck);
  53964. };
  53965. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53966. if (results) {
  53967. results.length = 0;
  53968. }
  53969. else {
  53970. results = [];
  53971. }
  53972. for (var i = 0; i < meshes.length; i++) {
  53973. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53974. if (pickInfo.hit) {
  53975. results.push(pickInfo);
  53976. }
  53977. }
  53978. results.sort(this._comparePickingInfo);
  53979. return results;
  53980. };
  53981. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53982. if (pickingInfoA.distance < pickingInfoB.distance) {
  53983. return -1;
  53984. }
  53985. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53986. return 1;
  53987. }
  53988. else {
  53989. return 0;
  53990. }
  53991. };
  53992. /**
  53993. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53994. * @param sega the first point of the segment to test the intersection against
  53995. * @param segb the second point of the segment to test the intersection against
  53996. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53997. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53998. */
  53999. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54000. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54001. var u = segb.subtract(sega);
  54002. var v = rsegb.subtract(this.origin);
  54003. var w = sega.subtract(this.origin);
  54004. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54005. var b = BABYLON.Vector3.Dot(u, v);
  54006. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54007. var d = BABYLON.Vector3.Dot(u, w);
  54008. var e = BABYLON.Vector3.Dot(v, w);
  54009. var D = a * c - b * b; // always >= 0
  54010. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54011. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54012. // compute the line parameters of the two closest points
  54013. if (D < Ray.smallnum) { // the lines are almost parallel
  54014. sN = 0.0; // force using point P0 on segment S1
  54015. sD = 1.0; // to prevent possible division by 0.0 later
  54016. tN = e;
  54017. tD = c;
  54018. }
  54019. else { // get the closest points on the infinite lines
  54020. sN = (b * e - c * d);
  54021. tN = (a * e - b * d);
  54022. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54023. sN = 0.0;
  54024. tN = e;
  54025. tD = c;
  54026. }
  54027. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54028. sN = sD;
  54029. tN = e + b;
  54030. tD = c;
  54031. }
  54032. }
  54033. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54034. tN = 0.0;
  54035. // recompute sc for this edge
  54036. if (-d < 0.0) {
  54037. sN = 0.0;
  54038. }
  54039. else if (-d > a)
  54040. sN = sD;
  54041. else {
  54042. sN = -d;
  54043. sD = a;
  54044. }
  54045. }
  54046. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54047. tN = tD;
  54048. // recompute sc for this edge
  54049. if ((-d + b) < 0.0) {
  54050. sN = 0;
  54051. }
  54052. else if ((-d + b) > a) {
  54053. sN = sD;
  54054. }
  54055. else {
  54056. sN = (-d + b);
  54057. sD = a;
  54058. }
  54059. }
  54060. // finally do the division to get sc and tc
  54061. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54062. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54063. // get the difference of the two closest points
  54064. var qtc = v.multiplyByFloats(tc, tc, tc);
  54065. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54066. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54067. if (isIntersected) {
  54068. return qtc.length();
  54069. }
  54070. return -1;
  54071. };
  54072. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54073. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54074. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54075. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54076. this.direction.normalize();
  54077. return this;
  54078. };
  54079. // Statics
  54080. Ray.Zero = function () {
  54081. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54082. };
  54083. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54084. var result = Ray.Zero();
  54085. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54086. };
  54087. /**
  54088. * 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
  54089. * transformed to the given world matrix.
  54090. * @param origin The origin point
  54091. * @param end The end point
  54092. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54093. */
  54094. Ray.CreateNewFromTo = function (origin, end, world) {
  54095. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54096. var direction = end.subtract(origin);
  54097. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54098. direction.normalize();
  54099. return Ray.Transform(new Ray(origin, direction, length), world);
  54100. };
  54101. Ray.Transform = function (ray, matrix) {
  54102. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54103. Ray.TransformToRef(ray, matrix, result);
  54104. return result;
  54105. };
  54106. Ray.TransformToRef = function (ray, matrix, result) {
  54107. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54108. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54109. result.length = ray.length;
  54110. var dir = result.direction;
  54111. var len = dir.length();
  54112. if (!(len === 0 || len === 1)) {
  54113. var num = 1.0 / len;
  54114. dir.x *= num;
  54115. dir.y *= num;
  54116. dir.z *= num;
  54117. result.length *= len;
  54118. }
  54119. };
  54120. Ray.smallnum = 0.00000001;
  54121. Ray.rayl = 10e8;
  54122. return Ray;
  54123. }());
  54124. BABYLON.Ray = Ray;
  54125. })(BABYLON || (BABYLON = {}));
  54126. //# sourceMappingURL=babylon.ray.js.map
  54127. var BABYLON;
  54128. (function (BABYLON) {
  54129. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54130. if (boxMin.x > sphereCenter.x + sphereRadius)
  54131. return false;
  54132. if (sphereCenter.x - sphereRadius > boxMax.x)
  54133. return false;
  54134. if (boxMin.y > sphereCenter.y + sphereRadius)
  54135. return false;
  54136. if (sphereCenter.y - sphereRadius > boxMax.y)
  54137. return false;
  54138. if (boxMin.z > sphereCenter.z + sphereRadius)
  54139. return false;
  54140. if (sphereCenter.z - sphereRadius > boxMax.z)
  54141. return false;
  54142. return true;
  54143. };
  54144. var getLowestRoot = (function () {
  54145. var result = { root: 0, found: false };
  54146. return function (a, b, c, maxR) {
  54147. result.root = 0;
  54148. result.found = false;
  54149. var determinant = b * b - 4.0 * a * c;
  54150. if (determinant < 0)
  54151. return result;
  54152. var sqrtD = Math.sqrt(determinant);
  54153. var r1 = (-b - sqrtD) / (2.0 * a);
  54154. var r2 = (-b + sqrtD) / (2.0 * a);
  54155. if (r1 > r2) {
  54156. var temp = r2;
  54157. r2 = r1;
  54158. r1 = temp;
  54159. }
  54160. if (r1 > 0 && r1 < maxR) {
  54161. result.root = r1;
  54162. result.found = true;
  54163. return result;
  54164. }
  54165. if (r2 > 0 && r2 < maxR) {
  54166. result.root = r2;
  54167. result.found = true;
  54168. return result;
  54169. }
  54170. return result;
  54171. };
  54172. })();
  54173. var Collider = /** @class */ (function () {
  54174. function Collider() {
  54175. this._collisionPoint = BABYLON.Vector3.Zero();
  54176. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54177. this._tempVector = BABYLON.Vector3.Zero();
  54178. this._tempVector2 = BABYLON.Vector3.Zero();
  54179. this._tempVector3 = BABYLON.Vector3.Zero();
  54180. this._tempVector4 = BABYLON.Vector3.Zero();
  54181. this._edge = BABYLON.Vector3.Zero();
  54182. this._baseToVertex = BABYLON.Vector3.Zero();
  54183. this._destinationPoint = BABYLON.Vector3.Zero();
  54184. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54185. this._displacementVector = BABYLON.Vector3.Zero();
  54186. this._radius = BABYLON.Vector3.One();
  54187. this._retry = 0;
  54188. this._basePointWorld = BABYLON.Vector3.Zero();
  54189. this._velocityWorld = BABYLON.Vector3.Zero();
  54190. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54191. this._collisionMask = -1;
  54192. }
  54193. Object.defineProperty(Collider.prototype, "collisionMask", {
  54194. get: function () {
  54195. return this._collisionMask;
  54196. },
  54197. set: function (mask) {
  54198. this._collisionMask = !isNaN(mask) ? mask : -1;
  54199. },
  54200. enumerable: true,
  54201. configurable: true
  54202. });
  54203. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54204. /**
  54205. * Gets the plane normal used to compute the sliding response (in local space)
  54206. */
  54207. get: function () {
  54208. return this._slidePlaneNormal;
  54209. },
  54210. enumerable: true,
  54211. configurable: true
  54212. });
  54213. // Methods
  54214. Collider.prototype._initialize = function (source, dir, e) {
  54215. this._velocity = dir;
  54216. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54217. this._basePoint = source;
  54218. source.multiplyToRef(this._radius, this._basePointWorld);
  54219. dir.multiplyToRef(this._radius, this._velocityWorld);
  54220. this._velocityWorldLength = this._velocityWorld.length();
  54221. this._epsilon = e;
  54222. this.collisionFound = false;
  54223. };
  54224. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54225. pa.subtractToRef(point, this._tempVector);
  54226. pb.subtractToRef(point, this._tempVector2);
  54227. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54228. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54229. if (d < 0)
  54230. return false;
  54231. pc.subtractToRef(point, this._tempVector3);
  54232. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54233. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54234. if (d < 0)
  54235. return false;
  54236. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54237. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54238. return d >= 0;
  54239. };
  54240. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54241. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54242. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54243. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54244. return false;
  54245. }
  54246. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54247. return false;
  54248. return true;
  54249. };
  54250. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54251. var t0;
  54252. var embeddedInPlane = false;
  54253. //defensive programming, actually not needed.
  54254. if (!trianglePlaneArray) {
  54255. trianglePlaneArray = [];
  54256. }
  54257. if (!trianglePlaneArray[faceIndex]) {
  54258. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54259. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54260. }
  54261. var trianglePlane = trianglePlaneArray[faceIndex];
  54262. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54263. return;
  54264. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54265. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54266. if (normalDotVelocity == 0) {
  54267. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54268. return;
  54269. embeddedInPlane = true;
  54270. t0 = 0;
  54271. }
  54272. else {
  54273. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54274. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54275. if (t0 > t1) {
  54276. var temp = t1;
  54277. t1 = t0;
  54278. t0 = temp;
  54279. }
  54280. if (t0 > 1.0 || t1 < 0.0)
  54281. return;
  54282. if (t0 < 0)
  54283. t0 = 0;
  54284. if (t0 > 1.0)
  54285. t0 = 1.0;
  54286. }
  54287. this._collisionPoint.copyFromFloats(0, 0, 0);
  54288. var found = false;
  54289. var t = 1.0;
  54290. if (!embeddedInPlane) {
  54291. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54292. this._velocity.scaleToRef(t0, this._tempVector);
  54293. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54294. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54295. found = true;
  54296. t = t0;
  54297. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54298. }
  54299. }
  54300. if (!found) {
  54301. var velocitySquaredLength = this._velocity.lengthSquared();
  54302. var a = velocitySquaredLength;
  54303. this._basePoint.subtractToRef(p1, this._tempVector);
  54304. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54305. var c = this._tempVector.lengthSquared() - 1.0;
  54306. var lowestRoot = getLowestRoot(a, b, c, t);
  54307. if (lowestRoot.found) {
  54308. t = lowestRoot.root;
  54309. found = true;
  54310. this._collisionPoint.copyFrom(p1);
  54311. }
  54312. this._basePoint.subtractToRef(p2, this._tempVector);
  54313. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54314. c = this._tempVector.lengthSquared() - 1.0;
  54315. lowestRoot = getLowestRoot(a, b, c, t);
  54316. if (lowestRoot.found) {
  54317. t = lowestRoot.root;
  54318. found = true;
  54319. this._collisionPoint.copyFrom(p2);
  54320. }
  54321. this._basePoint.subtractToRef(p3, this._tempVector);
  54322. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54323. c = this._tempVector.lengthSquared() - 1.0;
  54324. lowestRoot = getLowestRoot(a, b, c, t);
  54325. if (lowestRoot.found) {
  54326. t = lowestRoot.root;
  54327. found = true;
  54328. this._collisionPoint.copyFrom(p3);
  54329. }
  54330. p2.subtractToRef(p1, this._edge);
  54331. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54332. var edgeSquaredLength = this._edge.lengthSquared();
  54333. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54334. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54335. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54336. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54337. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54338. lowestRoot = getLowestRoot(a, b, c, t);
  54339. if (lowestRoot.found) {
  54340. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54341. if (f >= 0.0 && f <= 1.0) {
  54342. t = lowestRoot.root;
  54343. found = true;
  54344. this._edge.scaleInPlace(f);
  54345. p1.addToRef(this._edge, this._collisionPoint);
  54346. }
  54347. }
  54348. p3.subtractToRef(p2, this._edge);
  54349. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54350. edgeSquaredLength = this._edge.lengthSquared();
  54351. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54352. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54353. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54354. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54355. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54356. lowestRoot = getLowestRoot(a, b, c, t);
  54357. if (lowestRoot.found) {
  54358. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54359. if (f >= 0.0 && f <= 1.0) {
  54360. t = lowestRoot.root;
  54361. found = true;
  54362. this._edge.scaleInPlace(f);
  54363. p2.addToRef(this._edge, this._collisionPoint);
  54364. }
  54365. }
  54366. p1.subtractToRef(p3, this._edge);
  54367. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54368. edgeSquaredLength = this._edge.lengthSquared();
  54369. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54370. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54371. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54372. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54373. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54374. lowestRoot = getLowestRoot(a, b, c, t);
  54375. if (lowestRoot.found) {
  54376. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54377. if (f >= 0.0 && f <= 1.0) {
  54378. t = lowestRoot.root;
  54379. found = true;
  54380. this._edge.scaleInPlace(f);
  54381. p3.addToRef(this._edge, this._collisionPoint);
  54382. }
  54383. }
  54384. }
  54385. if (found) {
  54386. var distToCollision = t * this._velocity.length();
  54387. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54388. if (!this.intersectionPoint) {
  54389. this.intersectionPoint = this._collisionPoint.clone();
  54390. }
  54391. else {
  54392. this.intersectionPoint.copyFrom(this._collisionPoint);
  54393. }
  54394. this._nearestDistance = distToCollision;
  54395. this.collisionFound = true;
  54396. }
  54397. }
  54398. };
  54399. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54400. for (var i = indexStart; i < indexEnd; i += 3) {
  54401. var p1 = pts[indices[i] - decal];
  54402. var p2 = pts[indices[i + 1] - decal];
  54403. var p3 = pts[indices[i + 2] - decal];
  54404. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54405. }
  54406. };
  54407. Collider.prototype._getResponse = function (pos, vel) {
  54408. pos.addToRef(vel, this._destinationPoint);
  54409. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54410. this._basePoint.addToRef(vel, pos);
  54411. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54412. this._slidePlaneNormal.normalize();
  54413. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54414. pos.addInPlace(this._displacementVector);
  54415. this.intersectionPoint.addInPlace(this._displacementVector);
  54416. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54417. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54418. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54419. };
  54420. return Collider;
  54421. }());
  54422. BABYLON.Collider = Collider;
  54423. })(BABYLON || (BABYLON = {}));
  54424. //# sourceMappingURL=babylon.collider.js.map
  54425. var BABYLON;
  54426. (function (BABYLON) {
  54427. //WebWorker code will be inserted to this variable.
  54428. BABYLON.CollisionWorker = "";
  54429. /** Defines supported task for worker process */
  54430. var WorkerTaskType;
  54431. (function (WorkerTaskType) {
  54432. /** Initialization */
  54433. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54434. /** Update of geometry */
  54435. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54436. /** Evaluate collision */
  54437. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54438. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54439. /** Defines kind of replies returned by worker */
  54440. var WorkerReplyType;
  54441. (function (WorkerReplyType) {
  54442. /** Success */
  54443. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54444. /** Unkown error */
  54445. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54446. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54447. var CollisionCoordinatorWorker = /** @class */ (function () {
  54448. function CollisionCoordinatorWorker() {
  54449. var _this = this;
  54450. this._scaledPosition = BABYLON.Vector3.Zero();
  54451. this._scaledVelocity = BABYLON.Vector3.Zero();
  54452. this.onMeshUpdated = function (transformNode) {
  54453. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54454. };
  54455. this.onGeometryUpdated = function (geometry) {
  54456. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54457. };
  54458. this._afterRender = function () {
  54459. if (!_this._init)
  54460. return;
  54461. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54462. return;
  54463. }
  54464. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54465. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54466. if (_this._runningUpdated > 4) {
  54467. return;
  54468. }
  54469. ++_this._runningUpdated;
  54470. var payload = {
  54471. updatedMeshes: _this._addUpdateMeshesList,
  54472. updatedGeometries: _this._addUpdateGeometriesList,
  54473. removedGeometries: _this._toRemoveGeometryArray,
  54474. removedMeshes: _this._toRemoveMeshesArray
  54475. };
  54476. var message = {
  54477. payload: payload,
  54478. taskType: WorkerTaskType.UPDATE
  54479. };
  54480. var serializable = [];
  54481. for (var id in payload.updatedGeometries) {
  54482. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54483. //prepare transferables
  54484. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54485. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54486. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54487. }
  54488. }
  54489. _this._worker.postMessage(message, serializable);
  54490. _this._addUpdateMeshesList = {};
  54491. _this._addUpdateGeometriesList = {};
  54492. _this._toRemoveGeometryArray = [];
  54493. _this._toRemoveMeshesArray = [];
  54494. };
  54495. this._onMessageFromWorker = function (e) {
  54496. var returnData = e.data;
  54497. if (returnData.error != WorkerReplyType.SUCCESS) {
  54498. //TODO what errors can be returned from the worker?
  54499. BABYLON.Tools.Warn("error returned from worker!");
  54500. return;
  54501. }
  54502. switch (returnData.taskType) {
  54503. case WorkerTaskType.INIT:
  54504. _this._init = true;
  54505. //Update the worked with ALL of the scene's current state
  54506. _this._scene.meshes.forEach(function (mesh) {
  54507. _this.onMeshAdded(mesh);
  54508. });
  54509. _this._scene.getGeometries().forEach(function (geometry) {
  54510. _this.onGeometryAdded(geometry);
  54511. });
  54512. break;
  54513. case WorkerTaskType.UPDATE:
  54514. _this._runningUpdated--;
  54515. break;
  54516. case WorkerTaskType.COLLIDE:
  54517. var returnPayload = returnData.payload;
  54518. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54519. return;
  54520. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54521. if (callback) {
  54522. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54523. if (mesh) {
  54524. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54525. }
  54526. }
  54527. //cleanup
  54528. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54529. break;
  54530. }
  54531. };
  54532. this._collisionsCallbackArray = [];
  54533. this._init = false;
  54534. this._runningUpdated = 0;
  54535. this._addUpdateMeshesList = {};
  54536. this._addUpdateGeometriesList = {};
  54537. this._toRemoveGeometryArray = [];
  54538. this._toRemoveMeshesArray = [];
  54539. }
  54540. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54541. if (!this._init)
  54542. return;
  54543. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54544. return;
  54545. position.divideToRef(collider._radius, this._scaledPosition);
  54546. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54547. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54548. var payload = {
  54549. collider: {
  54550. position: this._scaledPosition.asArray(),
  54551. velocity: this._scaledVelocity.asArray(),
  54552. radius: collider._radius.asArray()
  54553. },
  54554. collisionId: collisionIndex,
  54555. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54556. maximumRetry: maximumRetry
  54557. };
  54558. var message = {
  54559. payload: payload,
  54560. taskType: WorkerTaskType.COLLIDE
  54561. };
  54562. this._worker.postMessage(message);
  54563. };
  54564. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54565. this._scene = scene;
  54566. this._scene.registerAfterRender(this._afterRender);
  54567. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54568. this._worker = new Worker(workerUrl);
  54569. this._worker.onmessage = this._onMessageFromWorker;
  54570. var message = {
  54571. payload: {},
  54572. taskType: WorkerTaskType.INIT
  54573. };
  54574. this._worker.postMessage(message);
  54575. };
  54576. CollisionCoordinatorWorker.prototype.destroy = function () {
  54577. this._scene.unregisterAfterRender(this._afterRender);
  54578. this._worker.terminate();
  54579. };
  54580. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54581. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54582. this.onMeshUpdated(mesh);
  54583. };
  54584. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54585. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54586. };
  54587. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54588. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54589. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54590. this.onGeometryUpdated(geometry);
  54591. };
  54592. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54593. this._toRemoveGeometryArray.push(geometry.id);
  54594. };
  54595. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54596. var submeshes = [];
  54597. if (mesh.subMeshes) {
  54598. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54599. var boundingInfo = sm.getBoundingInfo();
  54600. return {
  54601. position: idx,
  54602. verticesStart: sm.verticesStart,
  54603. verticesCount: sm.verticesCount,
  54604. indexStart: sm.indexStart,
  54605. indexCount: sm.indexCount,
  54606. hasMaterial: !!sm.getMaterial(),
  54607. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54608. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54609. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54610. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54611. };
  54612. });
  54613. }
  54614. var geometryId = null;
  54615. if (mesh instanceof BABYLON.Mesh) {
  54616. var geometry = mesh.geometry;
  54617. geometryId = geometry ? geometry.id : null;
  54618. }
  54619. else if (mesh instanceof BABYLON.InstancedMesh) {
  54620. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54621. geometryId = geometry ? geometry.id : null;
  54622. }
  54623. var boundingInfo = mesh.getBoundingInfo();
  54624. return {
  54625. uniqueId: mesh.uniqueId,
  54626. id: mesh.id,
  54627. name: mesh.name,
  54628. geometryId: geometryId,
  54629. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54630. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54631. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54632. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54633. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54634. subMeshes: submeshes,
  54635. checkCollisions: mesh.checkCollisions
  54636. };
  54637. };
  54638. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54639. return {
  54640. id: geometry.id,
  54641. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54642. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54643. indices: new Uint32Array(geometry.getIndices() || []),
  54644. };
  54645. };
  54646. return CollisionCoordinatorWorker;
  54647. }());
  54648. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54649. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54650. function CollisionCoordinatorLegacy() {
  54651. this._scaledPosition = BABYLON.Vector3.Zero();
  54652. this._scaledVelocity = BABYLON.Vector3.Zero();
  54653. this._finalPosition = BABYLON.Vector3.Zero();
  54654. }
  54655. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54656. position.divideToRef(collider._radius, this._scaledPosition);
  54657. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54658. collider.collidedMesh = null;
  54659. collider._retry = 0;
  54660. collider._initialVelocity = this._scaledVelocity;
  54661. collider._initialPosition = this._scaledPosition;
  54662. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54663. this._finalPosition.multiplyInPlace(collider._radius);
  54664. //run the callback
  54665. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54666. };
  54667. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54668. this._scene = scene;
  54669. };
  54670. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54671. //Legacy need no destruction method.
  54672. };
  54673. //No update in legacy mode
  54674. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54675. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54676. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54677. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54678. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54679. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54680. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54681. if (excludedMesh === void 0) { excludedMesh = null; }
  54682. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54683. if (collider._retry >= maximumRetry) {
  54684. finalPosition.copyFrom(position);
  54685. return;
  54686. }
  54687. // Check if this is a mesh else camera or -1
  54688. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54689. collider._initialize(position, velocity, closeDistance);
  54690. // Check all meshes
  54691. for (var index = 0; index < this._scene.meshes.length; index++) {
  54692. var mesh = this._scene.meshes[index];
  54693. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54694. mesh._checkCollision(collider);
  54695. }
  54696. }
  54697. if (!collider.collisionFound) {
  54698. position.addToRef(velocity, finalPosition);
  54699. return;
  54700. }
  54701. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54702. collider._getResponse(position, velocity);
  54703. }
  54704. if (velocity.length() <= closeDistance) {
  54705. finalPosition.copyFrom(position);
  54706. return;
  54707. }
  54708. collider._retry++;
  54709. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54710. };
  54711. return CollisionCoordinatorLegacy;
  54712. }());
  54713. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54714. })(BABYLON || (BABYLON = {}));
  54715. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54716. var BABYLON;
  54717. (function (BABYLON) {
  54718. /**
  54719. * A particle represents one of the element emitted by a particle system.
  54720. * This is mainly define by its coordinates, direction, velocity and age.
  54721. */
  54722. var Particle = /** @class */ (function () {
  54723. /**
  54724. * Creates a new instance Particle
  54725. * @param particleSystem the particle system the particle belongs to
  54726. */
  54727. function Particle(
  54728. /**
  54729. * particleSystem the particle system the particle belongs to.
  54730. */
  54731. particleSystem) {
  54732. this.particleSystem = particleSystem;
  54733. /**
  54734. * The world position of the particle in the scene.
  54735. */
  54736. this.position = BABYLON.Vector3.Zero();
  54737. /**
  54738. * The world direction of the particle in the scene.
  54739. */
  54740. this.direction = BABYLON.Vector3.Zero();
  54741. /**
  54742. * The color of the particle.
  54743. */
  54744. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54745. /**
  54746. * The color change of the particle per step.
  54747. */
  54748. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54749. /**
  54750. * Defines how long will the life of the particle be.
  54751. */
  54752. this.lifeTime = 1.0;
  54753. /**
  54754. * The current age of the particle.
  54755. */
  54756. this.age = 0;
  54757. /**
  54758. * The current size of the particle.
  54759. */
  54760. this.size = 0;
  54761. /**
  54762. * The current scale of the particle.
  54763. */
  54764. this.scale = new BABYLON.Vector2(1, 1);
  54765. /**
  54766. * The current angle of the particle.
  54767. */
  54768. this.angle = 0;
  54769. /**
  54770. * Defines how fast is the angle changing.
  54771. */
  54772. this.angularSpeed = 0;
  54773. /**
  54774. * Defines the cell index used by the particle to be rendered from a sprite.
  54775. */
  54776. this.cellIndex = 0;
  54777. /** @hidden */
  54778. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54779. /** @hidden */
  54780. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54781. /** @hidden */
  54782. this._currentSize1 = 0;
  54783. /** @hidden */
  54784. this._currentSize2 = 0;
  54785. /** @hidden */
  54786. this._currentAngularSpeed1 = 0;
  54787. /** @hidden */
  54788. this._currentAngularSpeed2 = 0;
  54789. /** @hidden */
  54790. this._currentVelocity1 = 0;
  54791. /** @hidden */
  54792. this._currentVelocity2 = 0;
  54793. if (!this.particleSystem.isAnimationSheetEnabled) {
  54794. return;
  54795. }
  54796. this.updateCellInfoFromSystem();
  54797. }
  54798. Particle.prototype.updateCellInfoFromSystem = function () {
  54799. this.cellIndex = this.particleSystem.startSpriteCellID;
  54800. };
  54801. /**
  54802. * Defines how the sprite cell index is updated for the particle
  54803. */
  54804. Particle.prototype.updateCellIndex = function () {
  54805. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54806. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54807. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54808. };
  54809. /**
  54810. * Copy the properties of particle to another one.
  54811. * @param other the particle to copy the information to.
  54812. */
  54813. Particle.prototype.copyTo = function (other) {
  54814. other.position.copyFrom(this.position);
  54815. if (this._initialDirection) {
  54816. if (other._initialDirection) {
  54817. other._initialDirection.copyFrom(this._initialDirection);
  54818. }
  54819. else {
  54820. other._initialDirection = this._initialDirection.clone();
  54821. }
  54822. }
  54823. else {
  54824. other._initialDirection = null;
  54825. }
  54826. other.direction.copyFrom(this.direction);
  54827. other.color.copyFrom(this.color);
  54828. other.colorStep.copyFrom(this.colorStep);
  54829. other.lifeTime = this.lifeTime;
  54830. other.age = this.age;
  54831. other.size = this.size;
  54832. other.scale.copyFrom(this.scale);
  54833. other.angle = this.angle;
  54834. other.angularSpeed = this.angularSpeed;
  54835. other.particleSystem = this.particleSystem;
  54836. other.cellIndex = this.cellIndex;
  54837. if (this._currentColorGradient) {
  54838. other._currentColorGradient = this._currentColorGradient;
  54839. other._currentColor1.copyFrom(this._currentColor1);
  54840. other._currentColor2.copyFrom(this._currentColor2);
  54841. }
  54842. if (this._currentSizeGradient) {
  54843. other._currentSizeGradient = this._currentSizeGradient;
  54844. other._currentSize1 = this._currentSize1;
  54845. other._currentSize2 = this._currentSize2;
  54846. }
  54847. if (this._currentAngularSpeedGradient) {
  54848. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54849. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54850. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54851. }
  54852. if (this._currentVelocityGradient) {
  54853. other._currentVelocityGradient = this._currentVelocityGradient;
  54854. other._currentVelocity1 = this._currentVelocity1;
  54855. other._currentVelocity2 = this._currentVelocity2;
  54856. }
  54857. if (this.particleSystem.isAnimationSheetEnabled) {
  54858. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54859. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54860. }
  54861. };
  54862. return Particle;
  54863. }());
  54864. BABYLON.Particle = Particle;
  54865. })(BABYLON || (BABYLON = {}));
  54866. //# sourceMappingURL=babylon.particle.js.map
  54867. var BABYLON;
  54868. (function (BABYLON) {
  54869. /**
  54870. * This represents a particle system in Babylon.
  54871. * 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.
  54872. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54873. * @example https://doc.babylonjs.com/babylon101/particles
  54874. */
  54875. var ParticleSystem = /** @class */ (function () {
  54876. /**
  54877. * Instantiates a particle system.
  54878. * 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.
  54879. * @param name The name of the particle system
  54880. * @param capacity The max number of particles alive at the same time
  54881. * @param scene The scene the particle system belongs to
  54882. * @param customEffect a custom effect used to change the way particles are rendered by default
  54883. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54884. * @param epsilon Offset used to render the particles
  54885. */
  54886. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54887. if (customEffect === void 0) { customEffect = null; }
  54888. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54889. if (epsilon === void 0) { epsilon = 0.01; }
  54890. var _this = this;
  54891. /**
  54892. * List of animations used by the particle system.
  54893. */
  54894. this.animations = [];
  54895. /**
  54896. * The rendering group used by the Particle system to chose when to render.
  54897. */
  54898. this.renderingGroupId = 0;
  54899. /**
  54900. * The emitter represents the Mesh or position we are attaching the particle system to.
  54901. */
  54902. this.emitter = null;
  54903. /**
  54904. * The maximum number of particles to emit per frame
  54905. */
  54906. this.emitRate = 10;
  54907. /**
  54908. * If you want to launch only a few particles at once, that can be done, as well.
  54909. */
  54910. this.manualEmitCount = -1;
  54911. /**
  54912. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54913. */
  54914. this.updateSpeed = 0.01;
  54915. /**
  54916. * The amount of time the particle system is running (depends of the overall update speed).
  54917. */
  54918. this.targetStopDuration = 0;
  54919. /**
  54920. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54921. */
  54922. this.disposeOnStop = false;
  54923. /**
  54924. * Minimum power of emitting particles.
  54925. */
  54926. this.minEmitPower = 1;
  54927. /**
  54928. * Maximum power of emitting particles.
  54929. */
  54930. this.maxEmitPower = 1;
  54931. /**
  54932. * Minimum life time of emitting particles.
  54933. */
  54934. this.minLifeTime = 1;
  54935. /**
  54936. * Maximum life time of emitting particles.
  54937. */
  54938. this.maxLifeTime = 1;
  54939. /**
  54940. * Minimum Size of emitting particles.
  54941. */
  54942. this.minSize = 1;
  54943. /**
  54944. * Maximum Size of emitting particles.
  54945. */
  54946. this.maxSize = 1;
  54947. /**
  54948. * Minimum scale of emitting particles on X axis.
  54949. */
  54950. this.minScaleX = 1;
  54951. /**
  54952. * Maximum scale of emitting particles on X axis.
  54953. */
  54954. this.maxScaleX = 1;
  54955. /**
  54956. * Minimum scale of emitting particles on Y axis.
  54957. */
  54958. this.minScaleY = 1;
  54959. /**
  54960. * Maximum scale of emitting particles on Y axis.
  54961. */
  54962. this.maxScaleY = 1;
  54963. /**
  54964. * Gets or sets the minimal initial rotation in radians.
  54965. */
  54966. this.minInitialRotation = 0;
  54967. /**
  54968. * Gets or sets the maximal initial rotation in radians.
  54969. */
  54970. this.maxInitialRotation = 0;
  54971. /**
  54972. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54973. */
  54974. this.minAngularSpeed = 0;
  54975. /**
  54976. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54977. */
  54978. this.maxAngularSpeed = 0;
  54979. /**
  54980. * The layer mask we are rendering the particles through.
  54981. */
  54982. this.layerMask = 0x0FFFFFFF;
  54983. /**
  54984. * This can help using your own shader to render the particle system.
  54985. * The according effect will be created
  54986. */
  54987. this.customShader = null;
  54988. /**
  54989. * By default particle system starts as soon as they are created. This prevents the
  54990. * automatic start to happen and let you decide when to start emitting particles.
  54991. */
  54992. this.preventAutoStart = false;
  54993. /**
  54994. * Callback triggered when the particle animation is ending.
  54995. */
  54996. this.onAnimationEnd = null;
  54997. /**
  54998. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54999. */
  55000. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55001. /**
  55002. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55003. * to override the particles.
  55004. */
  55005. this.forceDepthWrite = false;
  55006. /**
  55007. * You can use gravity if you want to give an orientation to your particles.
  55008. */
  55009. this.gravity = BABYLON.Vector3.Zero();
  55010. this._colorGradients = null;
  55011. this._sizeGradients = null;
  55012. this._lifeTimeGradients = null;
  55013. this._angularSpeedGradients = null;
  55014. this._velocityGradients = null;
  55015. /**
  55016. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55017. */
  55018. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55019. /**
  55020. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55021. */
  55022. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55023. /**
  55024. * Color the particle will have at the end of its lifetime
  55025. */
  55026. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55027. /**
  55028. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55029. */
  55030. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55031. /**
  55032. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55033. */
  55034. this.spriteCellChangeSpeed = 1;
  55035. /**
  55036. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55037. */
  55038. this.startSpriteCellID = 0;
  55039. /**
  55040. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55041. */
  55042. this.endSpriteCellID = 0;
  55043. /**
  55044. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55045. */
  55046. this.spriteCellWidth = 0;
  55047. /**
  55048. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55049. */
  55050. this.spriteCellHeight = 0;
  55051. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55052. this.preWarmCycles = 0;
  55053. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55054. this.preWarmStepOffset = 1;
  55055. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55056. this.translationPivot = new BABYLON.Vector2(0, 0);
  55057. /**
  55058. * An event triggered when the system is disposed
  55059. */
  55060. this.onDisposeObservable = new BABYLON.Observable();
  55061. /**
  55062. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55063. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55064. */
  55065. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55066. this._particles = new Array();
  55067. this._stockParticles = new Array();
  55068. this._newPartsExcess = 0;
  55069. this._vertexBuffers = {};
  55070. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55071. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55072. this._scaledDirection = BABYLON.Vector3.Zero();
  55073. this._scaledGravity = BABYLON.Vector3.Zero();
  55074. this._currentRenderId = -1;
  55075. this._useInstancing = false;
  55076. this._started = false;
  55077. this._stopped = false;
  55078. this._actualFrame = 0;
  55079. this._isBillboardBased = true;
  55080. // start of sub system methods
  55081. /**
  55082. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55083. * Its lifetime will start back at 0.
  55084. */
  55085. this.recycleParticle = function (particle) {
  55086. var lastParticle = _this._particles.pop();
  55087. if (lastParticle !== particle) {
  55088. lastParticle.copyTo(particle);
  55089. }
  55090. _this._stockParticles.push(lastParticle);
  55091. };
  55092. this._createParticle = function () {
  55093. var particle;
  55094. if (_this._stockParticles.length !== 0) {
  55095. particle = _this._stockParticles.pop();
  55096. particle.age = 0;
  55097. particle._currentColorGradient = null;
  55098. particle.cellIndex = _this.startSpriteCellID;
  55099. }
  55100. else {
  55101. particle = new BABYLON.Particle(_this);
  55102. }
  55103. return particle;
  55104. };
  55105. this._emitFromParticle = function (particle) {
  55106. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55107. return;
  55108. }
  55109. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55110. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55111. subSystem._rootParticleSystem = _this;
  55112. _this.activeSubSystems.push(subSystem);
  55113. subSystem.start();
  55114. };
  55115. this.id = name;
  55116. this.name = name;
  55117. this._capacity = capacity;
  55118. this._epsilon = epsilon;
  55119. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55120. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55121. this._customEffect = customEffect;
  55122. scene.particleSystems.push(this);
  55123. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55124. this._createIndexBuffer();
  55125. this._createVertexBuffers();
  55126. // Default emitter type
  55127. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55128. this.updateFunction = function (particles) {
  55129. var _loop_1 = function () {
  55130. particle = particles[index];
  55131. particle.age += _this._scaledUpdateSpeed;
  55132. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55133. _this._emitFromParticle(particle);
  55134. _this.recycleParticle(particle);
  55135. index--;
  55136. return "continue";
  55137. }
  55138. else {
  55139. var ratio = particle.age / particle.lifeTime;
  55140. // Color
  55141. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55142. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55143. if (currentGradient !== particle._currentColorGradient) {
  55144. particle._currentColor1.copyFrom(particle._currentColor2);
  55145. nextGradient.getColorToRef(particle._currentColor2);
  55146. particle._currentColorGradient = currentGradient;
  55147. }
  55148. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55149. });
  55150. }
  55151. else {
  55152. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55153. particle.color.addInPlace(_this._scaledColorStep);
  55154. if (particle.color.a < 0) {
  55155. particle.color.a = 0;
  55156. }
  55157. }
  55158. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55159. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55160. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55161. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55162. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55163. particle._currentAngularSpeedGradient = currentGradient;
  55164. }
  55165. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55166. });
  55167. }
  55168. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55169. var directionScale_1 = _this._scaledUpdateSpeed;
  55170. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55171. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55172. if (currentGradient !== particle._currentVelocityGradient) {
  55173. particle._currentVelocity1 = particle._currentVelocity2;
  55174. particle._currentVelocity2 = nextGradient.getFactor();
  55175. particle._currentVelocityGradient = currentGradient;
  55176. }
  55177. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55178. });
  55179. }
  55180. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55181. particle.position.addInPlace(_this._scaledDirection);
  55182. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55183. particle.direction.addInPlace(_this._scaledGravity);
  55184. // Size
  55185. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55186. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55187. if (currentGradient !== particle._currentSizeGradient) {
  55188. particle._currentSize1 = particle._currentSize2;
  55189. particle._currentSize2 = nextGradient.getFactor();
  55190. particle._currentSizeGradient = currentGradient;
  55191. }
  55192. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55193. });
  55194. }
  55195. if (_this._isAnimationSheetEnabled) {
  55196. particle.updateCellIndex();
  55197. }
  55198. }
  55199. };
  55200. var particle;
  55201. for (var index = 0; index < particles.length; index++) {
  55202. _loop_1();
  55203. }
  55204. };
  55205. }
  55206. /**
  55207. * Gets the current list of color gradients.
  55208. * You must use addColorGradient and removeColorGradient to udpate this list
  55209. * @returns the list of color gradients
  55210. */
  55211. ParticleSystem.prototype.getColorGradients = function () {
  55212. return this._colorGradients;
  55213. };
  55214. /**
  55215. * Gets the current list of size gradients.
  55216. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55217. * @returns the list of size gradients
  55218. */
  55219. ParticleSystem.prototype.getSizeGradients = function () {
  55220. return this._sizeGradients;
  55221. };
  55222. /**
  55223. * Gets the current list of life time gradients.
  55224. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55225. * @returns the list of life time gradients
  55226. */
  55227. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55228. return this._lifeTimeGradients;
  55229. };
  55230. /**
  55231. * Gets the current list of angular speed gradients.
  55232. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55233. * @returns the list of angular speed gradients
  55234. */
  55235. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55236. return this._angularSpeedGradients;
  55237. };
  55238. /**
  55239. * Gets the current list of velocity gradients.
  55240. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55241. * @returns the list of velocity gradients
  55242. */
  55243. ParticleSystem.prototype.getVelocityGradients = function () {
  55244. return this._velocityGradients;
  55245. };
  55246. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55247. /**
  55248. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55249. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55250. */
  55251. get: function () {
  55252. if (this.particleEmitterType.direction1) {
  55253. return this.particleEmitterType.direction1;
  55254. }
  55255. return BABYLON.Vector3.Zero();
  55256. },
  55257. set: function (value) {
  55258. if (this.particleEmitterType.direction1) {
  55259. this.particleEmitterType.direction1 = value;
  55260. }
  55261. },
  55262. enumerable: true,
  55263. configurable: true
  55264. });
  55265. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55266. /**
  55267. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55268. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55269. */
  55270. get: function () {
  55271. if (this.particleEmitterType.direction2) {
  55272. return this.particleEmitterType.direction2;
  55273. }
  55274. return BABYLON.Vector3.Zero();
  55275. },
  55276. set: function (value) {
  55277. if (this.particleEmitterType.direction2) {
  55278. this.particleEmitterType.direction2 = value;
  55279. }
  55280. },
  55281. enumerable: true,
  55282. configurable: true
  55283. });
  55284. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55285. /**
  55286. * 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.
  55287. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55288. */
  55289. get: function () {
  55290. if (this.particleEmitterType.minEmitBox) {
  55291. return this.particleEmitterType.minEmitBox;
  55292. }
  55293. return BABYLON.Vector3.Zero();
  55294. },
  55295. set: function (value) {
  55296. if (this.particleEmitterType.minEmitBox) {
  55297. this.particleEmitterType.minEmitBox = value;
  55298. }
  55299. },
  55300. enumerable: true,
  55301. configurable: true
  55302. });
  55303. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55304. /**
  55305. * 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.
  55306. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55307. */
  55308. get: function () {
  55309. if (this.particleEmitterType.maxEmitBox) {
  55310. return this.particleEmitterType.maxEmitBox;
  55311. }
  55312. return BABYLON.Vector3.Zero();
  55313. },
  55314. set: function (value) {
  55315. if (this.particleEmitterType.maxEmitBox) {
  55316. this.particleEmitterType.maxEmitBox = value;
  55317. }
  55318. },
  55319. enumerable: true,
  55320. configurable: true
  55321. });
  55322. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55323. /**
  55324. * Sets a callback that will be triggered when the system is disposed
  55325. */
  55326. set: function (callback) {
  55327. if (this._onDisposeObserver) {
  55328. this.onDisposeObservable.remove(this._onDisposeObserver);
  55329. }
  55330. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55331. },
  55332. enumerable: true,
  55333. configurable: true
  55334. });
  55335. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55336. /**
  55337. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55338. */
  55339. get: function () {
  55340. return this._isAnimationSheetEnabled;
  55341. },
  55342. enumerable: true,
  55343. configurable: true
  55344. });
  55345. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55346. /**
  55347. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55348. */
  55349. get: function () {
  55350. return this._isBillboardBased;
  55351. },
  55352. set: function (value) {
  55353. if (this._isBillboardBased === value) {
  55354. return;
  55355. }
  55356. this._isBillboardBased = value;
  55357. this._resetEffect();
  55358. },
  55359. enumerable: true,
  55360. configurable: true
  55361. });
  55362. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55363. //end of Sub-emitter
  55364. /**
  55365. * Gets the current list of active particles
  55366. */
  55367. get: function () {
  55368. return this._particles;
  55369. },
  55370. enumerable: true,
  55371. configurable: true
  55372. });
  55373. /**
  55374. * Returns the string "ParticleSystem"
  55375. * @returns a string containing the class name
  55376. */
  55377. ParticleSystem.prototype.getClassName = function () {
  55378. return "ParticleSystem";
  55379. };
  55380. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55381. var newGradient = new BABYLON.FactorGradient();
  55382. newGradient.gradient = gradient;
  55383. newGradient.factor1 = factor;
  55384. newGradient.factor2 = factor2;
  55385. factorGradients.push(newGradient);
  55386. factorGradients.sort(function (a, b) {
  55387. if (a.gradient < b.gradient) {
  55388. return -1;
  55389. }
  55390. else if (a.gradient > b.gradient) {
  55391. return 1;
  55392. }
  55393. return 0;
  55394. });
  55395. };
  55396. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55397. if (!factorGradients) {
  55398. return;
  55399. }
  55400. var index = 0;
  55401. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55402. var factorGradient = factorGradients_1[_i];
  55403. if (factorGradient.gradient === gradient) {
  55404. factorGradients.splice(index, 1);
  55405. break;
  55406. }
  55407. index++;
  55408. }
  55409. };
  55410. /**
  55411. * Adds a new life time gradient
  55412. * @param gradient defines the gradient to use (between 0 and 1)
  55413. * @param factor defines the life time factor to affect to the specified gradient
  55414. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55415. * @returns the current particle system
  55416. */
  55417. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55418. if (!this._lifeTimeGradients) {
  55419. this._lifeTimeGradients = [];
  55420. }
  55421. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55422. return this;
  55423. };
  55424. /**
  55425. * Remove a specific life time gradient
  55426. * @param gradient defines the gradient to remove
  55427. * @returns the current particle system
  55428. */
  55429. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55430. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55431. return this;
  55432. };
  55433. /**
  55434. * Adds a new size gradient
  55435. * @param gradient defines the gradient to use (between 0 and 1)
  55436. * @param factor defines the size factor to affect to the specified gradient
  55437. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55438. * @returns the current particle system
  55439. */
  55440. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55441. if (!this._sizeGradients) {
  55442. this._sizeGradients = [];
  55443. }
  55444. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55445. return this;
  55446. };
  55447. /**
  55448. * Remove a specific size gradient
  55449. * @param gradient defines the gradient to remove
  55450. * @returns the current particle system
  55451. */
  55452. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55453. this._removeFactorGradient(this._sizeGradients, gradient);
  55454. return this;
  55455. };
  55456. /**
  55457. * Adds a new angular speed gradient
  55458. * @param gradient defines the gradient to use (between 0 and 1)
  55459. * @param factor defines the size factor to affect to the specified gradient
  55460. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55461. * @returns the current particle system
  55462. */
  55463. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55464. if (!this._angularSpeedGradients) {
  55465. this._angularSpeedGradients = [];
  55466. }
  55467. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55468. return this;
  55469. };
  55470. /**
  55471. * Remove a specific angular speed gradient
  55472. * @param gradient defines the gradient to remove
  55473. * @returns the current particle system
  55474. */
  55475. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55476. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55477. return this;
  55478. };
  55479. /**
  55480. * Adds a new velocity gradient
  55481. * @param gradient defines the gradient to use (between 0 and 1)
  55482. * @param factor defines the size factor to affect to the specified gradient
  55483. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55484. * @returns the current particle system
  55485. */
  55486. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55487. if (!this._velocityGradients) {
  55488. this._velocityGradients = [];
  55489. }
  55490. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55491. return this;
  55492. };
  55493. /**
  55494. * Remove a specific velocity gradient
  55495. * @param gradient defines the gradient to remove
  55496. * @returns the current particle system
  55497. */
  55498. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55499. this._removeFactorGradient(this._velocityGradients, gradient);
  55500. return this;
  55501. };
  55502. /**
  55503. * Adds a new color gradient
  55504. * @param gradient defines the gradient to use (between 0 and 1)
  55505. * @param color defines the color to affect to the specified gradient
  55506. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55507. */
  55508. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55509. if (!this._colorGradients) {
  55510. this._colorGradients = [];
  55511. }
  55512. var colorGradient = new BABYLON.ColorGradient();
  55513. colorGradient.gradient = gradient;
  55514. colorGradient.color1 = color;
  55515. colorGradient.color2 = color2;
  55516. this._colorGradients.push(colorGradient);
  55517. this._colorGradients.sort(function (a, b) {
  55518. if (a.gradient < b.gradient) {
  55519. return -1;
  55520. }
  55521. else if (a.gradient > b.gradient) {
  55522. return 1;
  55523. }
  55524. return 0;
  55525. });
  55526. return this;
  55527. };
  55528. /**
  55529. * Remove a specific color gradient
  55530. * @param gradient defines the gradient to remove
  55531. */
  55532. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55533. if (!this._colorGradients) {
  55534. return this;
  55535. }
  55536. var index = 0;
  55537. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55538. var colorGradient = _a[_i];
  55539. if (colorGradient.gradient === gradient) {
  55540. this._colorGradients.splice(index, 1);
  55541. break;
  55542. }
  55543. index++;
  55544. }
  55545. return this;
  55546. };
  55547. ParticleSystem.prototype._resetEffect = function () {
  55548. if (this._vertexBuffer) {
  55549. this._vertexBuffer.dispose();
  55550. this._vertexBuffer = null;
  55551. }
  55552. if (this._spriteBuffer) {
  55553. this._spriteBuffer.dispose();
  55554. this._spriteBuffer = null;
  55555. }
  55556. this._createVertexBuffers();
  55557. };
  55558. ParticleSystem.prototype._createVertexBuffers = function () {
  55559. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55560. if (this._isAnimationSheetEnabled) {
  55561. this._vertexBufferSize += 1;
  55562. }
  55563. if (!this._isBillboardBased) {
  55564. this._vertexBufferSize += 3;
  55565. }
  55566. var engine = this._scene.getEngine();
  55567. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55568. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55569. var dataOffset = 0;
  55570. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55571. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55572. dataOffset += 3;
  55573. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55574. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55575. dataOffset += 4;
  55576. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55577. this._vertexBuffers["angle"] = options;
  55578. dataOffset += 1;
  55579. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55580. this._vertexBuffers["size"] = size;
  55581. dataOffset += 2;
  55582. if (this._isAnimationSheetEnabled) {
  55583. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55584. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55585. dataOffset += 1;
  55586. }
  55587. if (!this._isBillboardBased) {
  55588. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55589. this._vertexBuffers["direction"] = directionBuffer;
  55590. dataOffset += 3;
  55591. }
  55592. var offsets;
  55593. if (this._useInstancing) {
  55594. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55595. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55596. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55597. }
  55598. else {
  55599. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55600. dataOffset += 2;
  55601. }
  55602. this._vertexBuffers["offset"] = offsets;
  55603. };
  55604. ParticleSystem.prototype._createIndexBuffer = function () {
  55605. if (this._useInstancing) {
  55606. return;
  55607. }
  55608. var indices = [];
  55609. var index = 0;
  55610. for (var count = 0; count < this._capacity; count++) {
  55611. indices.push(index);
  55612. indices.push(index + 1);
  55613. indices.push(index + 2);
  55614. indices.push(index);
  55615. indices.push(index + 2);
  55616. indices.push(index + 3);
  55617. index += 4;
  55618. }
  55619. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55620. };
  55621. /**
  55622. * Gets the maximum number of particles active at the same time.
  55623. * @returns The max number of active particles.
  55624. */
  55625. ParticleSystem.prototype.getCapacity = function () {
  55626. return this._capacity;
  55627. };
  55628. /**
  55629. * Gets Wether there are still active particles in the system.
  55630. * @returns True if it is alive, otherwise false.
  55631. */
  55632. ParticleSystem.prototype.isAlive = function () {
  55633. return this._alive;
  55634. };
  55635. /**
  55636. * Gets Wether the system has been started.
  55637. * @returns True if it has been started, otherwise false.
  55638. */
  55639. ParticleSystem.prototype.isStarted = function () {
  55640. return this._started;
  55641. };
  55642. /**
  55643. * Starts the particle system and begins to emit.
  55644. */
  55645. ParticleSystem.prototype.start = function () {
  55646. this._started = true;
  55647. this._stopped = false;
  55648. this._actualFrame = 0;
  55649. if (this.subEmitters && this.subEmitters.length != 0) {
  55650. this.activeSubSystems = new Array();
  55651. }
  55652. if (this.preWarmCycles) {
  55653. for (var index = 0; index < this.preWarmCycles; index++) {
  55654. this.animate(true);
  55655. }
  55656. }
  55657. };
  55658. /**
  55659. * Stops the particle system.
  55660. * @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.
  55661. */
  55662. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55663. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55664. this._stopped = true;
  55665. if (stopSubEmitters) {
  55666. this._stopSubEmitters();
  55667. }
  55668. };
  55669. // animation sheet
  55670. /**
  55671. * Remove all active particles
  55672. */
  55673. ParticleSystem.prototype.reset = function () {
  55674. this._stockParticles = [];
  55675. this._particles = [];
  55676. };
  55677. /**
  55678. * @hidden (for internal use only)
  55679. */
  55680. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55681. var offset = index * this._vertexBufferSize;
  55682. this._vertexData[offset++] = particle.position.x;
  55683. this._vertexData[offset++] = particle.position.y;
  55684. this._vertexData[offset++] = particle.position.z;
  55685. this._vertexData[offset++] = particle.color.r;
  55686. this._vertexData[offset++] = particle.color.g;
  55687. this._vertexData[offset++] = particle.color.b;
  55688. this._vertexData[offset++] = particle.color.a;
  55689. this._vertexData[offset++] = particle.angle;
  55690. this._vertexData[offset++] = particle.scale.x * particle.size;
  55691. this._vertexData[offset++] = particle.scale.y * particle.size;
  55692. if (this._isAnimationSheetEnabled) {
  55693. this._vertexData[offset++] = particle.cellIndex;
  55694. }
  55695. if (!this._isBillboardBased) {
  55696. if (particle._initialDirection) {
  55697. this._vertexData[offset++] = particle._initialDirection.x;
  55698. this._vertexData[offset++] = particle._initialDirection.y;
  55699. this._vertexData[offset++] = particle._initialDirection.z;
  55700. }
  55701. else {
  55702. this._vertexData[offset++] = particle.direction.x;
  55703. this._vertexData[offset++] = particle.direction.y;
  55704. this._vertexData[offset++] = particle.direction.z;
  55705. }
  55706. }
  55707. if (!this._useInstancing) {
  55708. if (this._isAnimationSheetEnabled) {
  55709. if (offsetX === 0)
  55710. offsetX = this._epsilon;
  55711. else if (offsetX === 1)
  55712. offsetX = 1 - this._epsilon;
  55713. if (offsetY === 0)
  55714. offsetY = this._epsilon;
  55715. else if (offsetY === 1)
  55716. offsetY = 1 - this._epsilon;
  55717. }
  55718. this._vertexData[offset++] = offsetX;
  55719. this._vertexData[offset++] = offsetY;
  55720. }
  55721. };
  55722. ParticleSystem.prototype._stopSubEmitters = function () {
  55723. if (!this.activeSubSystems) {
  55724. return;
  55725. }
  55726. this.activeSubSystems.forEach(function (subSystem) {
  55727. subSystem.stop(true);
  55728. });
  55729. this.activeSubSystems = new Array();
  55730. };
  55731. ParticleSystem.prototype._removeFromRoot = function () {
  55732. if (!this._rootParticleSystem) {
  55733. return;
  55734. }
  55735. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55736. if (index !== -1) {
  55737. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55738. }
  55739. };
  55740. // End of sub system methods
  55741. ParticleSystem.prototype._update = function (newParticles) {
  55742. // Update current
  55743. this._alive = this._particles.length > 0;
  55744. this.updateFunction(this._particles);
  55745. // Add new ones
  55746. var worldMatrix;
  55747. if (this.emitter.position) {
  55748. var emitterMesh = this.emitter;
  55749. worldMatrix = emitterMesh.getWorldMatrix();
  55750. }
  55751. else {
  55752. var emitterPosition = this.emitter;
  55753. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55754. }
  55755. var particle;
  55756. var _loop_2 = function () {
  55757. if (this_1._particles.length === this_1._capacity) {
  55758. return "break";
  55759. }
  55760. particle = this_1._createParticle();
  55761. this_1._particles.push(particle);
  55762. // Emitter
  55763. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55764. if (this_1.startPositionFunction) {
  55765. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55766. }
  55767. else {
  55768. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55769. }
  55770. if (this_1.startDirectionFunction) {
  55771. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55772. }
  55773. else {
  55774. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55775. }
  55776. if (emitPower === 0) {
  55777. if (!particle._initialDirection) {
  55778. particle._initialDirection = particle.direction.clone();
  55779. }
  55780. else {
  55781. particle._initialDirection.copyFrom(particle.direction);
  55782. }
  55783. }
  55784. else {
  55785. particle._initialDirection = null;
  55786. }
  55787. particle.direction.scaleInPlace(emitPower);
  55788. // Life time
  55789. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55790. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55791. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55792. var factorGradient1 = currentGradient;
  55793. var factorGradient2 = nextGradient;
  55794. var lifeTime1 = factorGradient1.getFactor();
  55795. var lifeTime2 = factorGradient2.getFactor();
  55796. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55797. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55798. });
  55799. }
  55800. else {
  55801. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55802. }
  55803. // Size
  55804. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55805. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55806. }
  55807. else {
  55808. particle._currentSizeGradient = this_1._sizeGradients[0];
  55809. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55810. particle.size = particle._currentSize1;
  55811. if (this_1._sizeGradients.length > 1) {
  55812. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55813. }
  55814. else {
  55815. particle._currentSize2 = particle._currentSize1;
  55816. }
  55817. }
  55818. // Size and scale
  55819. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55820. // Angle
  55821. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55822. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55823. }
  55824. else {
  55825. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55826. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55827. particle._currentAngularSpeed1 = particle.angularSpeed;
  55828. if (this_1._angularSpeedGradients.length > 1) {
  55829. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55830. }
  55831. else {
  55832. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55833. }
  55834. }
  55835. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55836. // Velocity
  55837. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55838. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55839. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55840. if (this_1._velocityGradients.length > 1) {
  55841. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55842. }
  55843. else {
  55844. particle._currentVelocity2 = particle._currentVelocity1;
  55845. }
  55846. }
  55847. // Color
  55848. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55849. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55850. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55851. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55852. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55853. }
  55854. else {
  55855. particle._currentColorGradient = this_1._colorGradients[0];
  55856. particle._currentColorGradient.getColorToRef(particle.color);
  55857. particle._currentColor1.copyFrom(particle.color);
  55858. if (this_1._colorGradients.length > 1) {
  55859. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55860. }
  55861. else {
  55862. particle._currentColor2.copyFrom(particle.color);
  55863. }
  55864. }
  55865. // Sheet
  55866. if (this_1._isAnimationSheetEnabled) {
  55867. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55868. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55869. }
  55870. };
  55871. var this_1 = this, step;
  55872. for (var index = 0; index < newParticles; index++) {
  55873. var state_1 = _loop_2();
  55874. if (state_1 === "break")
  55875. break;
  55876. }
  55877. };
  55878. /** @hidden */
  55879. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55880. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55881. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55882. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55883. if (isAnimationSheetEnabled) {
  55884. attributeNamesOrOptions.push("cellIndex");
  55885. }
  55886. if (!isBillboardBased) {
  55887. attributeNamesOrOptions.push("direction");
  55888. }
  55889. return attributeNamesOrOptions;
  55890. };
  55891. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55892. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55893. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55894. if (isAnimationSheetEnabled) {
  55895. effectCreationOption.push("particlesInfos");
  55896. }
  55897. return effectCreationOption;
  55898. };
  55899. ParticleSystem.prototype._getEffect = function () {
  55900. if (this._customEffect) {
  55901. return this._customEffect;
  55902. }
  55903. ;
  55904. var defines = [];
  55905. if (this._scene.clipPlane) {
  55906. defines.push("#define CLIPPLANE");
  55907. }
  55908. if (this._isAnimationSheetEnabled) {
  55909. defines.push("#define ANIMATESHEET");
  55910. }
  55911. if (this._isBillboardBased) {
  55912. defines.push("#define BILLBOARD");
  55913. switch (this.billboardMode) {
  55914. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55915. defines.push("#define BILLBOARDY");
  55916. break;
  55917. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55918. default:
  55919. break;
  55920. }
  55921. }
  55922. // Effect
  55923. var join = defines.join("\n");
  55924. if (this._cachedDefines !== join) {
  55925. this._cachedDefines = join;
  55926. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55927. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55928. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55929. }
  55930. return this._effect;
  55931. };
  55932. /**
  55933. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55934. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55935. */
  55936. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55937. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55938. if (!this._started)
  55939. return;
  55940. if (!preWarmOnly) {
  55941. var effect = this._getEffect();
  55942. // Check
  55943. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55944. return;
  55945. if (this._currentRenderId === this._scene.getRenderId()) {
  55946. return;
  55947. }
  55948. this._currentRenderId = this._scene.getRenderId();
  55949. }
  55950. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55951. // determine the number of particles we need to create
  55952. var newParticles;
  55953. if (this.manualEmitCount > -1) {
  55954. newParticles = this.manualEmitCount;
  55955. this._newPartsExcess = 0;
  55956. this.manualEmitCount = 0;
  55957. }
  55958. else {
  55959. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55960. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55961. }
  55962. if (this._newPartsExcess > 1.0) {
  55963. newParticles += this._newPartsExcess >> 0;
  55964. this._newPartsExcess -= this._newPartsExcess >> 0;
  55965. }
  55966. this._alive = false;
  55967. if (!this._stopped) {
  55968. this._actualFrame += this._scaledUpdateSpeed;
  55969. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55970. this.stop();
  55971. }
  55972. else {
  55973. newParticles = 0;
  55974. }
  55975. this._update(newParticles);
  55976. // Stopped?
  55977. if (this._stopped) {
  55978. if (!this._alive) {
  55979. this._started = false;
  55980. if (this.onAnimationEnd) {
  55981. this.onAnimationEnd();
  55982. }
  55983. if (this.disposeOnStop) {
  55984. this._scene._toBeDisposed.push(this);
  55985. }
  55986. }
  55987. }
  55988. if (!preWarmOnly) {
  55989. // Update VBO
  55990. var offset = 0;
  55991. for (var index = 0; index < this._particles.length; index++) {
  55992. var particle = this._particles[index];
  55993. this._appendParticleVertices(offset, particle);
  55994. offset += this._useInstancing ? 1 : 4;
  55995. }
  55996. if (this._vertexBuffer) {
  55997. this._vertexBuffer.update(this._vertexData);
  55998. }
  55999. }
  56000. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56001. this.stop();
  56002. }
  56003. };
  56004. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56005. this._appendParticleVertex(offset++, particle, 0, 0);
  56006. if (!this._useInstancing) {
  56007. this._appendParticleVertex(offset++, particle, 1, 0);
  56008. this._appendParticleVertex(offset++, particle, 1, 1);
  56009. this._appendParticleVertex(offset++, particle, 0, 1);
  56010. }
  56011. };
  56012. /**
  56013. * Rebuilds the particle system.
  56014. */
  56015. ParticleSystem.prototype.rebuild = function () {
  56016. this._createIndexBuffer();
  56017. if (this._vertexBuffer) {
  56018. this._vertexBuffer._rebuild();
  56019. }
  56020. };
  56021. /**
  56022. * Is this system ready to be used/rendered
  56023. * @return true if the system is ready
  56024. */
  56025. ParticleSystem.prototype.isReady = function () {
  56026. var effect = this._getEffect();
  56027. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56028. return false;
  56029. }
  56030. return true;
  56031. };
  56032. /**
  56033. * Renders the particle system in its current state.
  56034. * @returns the current number of particles
  56035. */
  56036. ParticleSystem.prototype.render = function () {
  56037. var effect = this._getEffect();
  56038. // Check
  56039. if (!this.isReady() || !this._particles.length) {
  56040. return 0;
  56041. }
  56042. var engine = this._scene.getEngine();
  56043. // Render
  56044. engine.enableEffect(effect);
  56045. engine.setState(false);
  56046. var viewMatrix = this._scene.getViewMatrix();
  56047. effect.setTexture("diffuseSampler", this.particleTexture);
  56048. effect.setMatrix("view", viewMatrix);
  56049. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56050. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56051. var baseSize = this.particleTexture.getBaseSize();
  56052. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56053. }
  56054. effect.setVector2("translationPivot", this.translationPivot);
  56055. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56056. if (this._isBillboardBased) {
  56057. var camera = this._scene.activeCamera;
  56058. effect.setVector3("eyePosition", camera.globalPosition);
  56059. }
  56060. if (this._scene.clipPlane) {
  56061. var clipPlane = this._scene.clipPlane;
  56062. var invView = viewMatrix.clone();
  56063. invView.invert();
  56064. effect.setMatrix("invView", invView);
  56065. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56066. }
  56067. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56068. // Draw order
  56069. switch (this.blendMode) {
  56070. case ParticleSystem.BLENDMODE_ADD:
  56071. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56072. break;
  56073. case ParticleSystem.BLENDMODE_ONEONE:
  56074. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56075. break;
  56076. case ParticleSystem.BLENDMODE_STANDARD:
  56077. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56078. break;
  56079. }
  56080. if (this.forceDepthWrite) {
  56081. engine.setDepthWrite(true);
  56082. }
  56083. if (this._useInstancing) {
  56084. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56085. engine.unbindInstanceAttributes();
  56086. }
  56087. else {
  56088. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56089. }
  56090. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56091. return this._particles.length;
  56092. };
  56093. /**
  56094. * Disposes the particle system and free the associated resources
  56095. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56096. */
  56097. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56098. if (disposeTexture === void 0) { disposeTexture = true; }
  56099. if (this._vertexBuffer) {
  56100. this._vertexBuffer.dispose();
  56101. this._vertexBuffer = null;
  56102. }
  56103. if (this._spriteBuffer) {
  56104. this._spriteBuffer.dispose();
  56105. this._spriteBuffer = null;
  56106. }
  56107. if (this._indexBuffer) {
  56108. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56109. this._indexBuffer = null;
  56110. }
  56111. if (disposeTexture && this.particleTexture) {
  56112. this.particleTexture.dispose();
  56113. this.particleTexture = null;
  56114. }
  56115. this._removeFromRoot();
  56116. // Remove from scene
  56117. var index = this._scene.particleSystems.indexOf(this);
  56118. if (index > -1) {
  56119. this._scene.particleSystems.splice(index, 1);
  56120. }
  56121. // Callback
  56122. this.onDisposeObservable.notifyObservers(this);
  56123. this.onDisposeObservable.clear();
  56124. };
  56125. /**
  56126. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56127. * @param radius The radius of the sphere to emit from
  56128. * @returns the emitter
  56129. */
  56130. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56131. if (radius === void 0) { radius = 1; }
  56132. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56133. this.particleEmitterType = particleEmitter;
  56134. return particleEmitter;
  56135. };
  56136. /**
  56137. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56138. * @param radius The radius of the sphere to emit from
  56139. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56140. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56141. * @returns the emitter
  56142. */
  56143. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56144. if (radius === void 0) { radius = 1; }
  56145. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56146. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56147. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56148. this.particleEmitterType = particleEmitter;
  56149. return particleEmitter;
  56150. };
  56151. /**
  56152. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56153. * @param radius The radius of the cone to emit from
  56154. * @param angle The base angle of the cone
  56155. * @returns the emitter
  56156. */
  56157. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56158. if (radius === void 0) { radius = 1; }
  56159. if (angle === void 0) { angle = Math.PI / 4; }
  56160. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56161. this.particleEmitterType = particleEmitter;
  56162. return particleEmitter;
  56163. };
  56164. // 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.
  56165. /**
  56166. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56167. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56168. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56169. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56170. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56171. * @returns the emitter
  56172. */
  56173. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56174. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56175. this.particleEmitterType = particleEmitter;
  56176. this.direction1 = direction1;
  56177. this.direction2 = direction2;
  56178. this.minEmitBox = minEmitBox;
  56179. this.maxEmitBox = maxEmitBox;
  56180. return particleEmitter;
  56181. };
  56182. // Clone
  56183. /**
  56184. * Clones the particle system.
  56185. * @param name The name of the cloned object
  56186. * @param newEmitter The new emitter to use
  56187. * @returns the cloned particle system
  56188. */
  56189. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56190. var custom = null;
  56191. var program = null;
  56192. if (this.customShader != null) {
  56193. program = this.customShader;
  56194. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56195. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56196. }
  56197. else if (this._customEffect) {
  56198. custom = this._customEffect;
  56199. }
  56200. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56201. result.customShader = program;
  56202. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56203. if (newEmitter === undefined) {
  56204. newEmitter = this.emitter;
  56205. }
  56206. result.emitter = newEmitter;
  56207. if (this.particleTexture) {
  56208. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56209. }
  56210. if (!this.preventAutoStart) {
  56211. result.start();
  56212. }
  56213. return result;
  56214. };
  56215. /**
  56216. * Serializes the particle system to a JSON object.
  56217. * @returns the JSON object
  56218. */
  56219. ParticleSystem.prototype.serialize = function () {
  56220. var serializationObject = {};
  56221. ParticleSystem._Serialize(serializationObject, this);
  56222. serializationObject.textureMask = this.textureMask.asArray();
  56223. serializationObject.customShader = this.customShader;
  56224. serializationObject.preventAutoStart = this.preventAutoStart;
  56225. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56226. return serializationObject;
  56227. };
  56228. /** @hidden */
  56229. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56230. serializationObject.name = particleSystem.name;
  56231. serializationObject.id = particleSystem.id;
  56232. serializationObject.capacity = particleSystem.getCapacity();
  56233. // Emitter
  56234. if (particleSystem.emitter.position) {
  56235. var emitterMesh = particleSystem.emitter;
  56236. serializationObject.emitterId = emitterMesh.id;
  56237. }
  56238. else {
  56239. var emitterPosition = particleSystem.emitter;
  56240. serializationObject.emitter = emitterPosition.asArray();
  56241. }
  56242. // Emitter
  56243. if (particleSystem.particleEmitterType) {
  56244. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56245. }
  56246. if (particleSystem.particleTexture) {
  56247. serializationObject.textureName = particleSystem.particleTexture.name;
  56248. }
  56249. // Animations
  56250. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56251. // Particle system
  56252. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56253. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56254. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56255. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56256. serializationObject.minSize = particleSystem.minSize;
  56257. serializationObject.maxSize = particleSystem.maxSize;
  56258. serializationObject.minScaleX = particleSystem.minScaleX;
  56259. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56260. serializationObject.minScaleY = particleSystem.minScaleY;
  56261. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56262. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56263. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56264. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56265. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56266. serializationObject.emitRate = particleSystem.emitRate;
  56267. serializationObject.gravity = particleSystem.gravity.asArray();
  56268. serializationObject.color1 = particleSystem.color1.asArray();
  56269. serializationObject.color2 = particleSystem.color2.asArray();
  56270. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56271. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56272. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56273. serializationObject.blendMode = particleSystem.blendMode;
  56274. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56275. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56276. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56277. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56278. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56279. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56280. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56281. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56282. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56283. var colorGradients = particleSystem.getColorGradients();
  56284. if (colorGradients) {
  56285. serializationObject.colorGradients = [];
  56286. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56287. var colorGradient = colorGradients_1[_i];
  56288. var serializedGradient = {
  56289. gradient: colorGradient.gradient,
  56290. color1: colorGradient.color1.asArray()
  56291. };
  56292. if (colorGradient.color2) {
  56293. serializedGradient.color2 = colorGradient.color2.asArray();
  56294. }
  56295. serializationObject.colorGradients.push(serializedGradient);
  56296. }
  56297. }
  56298. var sizeGradients = particleSystem.getSizeGradients();
  56299. if (sizeGradients) {
  56300. serializationObject.sizeGradients = [];
  56301. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56302. var sizeGradient = sizeGradients_1[_a];
  56303. var serializedGradient = {
  56304. gradient: sizeGradient.gradient,
  56305. factor1: sizeGradient.factor1
  56306. };
  56307. if (sizeGradient.factor2 !== undefined) {
  56308. serializedGradient.factor2 = sizeGradient.factor2;
  56309. }
  56310. serializationObject.sizeGradients.push(serializedGradient);
  56311. }
  56312. }
  56313. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56314. if (angularSpeedGradients) {
  56315. serializationObject.angularSpeedGradients = [];
  56316. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56317. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56318. var serializedGradient = {
  56319. gradient: angularSpeedGradient.gradient,
  56320. factor1: angularSpeedGradient.factor1
  56321. };
  56322. if (angularSpeedGradient.factor2 !== undefined) {
  56323. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56324. }
  56325. serializationObject.angularSpeedGradients.push(serializedGradient);
  56326. }
  56327. }
  56328. var velocityGradients = particleSystem.getVelocityGradients();
  56329. if (velocityGradients) {
  56330. serializationObject.velocityGradients = [];
  56331. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56332. var velocityGradient = velocityGradients_1[_c];
  56333. var serializedGradient = {
  56334. gradient: velocityGradient.gradient,
  56335. factor1: velocityGradient.factor1
  56336. };
  56337. if (velocityGradient.factor2 !== undefined) {
  56338. serializedGradient.factor2 = velocityGradient.factor2;
  56339. }
  56340. serializationObject.velocityGradients.push(serializedGradient);
  56341. }
  56342. }
  56343. };
  56344. /** @hidden */
  56345. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56346. // Texture
  56347. if (parsedParticleSystem.textureName) {
  56348. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56349. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56350. }
  56351. // Emitter
  56352. if (parsedParticleSystem.emitterId === undefined) {
  56353. particleSystem.emitter = BABYLON.Vector3.Zero();
  56354. }
  56355. else if (parsedParticleSystem.emitterId) {
  56356. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56357. }
  56358. else {
  56359. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56360. }
  56361. // Misc.
  56362. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56363. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56364. }
  56365. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56366. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56367. }
  56368. // Animations
  56369. if (parsedParticleSystem.animations) {
  56370. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56371. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56372. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56373. }
  56374. }
  56375. if (parsedParticleSystem.autoAnimate) {
  56376. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56377. }
  56378. // Particle system
  56379. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56380. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56381. particleSystem.minSize = parsedParticleSystem.minSize;
  56382. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56383. if (parsedParticleSystem.minScaleX) {
  56384. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56385. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56386. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56387. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56388. }
  56389. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56390. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56391. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56392. }
  56393. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56394. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56395. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56396. }
  56397. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56398. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56399. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56400. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56401. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56402. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56403. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56404. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56405. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56406. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56407. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56408. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56409. if (parsedParticleSystem.colorGradients) {
  56410. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56411. var colorGradient = _a[_i];
  56412. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56413. }
  56414. }
  56415. if (parsedParticleSystem.sizeGradients) {
  56416. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56417. var sizeGradient = _c[_b];
  56418. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56419. }
  56420. }
  56421. if (parsedParticleSystem.angularSpeedGradients) {
  56422. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56423. var angularSpeedGradient = _e[_d];
  56424. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56425. }
  56426. }
  56427. if (parsedParticleSystem.velocityGradients) {
  56428. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56429. var velocityGradient = _g[_f];
  56430. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56431. }
  56432. }
  56433. // Emitter
  56434. var emitterType;
  56435. if (parsedParticleSystem.particleEmitterType) {
  56436. switch (parsedParticleSystem.particleEmitterType.type) {
  56437. case "SphereParticleEmitter":
  56438. emitterType = new BABYLON.SphereParticleEmitter();
  56439. break;
  56440. case "SphereDirectedParticleEmitter":
  56441. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56442. break;
  56443. case "ConeEmitter":
  56444. case "ConeParticleEmitter":
  56445. emitterType = new BABYLON.ConeParticleEmitter();
  56446. break;
  56447. case "BoxEmitter":
  56448. case "BoxParticleEmitter":
  56449. default:
  56450. emitterType = new BABYLON.BoxParticleEmitter();
  56451. break;
  56452. }
  56453. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56454. }
  56455. else {
  56456. emitterType = new BABYLON.BoxParticleEmitter();
  56457. emitterType.parse(parsedParticleSystem);
  56458. }
  56459. particleSystem.particleEmitterType = emitterType;
  56460. // Animation sheet
  56461. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56462. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56463. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56464. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56465. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56466. };
  56467. /**
  56468. * Parses a JSON object to create a particle system.
  56469. * @param parsedParticleSystem The JSON object to parse
  56470. * @param scene The scene to create the particle system in
  56471. * @param rootUrl The root url to use to load external dependencies like texture
  56472. * @returns the Parsed particle system
  56473. */
  56474. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56475. var name = parsedParticleSystem.name;
  56476. var custom = null;
  56477. var program = null;
  56478. if (parsedParticleSystem.customShader) {
  56479. program = parsedParticleSystem.customShader;
  56480. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56481. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56482. }
  56483. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56484. particleSystem.customShader = program;
  56485. if (parsedParticleSystem.id) {
  56486. particleSystem.id = parsedParticleSystem.id;
  56487. }
  56488. // Auto start
  56489. if (parsedParticleSystem.preventAutoStart) {
  56490. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56491. }
  56492. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56493. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56494. if (!particleSystem.preventAutoStart) {
  56495. particleSystem.start();
  56496. }
  56497. return particleSystem;
  56498. };
  56499. /**
  56500. * Source color is added to the destination color without alpha affecting the result.
  56501. */
  56502. ParticleSystem.BLENDMODE_ONEONE = 0;
  56503. /**
  56504. * Blend current color and particle color using particle’s alpha.
  56505. */
  56506. ParticleSystem.BLENDMODE_STANDARD = 1;
  56507. /**
  56508. * Add current color and particle color multiplied by particle’s alpha.
  56509. */
  56510. ParticleSystem.BLENDMODE_ADD = 2;
  56511. return ParticleSystem;
  56512. }());
  56513. BABYLON.ParticleSystem = ParticleSystem;
  56514. })(BABYLON || (BABYLON = {}));
  56515. //# sourceMappingURL=babylon.particleSystem.js.map
  56516. var BABYLON;
  56517. (function (BABYLON) {
  56518. /**
  56519. * Particle emitter emitting particles from the inside of a box.
  56520. * It emits the particles randomly between 2 given directions.
  56521. */
  56522. var BoxParticleEmitter = /** @class */ (function () {
  56523. /**
  56524. * Creates a new instance BoxParticleEmitter
  56525. */
  56526. function BoxParticleEmitter() {
  56527. /**
  56528. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56529. */
  56530. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56531. /**
  56532. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56533. */
  56534. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56535. /**
  56536. * 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.
  56537. */
  56538. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56539. /**
  56540. * 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.
  56541. */
  56542. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56543. }
  56544. /**
  56545. * Called by the particle System when the direction is computed for the created particle.
  56546. * @param worldMatrix is the world matrix of the particle system
  56547. * @param directionToUpdate is the direction vector to update with the result
  56548. * @param particle is the particle we are computed the direction for
  56549. */
  56550. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56551. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56552. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56553. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56554. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56555. };
  56556. /**
  56557. * Called by the particle System when the position is computed for the created particle.
  56558. * @param worldMatrix is the world matrix of the particle system
  56559. * @param positionToUpdate is the position vector to update with the result
  56560. * @param particle is the particle we are computed the position for
  56561. */
  56562. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56563. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56564. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56565. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56566. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56567. };
  56568. /**
  56569. * Clones the current emitter and returns a copy of it
  56570. * @returns the new emitter
  56571. */
  56572. BoxParticleEmitter.prototype.clone = function () {
  56573. var newOne = new BoxParticleEmitter();
  56574. BABYLON.Tools.DeepCopy(this, newOne);
  56575. return newOne;
  56576. };
  56577. /**
  56578. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56579. * @param effect defines the update shader
  56580. */
  56581. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56582. effect.setVector3("direction1", this.direction1);
  56583. effect.setVector3("direction2", this.direction2);
  56584. effect.setVector3("minEmitBox", this.minEmitBox);
  56585. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56586. };
  56587. /**
  56588. * Returns a string to use to update the GPU particles update shader
  56589. * @returns a string containng the defines string
  56590. */
  56591. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56592. return "#define BOXEMITTER";
  56593. };
  56594. /**
  56595. * Returns the string "BoxParticleEmitter"
  56596. * @returns a string containing the class name
  56597. */
  56598. BoxParticleEmitter.prototype.getClassName = function () {
  56599. return "BoxParticleEmitter";
  56600. };
  56601. /**
  56602. * Serializes the particle system to a JSON object.
  56603. * @returns the JSON object
  56604. */
  56605. BoxParticleEmitter.prototype.serialize = function () {
  56606. var serializationObject = {};
  56607. serializationObject.type = this.getClassName();
  56608. serializationObject.direction1 = this.direction1.asArray();
  56609. serializationObject.direction2 = this.direction2.asArray();
  56610. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56611. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56612. return serializationObject;
  56613. };
  56614. /**
  56615. * Parse properties from a JSON object
  56616. * @param serializationObject defines the JSON object
  56617. */
  56618. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56619. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56620. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56621. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56622. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56623. };
  56624. return BoxParticleEmitter;
  56625. }());
  56626. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56627. })(BABYLON || (BABYLON = {}));
  56628. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56629. var BABYLON;
  56630. (function (BABYLON) {
  56631. /**
  56632. * Particle emitter emitting particles from the inside of a cone.
  56633. * It emits the particles alongside the cone volume from the base to the particle.
  56634. * The emission direction might be randomized.
  56635. */
  56636. var ConeParticleEmitter = /** @class */ (function () {
  56637. /**
  56638. * Creates a new instance ConeParticleEmitter
  56639. * @param radius the radius of the emission cone (1 by default)
  56640. * @param angles the cone base angle (PI by default)
  56641. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56642. */
  56643. function ConeParticleEmitter(radius, angle,
  56644. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56645. directionRandomizer) {
  56646. if (radius === void 0) { radius = 1; }
  56647. if (angle === void 0) { angle = Math.PI; }
  56648. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56649. this.directionRandomizer = directionRandomizer;
  56650. /**
  56651. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56652. */
  56653. this.radiusRange = 1;
  56654. /**
  56655. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56656. */
  56657. this.heightRange = 1;
  56658. this.angle = angle;
  56659. this.radius = radius;
  56660. }
  56661. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56662. /**
  56663. * Gets or sets the radius of the emission cone
  56664. */
  56665. get: function () {
  56666. return this._radius;
  56667. },
  56668. set: function (value) {
  56669. this._radius = value;
  56670. this._buildHeight();
  56671. },
  56672. enumerable: true,
  56673. configurable: true
  56674. });
  56675. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56676. /**
  56677. * Gets or sets the angle of the emission cone
  56678. */
  56679. get: function () {
  56680. return this._angle;
  56681. },
  56682. set: function (value) {
  56683. this._angle = value;
  56684. this._buildHeight();
  56685. },
  56686. enumerable: true,
  56687. configurable: true
  56688. });
  56689. ConeParticleEmitter.prototype._buildHeight = function () {
  56690. if (this._angle !== 0) {
  56691. this._height = this._radius / Math.tan(this._angle / 2);
  56692. }
  56693. else {
  56694. this._height = 1;
  56695. }
  56696. };
  56697. /**
  56698. * Called by the particle System when the direction is computed for the created particle.
  56699. * @param worldMatrix is the world matrix of the particle system
  56700. * @param directionToUpdate is the direction vector to update with the result
  56701. * @param particle is the particle we are computed the direction for
  56702. */
  56703. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56704. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56705. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56706. }
  56707. else {
  56708. // measure the direction Vector from the emitter to the particle.
  56709. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56710. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56711. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56712. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56713. direction.x += randX;
  56714. direction.y += randY;
  56715. direction.z += randZ;
  56716. direction.normalize();
  56717. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56718. }
  56719. };
  56720. /**
  56721. * Called by the particle System when the position is computed for the created particle.
  56722. * @param worldMatrix is the world matrix of the particle system
  56723. * @param positionToUpdate is the position vector to update with the result
  56724. * @param particle is the particle we are computed the position for
  56725. */
  56726. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56727. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56728. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56729. // Better distribution in a cone at normal angles.
  56730. h = 1 - h * h;
  56731. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56732. radius = radius * h;
  56733. var randX = radius * Math.sin(s);
  56734. var randZ = radius * Math.cos(s);
  56735. var randY = h * this._height;
  56736. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56737. };
  56738. /**
  56739. * Clones the current emitter and returns a copy of it
  56740. * @returns the new emitter
  56741. */
  56742. ConeParticleEmitter.prototype.clone = function () {
  56743. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56744. BABYLON.Tools.DeepCopy(this, newOne);
  56745. return newOne;
  56746. };
  56747. /**
  56748. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56749. * @param effect defines the update shader
  56750. */
  56751. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56752. effect.setFloat2("radius", this._radius, this.radiusRange);
  56753. effect.setFloat("coneAngle", this._angle);
  56754. effect.setFloat2("height", this._height, this.heightRange);
  56755. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56756. };
  56757. /**
  56758. * Returns a string to use to update the GPU particles update shader
  56759. * @returns a string containng the defines string
  56760. */
  56761. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56762. return "#define CONEEMITTER";
  56763. };
  56764. /**
  56765. * Returns the string "ConeParticleEmitter"
  56766. * @returns a string containing the class name
  56767. */
  56768. ConeParticleEmitter.prototype.getClassName = function () {
  56769. return "ConeParticleEmitter";
  56770. };
  56771. /**
  56772. * Serializes the particle system to a JSON object.
  56773. * @returns the JSON object
  56774. */
  56775. ConeParticleEmitter.prototype.serialize = function () {
  56776. var serializationObject = {};
  56777. serializationObject.type = this.getClassName();
  56778. serializationObject.radius = this._radius;
  56779. serializationObject.angle = this._angle;
  56780. serializationObject.directionRandomizer = this.directionRandomizer;
  56781. return serializationObject;
  56782. };
  56783. /**
  56784. * Parse properties from a JSON object
  56785. * @param serializationObject defines the JSON object
  56786. */
  56787. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56788. this.radius = serializationObject.radius;
  56789. this.angle = serializationObject.angle;
  56790. this.directionRandomizer = serializationObject.directionRandomizer;
  56791. };
  56792. return ConeParticleEmitter;
  56793. }());
  56794. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56795. })(BABYLON || (BABYLON = {}));
  56796. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56797. var BABYLON;
  56798. (function (BABYLON) {
  56799. /**
  56800. * Particle emitter emitting particles from the inside of a sphere.
  56801. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56802. */
  56803. var SphereParticleEmitter = /** @class */ (function () {
  56804. /**
  56805. * Creates a new instance SphereParticleEmitter
  56806. * @param radius the radius of the emission sphere (1 by default)
  56807. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56808. */
  56809. function SphereParticleEmitter(
  56810. /**
  56811. * The radius of the emission sphere.
  56812. */
  56813. radius,
  56814. /**
  56815. * How much to randomize the particle direction [0-1].
  56816. */
  56817. directionRandomizer) {
  56818. if (radius === void 0) { radius = 1; }
  56819. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56820. this.radius = radius;
  56821. this.directionRandomizer = directionRandomizer;
  56822. /**
  56823. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56824. */
  56825. this.radiusRange = 1;
  56826. }
  56827. /**
  56828. * Called by the particle System when the direction is computed for the created particle.
  56829. * @param worldMatrix is the world matrix of the particle system
  56830. * @param directionToUpdate is the direction vector to update with the result
  56831. * @param particle is the particle we are computed the direction for
  56832. */
  56833. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56834. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56835. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56836. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56837. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56838. direction.x += randX;
  56839. direction.y += randY;
  56840. direction.z += randZ;
  56841. direction.normalize();
  56842. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56843. };
  56844. /**
  56845. * Called by the particle System when the position is computed for the created particle.
  56846. * @param worldMatrix is the world matrix of the particle system
  56847. * @param positionToUpdate is the position vector to update with the result
  56848. * @param particle is the particle we are computed the position for
  56849. */
  56850. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56851. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56852. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56853. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56854. var theta = Math.acos(2 * v - 1);
  56855. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56856. var randY = randRadius * Math.cos(theta);
  56857. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56858. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56859. };
  56860. /**
  56861. * Clones the current emitter and returns a copy of it
  56862. * @returns the new emitter
  56863. */
  56864. SphereParticleEmitter.prototype.clone = function () {
  56865. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56866. BABYLON.Tools.DeepCopy(this, newOne);
  56867. return newOne;
  56868. };
  56869. /**
  56870. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56871. * @param effect defines the update shader
  56872. */
  56873. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56874. effect.setFloat("radius", this.radius);
  56875. effect.setFloat("radiusRange", this.radiusRange);
  56876. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56877. };
  56878. /**
  56879. * Returns a string to use to update the GPU particles update shader
  56880. * @returns a string containng the defines string
  56881. */
  56882. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56883. return "#define SPHEREEMITTER";
  56884. };
  56885. /**
  56886. * Returns the string "SphereParticleEmitter"
  56887. * @returns a string containing the class name
  56888. */
  56889. SphereParticleEmitter.prototype.getClassName = function () {
  56890. return "SphereParticleEmitter";
  56891. };
  56892. /**
  56893. * Serializes the particle system to a JSON object.
  56894. * @returns the JSON object
  56895. */
  56896. SphereParticleEmitter.prototype.serialize = function () {
  56897. var serializationObject = {};
  56898. serializationObject.type = this.getClassName();
  56899. serializationObject.radius = this.radius;
  56900. serializationObject.radiusRange = this.radiusRange;
  56901. serializationObject.directionRandomizer = this.directionRandomizer;
  56902. return serializationObject;
  56903. };
  56904. /**
  56905. * Parse properties from a JSON object
  56906. * @param serializationObject defines the JSON object
  56907. */
  56908. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56909. this.radius = serializationObject.radius;
  56910. this.radiusRange = serializationObject.radiusRange;
  56911. this.directionRandomizer = serializationObject.directionRandomizer;
  56912. };
  56913. return SphereParticleEmitter;
  56914. }());
  56915. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56916. /**
  56917. * Particle emitter emitting particles from the inside of a sphere.
  56918. * It emits the particles randomly between two vectors.
  56919. */
  56920. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56921. __extends(SphereDirectedParticleEmitter, _super);
  56922. /**
  56923. * Creates a new instance SphereDirectedParticleEmitter
  56924. * @param radius the radius of the emission sphere (1 by default)
  56925. * @param direction1 the min limit of the emission direction (up vector by default)
  56926. * @param direction2 the max limit of the emission direction (up vector by default)
  56927. */
  56928. function SphereDirectedParticleEmitter(radius,
  56929. /**
  56930. * The min limit of the emission direction.
  56931. */
  56932. direction1,
  56933. /**
  56934. * The max limit of the emission direction.
  56935. */
  56936. direction2) {
  56937. if (radius === void 0) { radius = 1; }
  56938. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56939. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56940. var _this = _super.call(this, radius) || this;
  56941. _this.direction1 = direction1;
  56942. _this.direction2 = direction2;
  56943. return _this;
  56944. }
  56945. /**
  56946. * Called by the particle System when the direction is computed for the created particle.
  56947. * @param worldMatrix is the world matrix of the particle system
  56948. * @param directionToUpdate is the direction vector to update with the result
  56949. * @param particle is the particle we are computed the direction for
  56950. */
  56951. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56952. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56953. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56954. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56955. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56956. };
  56957. /**
  56958. * Clones the current emitter and returns a copy of it
  56959. * @returns the new emitter
  56960. */
  56961. SphereDirectedParticleEmitter.prototype.clone = function () {
  56962. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56963. BABYLON.Tools.DeepCopy(this, newOne);
  56964. return newOne;
  56965. };
  56966. /**
  56967. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56968. * @param effect defines the update shader
  56969. */
  56970. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56971. effect.setFloat("radius", this.radius);
  56972. effect.setFloat("radiusRange", this.radiusRange);
  56973. effect.setVector3("direction1", this.direction1);
  56974. effect.setVector3("direction2", this.direction2);
  56975. };
  56976. /**
  56977. * Returns a string to use to update the GPU particles update shader
  56978. * @returns a string containng the defines string
  56979. */
  56980. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56981. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56982. };
  56983. /**
  56984. * Returns the string "SphereDirectedParticleEmitter"
  56985. * @returns a string containing the class name
  56986. */
  56987. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56988. return "SphereDirectedParticleEmitter";
  56989. };
  56990. /**
  56991. * Serializes the particle system to a JSON object.
  56992. * @returns the JSON object
  56993. */
  56994. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56995. var serializationObject = _super.prototype.serialize.call(this);
  56996. serializationObject.direction1 = this.direction1.asArray();
  56997. serializationObject.direction2 = this.direction2.asArray();
  56998. return serializationObject;
  56999. };
  57000. /**
  57001. * Parse properties from a JSON object
  57002. * @param serializationObject defines the JSON object
  57003. */
  57004. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57005. _super.prototype.parse.call(this, serializationObject);
  57006. this.direction1.copyFrom(serializationObject.direction1);
  57007. this.direction2.copyFrom(serializationObject.direction2);
  57008. };
  57009. return SphereDirectedParticleEmitter;
  57010. }(SphereParticleEmitter));
  57011. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57012. })(BABYLON || (BABYLON = {}));
  57013. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57014. var BABYLON;
  57015. (function (BABYLON) {
  57016. // Adds the parsers to the scene parsers.
  57017. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57018. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57019. if (!individualParser) {
  57020. return;
  57021. }
  57022. // Particles Systems
  57023. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57024. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57025. var parsedParticleSystem = parsedData.particleSystems[index];
  57026. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57027. }
  57028. }
  57029. });
  57030. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57031. if (parsedParticleSystem.activeParticleCount) {
  57032. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57033. return ps;
  57034. }
  57035. else {
  57036. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57037. return ps;
  57038. }
  57039. });
  57040. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57041. if (uniformsNames === void 0) { uniformsNames = []; }
  57042. if (samplers === void 0) { samplers = []; }
  57043. if (defines === void 0) { defines = ""; }
  57044. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57045. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57046. if (defines.indexOf(" BILLBOARD") === -1) {
  57047. defines += "\n#define BILLBOARD\n";
  57048. }
  57049. if (samplers.indexOf("diffuseSampler") === -1) {
  57050. samplers.push("diffuseSampler");
  57051. }
  57052. return this.createEffect({
  57053. vertex: "particles",
  57054. fragmentElement: fragmentName
  57055. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57056. };
  57057. })(BABYLON || (BABYLON = {}));
  57058. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57059. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57060. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57061. s = arguments[i];
  57062. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57063. t[p] = s[p];
  57064. }
  57065. return t;
  57066. };
  57067. var BABYLON;
  57068. (function (BABYLON) {
  57069. /**
  57070. * This represents a GPU particle system in Babylon
  57071. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57072. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57073. */
  57074. var GPUParticleSystem = /** @class */ (function () {
  57075. /**
  57076. * Instantiates a GPU particle system.
  57077. * 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.
  57078. * @param name The name of the particle system
  57079. * @param options The options used to create the system
  57080. * @param scene The scene the particle system belongs to
  57081. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57082. */
  57083. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  57084. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57085. /**
  57086. * The emitter represents the Mesh or position we are attaching the particle system to.
  57087. */
  57088. this.emitter = null;
  57089. /**
  57090. * The rendering group used by the Particle system to chose when to render.
  57091. */
  57092. this.renderingGroupId = 0;
  57093. /**
  57094. * The layer mask we are rendering the particles through.
  57095. */
  57096. this.layerMask = 0x0FFFFFFF;
  57097. this._accumulatedCount = 0;
  57098. this._targetIndex = 0;
  57099. this._currentRenderId = -1;
  57100. this._started = false;
  57101. this._stopped = false;
  57102. this._timeDelta = 0;
  57103. this._attributesStrideSize = 21;
  57104. this._actualFrame = 0;
  57105. this._rawTextureWidth = 256;
  57106. /**
  57107. * List of animations used by the particle system.
  57108. */
  57109. this.animations = [];
  57110. /**
  57111. * An event triggered when the system is disposed.
  57112. */
  57113. this.onDisposeObservable = new BABYLON.Observable();
  57114. /**
  57115. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57116. */
  57117. this.updateSpeed = 0.01;
  57118. /**
  57119. * The amount of time the particle system is running (depends of the overall update speed).
  57120. */
  57121. this.targetStopDuration = 0;
  57122. /**
  57123. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57124. */
  57125. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57126. /**
  57127. * Minimum life time of emitting particles.
  57128. */
  57129. this.minLifeTime = 1;
  57130. /**
  57131. * Maximum life time of emitting particles.
  57132. */
  57133. this.maxLifeTime = 1;
  57134. /**
  57135. * Minimum Size of emitting particles.
  57136. */
  57137. this.minSize = 1;
  57138. /**
  57139. * Maximum Size of emitting particles.
  57140. */
  57141. this.maxSize = 1;
  57142. /**
  57143. * Minimum scale of emitting particles on X axis.
  57144. */
  57145. this.minScaleX = 1;
  57146. /**
  57147. * Maximum scale of emitting particles on X axis.
  57148. */
  57149. this.maxScaleX = 1;
  57150. /**
  57151. * Minimum scale of emitting particles on Y axis.
  57152. */
  57153. this.minScaleY = 1;
  57154. /**
  57155. * Maximum scale of emitting particles on Y axis.
  57156. */
  57157. this.maxScaleY = 1;
  57158. /**
  57159. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57160. */
  57161. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57162. /**
  57163. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57164. */
  57165. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57166. /**
  57167. * Color the particle will have at the end of its lifetime.
  57168. */
  57169. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57170. /**
  57171. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57172. */
  57173. this.emitRate = 100;
  57174. /**
  57175. * You can use gravity if you want to give an orientation to your particles.
  57176. */
  57177. this.gravity = BABYLON.Vector3.Zero();
  57178. /**
  57179. * Minimum power of emitting particles.
  57180. */
  57181. this.minEmitPower = 1;
  57182. /**
  57183. * Maximum power of emitting particles.
  57184. */
  57185. this.maxEmitPower = 1;
  57186. /**
  57187. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57188. */
  57189. this.minAngularSpeed = 0;
  57190. /**
  57191. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57192. */
  57193. this.maxAngularSpeed = 0;
  57194. /**
  57195. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57196. * to override the particles.
  57197. */
  57198. this.forceDepthWrite = false;
  57199. this._preWarmDone = false;
  57200. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  57201. this.preWarmCycles = 0;
  57202. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57203. this.preWarmStepOffset = 1;
  57204. /**
  57205. * Gets or sets the minimal initial rotation in radians.
  57206. */
  57207. this.minInitialRotation = 0;
  57208. /**
  57209. * Gets or sets the maximal initial rotation in radians.
  57210. */
  57211. this.maxInitialRotation = 0;
  57212. /**
  57213. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  57214. */
  57215. this.spriteCellChangeSpeed = 1;
  57216. /**
  57217. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57218. */
  57219. this.startSpriteCellID = 0;
  57220. /**
  57221. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57222. */
  57223. this.endSpriteCellID = 0;
  57224. /**
  57225. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57226. */
  57227. this.spriteCellWidth = 0;
  57228. /**
  57229. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57230. */
  57231. this.spriteCellHeight = 0;
  57232. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57233. this.translationPivot = new BABYLON.Vector2(0, 0);
  57234. /**
  57235. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57236. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  57237. */
  57238. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57239. this._isBillboardBased = true;
  57240. this._colorGradients = null;
  57241. this._angularSpeedGradients = null;
  57242. this._sizeGradients = null;
  57243. this._velocityGradients = null;
  57244. this.id = name;
  57245. this.name = name;
  57246. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57247. this._engine = this._scene.getEngine();
  57248. if (!options.randomTextureSize) {
  57249. delete options.randomTextureSize;
  57250. }
  57251. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57252. var optionsAsNumber = options;
  57253. if (isFinite(optionsAsNumber)) {
  57254. fullOptions.capacity = optionsAsNumber;
  57255. }
  57256. this._capacity = fullOptions.capacity;
  57257. this._activeCount = fullOptions.capacity;
  57258. this._currentActiveCount = 0;
  57259. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57260. this._scene.particleSystems.push(this);
  57261. this._updateEffectOptions = {
  57262. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57263. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57264. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57265. "angleRange", "radiusRange", "cellInfos"],
  57266. uniformBuffersNames: [],
  57267. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  57268. defines: "",
  57269. fallbacks: null,
  57270. onCompiled: null,
  57271. onError: null,
  57272. indexParameters: null,
  57273. maxSimultaneousLights: 0,
  57274. transformFeedbackVaryings: []
  57275. };
  57276. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57277. // Random data
  57278. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57279. var d = [];
  57280. for (var i = 0; i < maxTextureSize; ++i) {
  57281. d.push(Math.random());
  57282. d.push(Math.random());
  57283. d.push(Math.random());
  57284. d.push(Math.random());
  57285. }
  57286. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57287. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57288. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57289. d = [];
  57290. for (var i = 0; i < maxTextureSize; ++i) {
  57291. d.push(Math.random());
  57292. d.push(Math.random());
  57293. d.push(Math.random());
  57294. d.push(Math.random());
  57295. }
  57296. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57297. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57298. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57299. this._randomTextureSize = maxTextureSize;
  57300. }
  57301. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57302. /**
  57303. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57304. */
  57305. get: function () {
  57306. if (!BABYLON.Engine.LastCreatedEngine) {
  57307. return false;
  57308. }
  57309. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57310. },
  57311. enumerable: true,
  57312. configurable: true
  57313. });
  57314. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57315. /**
  57316. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57317. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57318. */
  57319. get: function () {
  57320. if (this.particleEmitterType.direction1) {
  57321. return this.particleEmitterType.direction1;
  57322. }
  57323. return BABYLON.Vector3.Zero();
  57324. },
  57325. set: function (value) {
  57326. if (this.particleEmitterType.direction1) {
  57327. this.particleEmitterType.direction1 = value;
  57328. }
  57329. },
  57330. enumerable: true,
  57331. configurable: true
  57332. });
  57333. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57334. /**
  57335. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57336. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57337. */
  57338. get: function () {
  57339. if (this.particleEmitterType.direction2) {
  57340. return this.particleEmitterType.direction2;
  57341. }
  57342. return BABYLON.Vector3.Zero();
  57343. },
  57344. set: function (value) {
  57345. if (this.particleEmitterType.direction2) {
  57346. this.particleEmitterType.direction2 = value;
  57347. }
  57348. },
  57349. enumerable: true,
  57350. configurable: true
  57351. });
  57352. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57353. /**
  57354. * 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.
  57355. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57356. */
  57357. get: function () {
  57358. if (this.particleEmitterType.minEmitBox) {
  57359. return this.particleEmitterType.minEmitBox;
  57360. }
  57361. return BABYLON.Vector3.Zero();
  57362. },
  57363. set: function (value) {
  57364. if (this.particleEmitterType.minEmitBox) {
  57365. this.particleEmitterType.minEmitBox = value;
  57366. }
  57367. },
  57368. enumerable: true,
  57369. configurable: true
  57370. });
  57371. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57372. /**
  57373. * 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.
  57374. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57375. */
  57376. get: function () {
  57377. if (this.particleEmitterType.maxEmitBox) {
  57378. return this.particleEmitterType.maxEmitBox;
  57379. }
  57380. return BABYLON.Vector3.Zero();
  57381. },
  57382. set: function (value) {
  57383. if (this.particleEmitterType.maxEmitBox) {
  57384. this.particleEmitterType.maxEmitBox = value;
  57385. }
  57386. },
  57387. enumerable: true,
  57388. configurable: true
  57389. });
  57390. /**
  57391. * Gets the maximum number of particles active at the same time.
  57392. * @returns The max number of active particles.
  57393. */
  57394. GPUParticleSystem.prototype.getCapacity = function () {
  57395. return this._capacity;
  57396. };
  57397. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57398. /**
  57399. * Gets or set the number of active particles
  57400. */
  57401. get: function () {
  57402. return this._activeCount;
  57403. },
  57404. set: function (value) {
  57405. this._activeCount = Math.min(value, this._capacity);
  57406. },
  57407. enumerable: true,
  57408. configurable: true
  57409. });
  57410. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57411. /**
  57412. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57413. */
  57414. get: function () {
  57415. return this._isAnimationSheetEnabled;
  57416. },
  57417. enumerable: true,
  57418. configurable: true
  57419. });
  57420. /**
  57421. * Is this system ready to be used/rendered
  57422. * @return true if the system is ready
  57423. */
  57424. GPUParticleSystem.prototype.isReady = function () {
  57425. if (!this._updateEffect) {
  57426. this._recreateUpdateEffect();
  57427. this._recreateRenderEffect();
  57428. return false;
  57429. }
  57430. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57431. return false;
  57432. }
  57433. return true;
  57434. };
  57435. /**
  57436. * Gets Wether the system has been started.
  57437. * @returns True if it has been started, otherwise false.
  57438. */
  57439. GPUParticleSystem.prototype.isStarted = function () {
  57440. return this._started;
  57441. };
  57442. /**
  57443. * Starts the particle system and begins to emit.
  57444. */
  57445. GPUParticleSystem.prototype.start = function () {
  57446. this._started = true;
  57447. this._stopped = false;
  57448. this._preWarmDone = false;
  57449. };
  57450. /**
  57451. * Stops the particle system.
  57452. */
  57453. GPUParticleSystem.prototype.stop = function () {
  57454. this._stopped = true;
  57455. };
  57456. /**
  57457. * Remove all active particles
  57458. */
  57459. GPUParticleSystem.prototype.reset = function () {
  57460. this._releaseBuffers();
  57461. this._releaseVAOs();
  57462. this._currentActiveCount = 0;
  57463. this._targetIndex = 0;
  57464. };
  57465. /**
  57466. * Returns the string "GPUParticleSystem"
  57467. * @returns a string containing the class name
  57468. */
  57469. GPUParticleSystem.prototype.getClassName = function () {
  57470. return "GPUParticleSystem";
  57471. };
  57472. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57473. /**
  57474. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57475. */
  57476. get: function () {
  57477. return this._isBillboardBased;
  57478. },
  57479. set: function (value) {
  57480. if (this._isBillboardBased === value) {
  57481. return;
  57482. }
  57483. this._isBillboardBased = value;
  57484. this._releaseBuffers();
  57485. },
  57486. enumerable: true,
  57487. configurable: true
  57488. });
  57489. /**
  57490. * Gets the current list of color gradients.
  57491. * You must use addColorGradient and removeColorGradient to udpate this list
  57492. * @returns the list of color gradients
  57493. */
  57494. GPUParticleSystem.prototype.getColorGradients = function () {
  57495. return this._colorGradients;
  57496. };
  57497. /**
  57498. * Gets the current list of size gradients.
  57499. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57500. * @returns the list of size gradients
  57501. */
  57502. GPUParticleSystem.prototype.getSizeGradients = function () {
  57503. return this._sizeGradients;
  57504. };
  57505. /**
  57506. * Gets the current list of angular speed gradients.
  57507. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57508. * @returns the list of angular speed gradients
  57509. */
  57510. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  57511. return this._angularSpeedGradients;
  57512. };
  57513. /**
  57514. * Gets the current list of velocity gradients.
  57515. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57516. * @returns the list of angular speed gradients
  57517. */
  57518. GPUParticleSystem.prototype.getVelocityGradients = function () {
  57519. return this._velocityGradients;
  57520. };
  57521. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  57522. if (!gradients) {
  57523. return this;
  57524. }
  57525. var index = 0;
  57526. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57527. var valueGradient = gradients_1[_i];
  57528. if (valueGradient.gradient === gradient) {
  57529. gradients.splice(index, 1);
  57530. break;
  57531. }
  57532. index++;
  57533. }
  57534. if (texture) {
  57535. texture.dispose();
  57536. }
  57537. this._releaseBuffers();
  57538. return this;
  57539. };
  57540. /**
  57541. * Adds a new color gradient
  57542. * @param gradient defines the gradient to use (between 0 and 1)
  57543. * @param color defines the color to affect to the specified gradient
  57544. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57545. * @returns the current particle system
  57546. */
  57547. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57548. if (!this._colorGradients) {
  57549. this._colorGradients = [];
  57550. }
  57551. var colorGradient = new BABYLON.ColorGradient();
  57552. colorGradient.gradient = gradient;
  57553. colorGradient.color1 = color1;
  57554. this._colorGradients.push(colorGradient);
  57555. this._colorGradients.sort(function (a, b) {
  57556. if (a.gradient < b.gradient) {
  57557. return -1;
  57558. }
  57559. else if (a.gradient > b.gradient) {
  57560. return 1;
  57561. }
  57562. return 0;
  57563. });
  57564. if (this._colorGradientsTexture) {
  57565. this._colorGradientsTexture.dispose();
  57566. this._colorGradientsTexture = null;
  57567. }
  57568. this._releaseBuffers();
  57569. return this;
  57570. };
  57571. /**
  57572. * Remove a specific color gradient
  57573. * @param gradient defines the gradient to remove
  57574. * @returns the current particle system
  57575. */
  57576. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57577. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  57578. this._colorGradientsTexture = null;
  57579. return this;
  57580. };
  57581. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  57582. var valueGradient = new BABYLON.FactorGradient();
  57583. valueGradient.gradient = gradient;
  57584. valueGradient.factor1 = factor;
  57585. factorGradients.push(valueGradient);
  57586. factorGradients.sort(function (a, b) {
  57587. if (a.gradient < b.gradient) {
  57588. return -1;
  57589. }
  57590. else if (a.gradient > b.gradient) {
  57591. return 1;
  57592. }
  57593. return 0;
  57594. });
  57595. this._releaseBuffers();
  57596. };
  57597. /**
  57598. * Adds a new size gradient
  57599. * @param gradient defines the gradient to use (between 0 and 1)
  57600. * @param factor defines the size factor to affect to the specified gradient
  57601. * @returns the current particle system
  57602. */
  57603. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57604. if (!this._sizeGradients) {
  57605. this._sizeGradients = [];
  57606. }
  57607. this._addFactorGradient(this._sizeGradients, gradient, factor);
  57608. if (this._sizeGradientsTexture) {
  57609. this._sizeGradientsTexture.dispose();
  57610. this._sizeGradientsTexture = null;
  57611. }
  57612. this._releaseBuffers();
  57613. return this;
  57614. };
  57615. /**
  57616. * Remove a specific size gradient
  57617. * @param gradient defines the gradient to remove
  57618. * @returns the current particle system
  57619. */
  57620. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57621. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  57622. this._sizeGradientsTexture = null;
  57623. return this;
  57624. };
  57625. /**
  57626. * Adds a new angular speed gradient
  57627. * @param gradient defines the gradient to use (between 0 and 1)
  57628. * @param factor defines the size factor to affect to the specified gradient
  57629. * @returns the current particle system
  57630. */
  57631. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  57632. if (!this._angularSpeedGradients) {
  57633. this._angularSpeedGradients = [];
  57634. }
  57635. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  57636. if (this._angularSpeedGradientsTexture) {
  57637. this._angularSpeedGradientsTexture.dispose();
  57638. this._angularSpeedGradientsTexture = null;
  57639. }
  57640. this._releaseBuffers();
  57641. return this;
  57642. };
  57643. /**
  57644. * Remove a specific angular speed gradient
  57645. * @param gradient defines the gradient to remove
  57646. * @returns the current particle system
  57647. */
  57648. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57649. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  57650. this._angularSpeedGradientsTexture = null;
  57651. return this;
  57652. };
  57653. /**
  57654. * Adds a new velocity gradient
  57655. * @param gradient defines the gradient to use (between 0 and 1)
  57656. * @param factor defines the size factor to affect to the specified gradient
  57657. * @returns the current particle system
  57658. */
  57659. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  57660. if (!this._velocityGradients) {
  57661. this._velocityGradients = [];
  57662. }
  57663. this._addFactorGradient(this._velocityGradients, gradient, factor);
  57664. if (this._velocityGradientsTexture) {
  57665. this._velocityGradientsTexture.dispose();
  57666. this._velocityGradientsTexture = null;
  57667. }
  57668. this._releaseBuffers();
  57669. return this;
  57670. };
  57671. /**
  57672. * Remove a specific velocity gradient
  57673. * @param gradient defines the gradient to remove
  57674. * @returns the current particle system
  57675. */
  57676. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57677. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  57678. this._velocityGradientsTexture = null;
  57679. return this;
  57680. };
  57681. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57682. var updateVertexBuffers = {};
  57683. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57684. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57685. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57686. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57687. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57688. var offset = 12;
  57689. if (!this._colorGradientsTexture) {
  57690. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57691. offset += 4;
  57692. }
  57693. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57694. offset += 3;
  57695. if (!this._isBillboardBased) {
  57696. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57697. offset += 3;
  57698. }
  57699. if (this._angularSpeedGradientsTexture) {
  57700. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  57701. offset += 1;
  57702. }
  57703. else {
  57704. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57705. offset += 2;
  57706. }
  57707. if (this._isAnimationSheetEnabled) {
  57708. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57709. offset += 1;
  57710. }
  57711. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57712. this._engine.bindArrayBuffer(null);
  57713. return vao;
  57714. };
  57715. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57716. var renderVertexBuffers = {};
  57717. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57718. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57719. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57720. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57721. var offset = 12;
  57722. if (!this._colorGradientsTexture) {
  57723. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57724. offset += 4;
  57725. }
  57726. offset += 3; // Direction
  57727. if (!this._isBillboardBased) {
  57728. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57729. offset += 3;
  57730. }
  57731. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  57732. if (this._angularSpeedGradientsTexture) {
  57733. offset++;
  57734. }
  57735. else {
  57736. offset += 2;
  57737. }
  57738. if (this._isAnimationSheetEnabled) {
  57739. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57740. offset += 1;
  57741. }
  57742. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57743. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57744. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57745. this._engine.bindArrayBuffer(null);
  57746. return vao;
  57747. };
  57748. GPUParticleSystem.prototype._initialize = function (force) {
  57749. if (force === void 0) { force = false; }
  57750. if (this._buffer0 && !force) {
  57751. return;
  57752. }
  57753. var engine = this._scene.getEngine();
  57754. var data = new Array();
  57755. if (!this.isBillboardBased) {
  57756. this._attributesStrideSize += 3;
  57757. }
  57758. if (this._colorGradientsTexture) {
  57759. this._attributesStrideSize -= 4;
  57760. }
  57761. if (this._angularSpeedGradientsTexture) {
  57762. this._attributesStrideSize -= 1;
  57763. }
  57764. if (this._isAnimationSheetEnabled) {
  57765. this._attributesStrideSize += 1;
  57766. }
  57767. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57768. // position
  57769. data.push(0.0);
  57770. data.push(0.0);
  57771. data.push(0.0);
  57772. // Age and life
  57773. data.push(0.0); // create the particle as a dead one to create a new one at start
  57774. data.push(0.0);
  57775. // Seed
  57776. data.push(Math.random());
  57777. data.push(Math.random());
  57778. data.push(Math.random());
  57779. data.push(Math.random());
  57780. // Size
  57781. data.push(0.0);
  57782. data.push(0.0);
  57783. data.push(0.0);
  57784. if (!this._colorGradientsTexture) {
  57785. // color
  57786. data.push(0.0);
  57787. data.push(0.0);
  57788. data.push(0.0);
  57789. data.push(0.0);
  57790. }
  57791. // direction
  57792. data.push(0.0);
  57793. data.push(0.0);
  57794. data.push(0.0);
  57795. if (!this.isBillboardBased) {
  57796. // initialDirection
  57797. data.push(0.0);
  57798. data.push(0.0);
  57799. data.push(0.0);
  57800. }
  57801. // angle
  57802. data.push(0.0);
  57803. if (!this._angularSpeedGradientsTexture) {
  57804. data.push(0.0);
  57805. }
  57806. if (this._isAnimationSheetEnabled) {
  57807. data.push(0.0);
  57808. }
  57809. }
  57810. // Sprite data
  57811. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57812. -0.5, 0.5, 0, 1,
  57813. -0.5, -0.5, 0, 0,
  57814. 0.5, -0.5, 1, 0]);
  57815. // Buffers
  57816. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57817. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57818. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57819. // Update VAO
  57820. this._updateVAO = [];
  57821. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57822. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57823. // Render VAO
  57824. this._renderVAO = [];
  57825. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57826. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57827. // Links
  57828. this._sourceBuffer = this._buffer0;
  57829. this._targetBuffer = this._buffer1;
  57830. };
  57831. /** @hidden */
  57832. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57833. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57834. if (this._isBillboardBased) {
  57835. defines += "\n#define BILLBOARD";
  57836. }
  57837. if (this._colorGradientsTexture) {
  57838. defines += "\n#define COLORGRADIENTS";
  57839. }
  57840. if (this._sizeGradientsTexture) {
  57841. defines += "\n#define SIZEGRADIENTS";
  57842. }
  57843. if (this._angularSpeedGradientsTexture) {
  57844. defines += "\n#define ANGULARSPEEDGRADIENTS";
  57845. }
  57846. if (this._velocityGradientsTexture) {
  57847. defines += "\n#define VELOCITYGRADIENTS";
  57848. }
  57849. if (this.isAnimationSheetEnabled) {
  57850. defines += "\n#define ANIMATESHEET";
  57851. }
  57852. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57853. return;
  57854. }
  57855. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57856. if (!this._colorGradientsTexture) {
  57857. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57858. }
  57859. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57860. if (!this._isBillboardBased) {
  57861. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57862. }
  57863. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57864. if (this.isAnimationSheetEnabled) {
  57865. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57866. }
  57867. this._updateEffectOptions.defines = defines;
  57868. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57869. };
  57870. /** @hidden */
  57871. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57872. var defines = "";
  57873. if (this._scene.clipPlane) {
  57874. defines = "\n#define CLIPPLANE";
  57875. }
  57876. if (this._isBillboardBased) {
  57877. defines += "\n#define BILLBOARD";
  57878. switch (this.billboardMode) {
  57879. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57880. defines += "\n#define BILLBOARDY";
  57881. break;
  57882. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57883. default:
  57884. break;
  57885. }
  57886. }
  57887. if (this._colorGradientsTexture) {
  57888. defines += "\n#define COLORGRADIENTS";
  57889. }
  57890. if (this.isAnimationSheetEnabled) {
  57891. defines += "\n#define ANIMATESHEET";
  57892. }
  57893. if (this._renderEffect && this._renderEffect.defines === defines) {
  57894. return;
  57895. }
  57896. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57897. };
  57898. /**
  57899. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57900. * @param preWarm defines if we are in the pre-warmimg phase
  57901. */
  57902. GPUParticleSystem.prototype.animate = function (preWarm) {
  57903. if (preWarm === void 0) { preWarm = false; }
  57904. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57905. this._actualFrame += this._timeDelta;
  57906. if (!this._stopped) {
  57907. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57908. this.stop();
  57909. }
  57910. }
  57911. };
  57912. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  57913. var texture = this[textureName];
  57914. if (!factorGradients || !factorGradients.length || texture) {
  57915. return;
  57916. }
  57917. var data = new Float32Array(this._rawTextureWidth);
  57918. for (var x = 0; x < this._rawTextureWidth; x++) {
  57919. var ratio = x / this._rawTextureWidth;
  57920. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  57921. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57922. });
  57923. }
  57924. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57925. };
  57926. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57927. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  57928. };
  57929. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  57930. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  57931. };
  57932. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  57933. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  57934. };
  57935. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57936. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57937. return;
  57938. }
  57939. var data = new Uint8Array(this._rawTextureWidth * 4);
  57940. var tmpColor = BABYLON.Tmp.Color4[0];
  57941. for (var x = 0; x < this._rawTextureWidth; x++) {
  57942. var ratio = x / this._rawTextureWidth;
  57943. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57944. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57945. data[x * 4] = tmpColor.r * 255;
  57946. data[x * 4 + 1] = tmpColor.g * 255;
  57947. data[x * 4 + 2] = tmpColor.b * 255;
  57948. data[x * 4 + 3] = tmpColor.a * 255;
  57949. });
  57950. }
  57951. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57952. };
  57953. /**
  57954. * Renders the particle system in its current state
  57955. * @param preWarm defines if the system should only update the particles but not render them
  57956. * @returns the current number of particles
  57957. */
  57958. GPUParticleSystem.prototype.render = function (preWarm) {
  57959. if (preWarm === void 0) { preWarm = false; }
  57960. if (!this._started) {
  57961. return 0;
  57962. }
  57963. this._createColorGradientTexture();
  57964. this._createSizeGradientTexture();
  57965. this._createAngularSpeedGradientTexture();
  57966. this._createVelocityGradientTexture();
  57967. this._recreateUpdateEffect();
  57968. this._recreateRenderEffect();
  57969. if (!this.isReady()) {
  57970. return 0;
  57971. }
  57972. if (!preWarm) {
  57973. if (!this._preWarmDone && this.preWarmCycles) {
  57974. for (var index = 0; index < this.preWarmCycles; index++) {
  57975. this.animate(true);
  57976. this.render(true);
  57977. }
  57978. this._preWarmDone = true;
  57979. }
  57980. if (this._currentRenderId === this._scene.getRenderId()) {
  57981. return 0;
  57982. }
  57983. this._currentRenderId = this._scene.getRenderId();
  57984. }
  57985. // Get everything ready to render
  57986. this._initialize();
  57987. this._accumulatedCount += this.emitRate * this._timeDelta;
  57988. if (this._accumulatedCount > 1) {
  57989. var intPart = this._accumulatedCount | 0;
  57990. this._accumulatedCount -= intPart;
  57991. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57992. }
  57993. if (!this._currentActiveCount) {
  57994. return 0;
  57995. }
  57996. // Enable update effect
  57997. this._engine.enableEffect(this._updateEffect);
  57998. this._engine.setState(false);
  57999. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58000. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58001. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58002. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58003. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  58004. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58005. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58006. if (!this._colorGradientsTexture) {
  58007. this._updateEffect.setDirectColor4("color1", this.color1);
  58008. this._updateEffect.setDirectColor4("color2", this.color2);
  58009. }
  58010. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58011. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  58012. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  58013. this._updateEffect.setVector3("gravity", this.gravity);
  58014. if (this._sizeGradientsTexture) {
  58015. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  58016. }
  58017. if (this._angularSpeedGradientsTexture) {
  58018. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  58019. }
  58020. if (this._velocityGradientsTexture) {
  58021. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  58022. }
  58023. if (this.particleEmitterType) {
  58024. this.particleEmitterType.applyToShader(this._updateEffect);
  58025. }
  58026. if (this._isAnimationSheetEnabled) {
  58027. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  58028. }
  58029. var emitterWM;
  58030. if (this.emitter.position) {
  58031. var emitterMesh = this.emitter;
  58032. emitterWM = emitterMesh.getWorldMatrix();
  58033. }
  58034. else {
  58035. var emitterPosition = this.emitter;
  58036. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58037. }
  58038. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58039. // Bind source VAO
  58040. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58041. // Update
  58042. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58043. this._engine.setRasterizerState(false);
  58044. this._engine.beginTransformFeedback();
  58045. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58046. this._engine.endTransformFeedback();
  58047. this._engine.setRasterizerState(true);
  58048. this._engine.bindTransformFeedbackBuffer(null);
  58049. if (!preWarm) {
  58050. // Enable render effect
  58051. this._engine.enableEffect(this._renderEffect);
  58052. var viewMatrix = this._scene.getViewMatrix();
  58053. this._renderEffect.setMatrix("view", viewMatrix);
  58054. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58055. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58056. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  58057. if (this._colorGradientsTexture) {
  58058. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  58059. }
  58060. else {
  58061. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58062. }
  58063. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58064. var baseSize = this.particleTexture.getBaseSize();
  58065. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58066. }
  58067. if (this._isBillboardBased) {
  58068. var camera = this._scene.activeCamera;
  58069. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  58070. }
  58071. if (this._scene.clipPlane) {
  58072. var clipPlane = this._scene.clipPlane;
  58073. var invView = viewMatrix.clone();
  58074. invView.invert();
  58075. this._renderEffect.setMatrix("invView", invView);
  58076. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58077. }
  58078. // Draw order
  58079. switch (this.blendMode) {
  58080. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  58081. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58082. break;
  58083. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  58084. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58085. break;
  58086. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  58087. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58088. break;
  58089. }
  58090. if (this.forceDepthWrite) {
  58091. this._engine.setDepthWrite(true);
  58092. }
  58093. // Bind source VAO
  58094. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58095. // Render
  58096. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58097. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58098. }
  58099. // Switch VAOs
  58100. this._targetIndex++;
  58101. if (this._targetIndex === 2) {
  58102. this._targetIndex = 0;
  58103. }
  58104. // Switch buffers
  58105. var tmpBuffer = this._sourceBuffer;
  58106. this._sourceBuffer = this._targetBuffer;
  58107. this._targetBuffer = tmpBuffer;
  58108. return this._currentActiveCount;
  58109. };
  58110. /**
  58111. * Rebuilds the particle system
  58112. */
  58113. GPUParticleSystem.prototype.rebuild = function () {
  58114. this._initialize(true);
  58115. };
  58116. GPUParticleSystem.prototype._releaseBuffers = function () {
  58117. if (this._buffer0) {
  58118. this._buffer0.dispose();
  58119. this._buffer0 = null;
  58120. }
  58121. if (this._buffer1) {
  58122. this._buffer1.dispose();
  58123. this._buffer1 = null;
  58124. }
  58125. if (this._spriteBuffer) {
  58126. this._spriteBuffer.dispose();
  58127. this._spriteBuffer = null;
  58128. }
  58129. };
  58130. GPUParticleSystem.prototype._releaseVAOs = function () {
  58131. if (!this._updateVAO) {
  58132. return;
  58133. }
  58134. for (var index = 0; index < this._updateVAO.length; index++) {
  58135. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58136. }
  58137. this._updateVAO = [];
  58138. for (var index = 0; index < this._renderVAO.length; index++) {
  58139. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58140. }
  58141. this._renderVAO = [];
  58142. };
  58143. /**
  58144. * Disposes the particle system and free the associated resources
  58145. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58146. */
  58147. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58148. if (disposeTexture === void 0) { disposeTexture = true; }
  58149. var index = this._scene.particleSystems.indexOf(this);
  58150. if (index > -1) {
  58151. this._scene.particleSystems.splice(index, 1);
  58152. }
  58153. this._releaseBuffers();
  58154. this._releaseVAOs();
  58155. if (this._colorGradientsTexture) {
  58156. this._colorGradientsTexture.dispose();
  58157. this._colorGradientsTexture = null;
  58158. }
  58159. if (this._sizeGradientsTexture) {
  58160. this._sizeGradientsTexture.dispose();
  58161. this._sizeGradientsTexture = null;
  58162. }
  58163. if (this._angularSpeedGradientsTexture) {
  58164. this._angularSpeedGradientsTexture.dispose();
  58165. this._angularSpeedGradientsTexture = null;
  58166. }
  58167. if (this._velocityGradientsTexture) {
  58168. this._velocityGradientsTexture.dispose();
  58169. this._velocityGradientsTexture = null;
  58170. }
  58171. if (this._randomTexture) {
  58172. this._randomTexture.dispose();
  58173. this._randomTexture = null;
  58174. }
  58175. if (this._randomTexture2) {
  58176. this._randomTexture2.dispose();
  58177. this._randomTexture2 = null;
  58178. }
  58179. if (disposeTexture && this.particleTexture) {
  58180. this.particleTexture.dispose();
  58181. this.particleTexture = null;
  58182. }
  58183. // Callback
  58184. this.onDisposeObservable.notifyObservers(this);
  58185. this.onDisposeObservable.clear();
  58186. };
  58187. /**
  58188. * Clones the particle system.
  58189. * @param name The name of the cloned object
  58190. * @param newEmitter The new emitter to use
  58191. * @returns the cloned particle system
  58192. */
  58193. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58194. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58195. BABYLON.Tools.DeepCopy(this, result);
  58196. if (newEmitter === undefined) {
  58197. newEmitter = this.emitter;
  58198. }
  58199. result.emitter = newEmitter;
  58200. if (this.particleTexture) {
  58201. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58202. }
  58203. return result;
  58204. };
  58205. /**
  58206. * Serializes the particle system to a JSON object.
  58207. * @returns the JSON object
  58208. */
  58209. GPUParticleSystem.prototype.serialize = function () {
  58210. var serializationObject = {};
  58211. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  58212. serializationObject.activeParticleCount = this.activeParticleCount;
  58213. return serializationObject;
  58214. };
  58215. /**
  58216. * Parses a JSON object to create a GPU particle system.
  58217. * @param parsedParticleSystem The JSON object to parse
  58218. * @param scene The scene to create the particle system in
  58219. * @param rootUrl The root url to use to load external dependencies like texture
  58220. * @returns the parsed GPU particle system
  58221. */
  58222. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58223. var name = parsedParticleSystem.name;
  58224. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58225. if (parsedParticleSystem.activeParticleCount) {
  58226. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58227. }
  58228. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58229. return particleSystem;
  58230. };
  58231. return GPUParticleSystem;
  58232. }());
  58233. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58234. })(BABYLON || (BABYLON = {}));
  58235. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58236. var BABYLON;
  58237. (function (BABYLON) {
  58238. /**
  58239. * Represents one particle of a solid particle system.
  58240. */
  58241. var SolidParticle = /** @class */ (function () {
  58242. /**
  58243. * Creates a Solid Particle object.
  58244. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58245. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58246. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58247. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58248. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58249. * @param shapeId (integer) is the model shape identifier in the SPS.
  58250. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58251. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58252. */
  58253. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58254. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58255. /**
  58256. * particle global index
  58257. */
  58258. this.idx = 0;
  58259. /**
  58260. * The color of the particle
  58261. */
  58262. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58263. /**
  58264. * The world space position of the particle.
  58265. */
  58266. this.position = BABYLON.Vector3.Zero();
  58267. /**
  58268. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58269. */
  58270. this.rotation = BABYLON.Vector3.Zero();
  58271. /**
  58272. * The scaling of the particle.
  58273. */
  58274. this.scaling = BABYLON.Vector3.One();
  58275. /**
  58276. * The uvs of the particle.
  58277. */
  58278. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58279. /**
  58280. * The current speed of the particle.
  58281. */
  58282. this.velocity = BABYLON.Vector3.Zero();
  58283. /**
  58284. * The pivot point in the particle local space.
  58285. */
  58286. this.pivot = BABYLON.Vector3.Zero();
  58287. /**
  58288. * Must the particle be translated from its pivot point in its local space ?
  58289. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58290. * Default : false
  58291. */
  58292. this.translateFromPivot = false;
  58293. /**
  58294. * Is the particle active or not ?
  58295. */
  58296. this.alive = true;
  58297. /**
  58298. * Is the particle visible or not ?
  58299. */
  58300. this.isVisible = true;
  58301. /**
  58302. * Index of this particle in the global "positions" array (Internal use)
  58303. */
  58304. this._pos = 0;
  58305. /**
  58306. * Index of this particle in the global "indices" array (Internal use)
  58307. */
  58308. this._ind = 0;
  58309. /**
  58310. * ModelShape id of this particle
  58311. */
  58312. this.shapeId = 0;
  58313. /**
  58314. * Index of the particle in its shape id (Internal use)
  58315. */
  58316. this.idxInShape = 0;
  58317. /**
  58318. * Still set as invisible in order to skip useless computations (Internal use)
  58319. */
  58320. this._stillInvisible = false;
  58321. /**
  58322. * Last computed particle rotation matrix
  58323. */
  58324. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58325. /**
  58326. * Parent particle Id, if any.
  58327. * Default null.
  58328. */
  58329. this.parentId = null;
  58330. /**
  58331. * Internal global position in the SPS.
  58332. */
  58333. this._globalPosition = BABYLON.Vector3.Zero();
  58334. this.idx = particleIndex;
  58335. this._pos = positionIndex;
  58336. this._ind = indiceIndex;
  58337. this._model = model;
  58338. this.shapeId = shapeId;
  58339. this.idxInShape = idxInShape;
  58340. this._sps = sps;
  58341. if (modelBoundingInfo) {
  58342. this._modelBoundingInfo = modelBoundingInfo;
  58343. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58344. }
  58345. }
  58346. Object.defineProperty(SolidParticle.prototype, "scale", {
  58347. /**
  58348. * Legacy support, changed scale to scaling
  58349. */
  58350. get: function () {
  58351. return this.scaling;
  58352. },
  58353. /**
  58354. * Legacy support, changed scale to scaling
  58355. */
  58356. set: function (scale) {
  58357. this.scaling = scale;
  58358. },
  58359. enumerable: true,
  58360. configurable: true
  58361. });
  58362. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58363. /**
  58364. * Legacy support, changed quaternion to rotationQuaternion
  58365. */
  58366. get: function () {
  58367. return this.rotationQuaternion;
  58368. },
  58369. /**
  58370. * Legacy support, changed quaternion to rotationQuaternion
  58371. */
  58372. set: function (q) {
  58373. this.rotationQuaternion = q;
  58374. },
  58375. enumerable: true,
  58376. configurable: true
  58377. });
  58378. /**
  58379. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58380. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58381. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58382. * @returns true if it intersects
  58383. */
  58384. SolidParticle.prototype.intersectsMesh = function (target) {
  58385. if (!this._boundingInfo || !target._boundingInfo) {
  58386. return false;
  58387. }
  58388. if (this._sps._bSphereOnly) {
  58389. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58390. }
  58391. return this._boundingInfo.intersects(target._boundingInfo, false);
  58392. };
  58393. return SolidParticle;
  58394. }());
  58395. BABYLON.SolidParticle = SolidParticle;
  58396. /**
  58397. * Represents the shape of the model used by one particle of a solid particle system.
  58398. * SPS internal tool, don't use it manually.
  58399. */
  58400. var ModelShape = /** @class */ (function () {
  58401. /**
  58402. * 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.
  58403. * SPS internal tool, don't use it manually.
  58404. * @hidden
  58405. */
  58406. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58407. /**
  58408. * length of the shape in the model indices array (internal use)
  58409. */
  58410. this._indicesLength = 0;
  58411. this.shapeID = id;
  58412. this._shape = shape;
  58413. this._indicesLength = indicesLength;
  58414. this._shapeUV = shapeUV;
  58415. this._positionFunction = posFunction;
  58416. this._vertexFunction = vtxFunction;
  58417. }
  58418. return ModelShape;
  58419. }());
  58420. BABYLON.ModelShape = ModelShape;
  58421. /**
  58422. * Represents a Depth Sorted Particle in the solid particle system.
  58423. */
  58424. var DepthSortedParticle = /** @class */ (function () {
  58425. function DepthSortedParticle() {
  58426. /**
  58427. * Index of the particle in the "indices" array
  58428. */
  58429. this.ind = 0;
  58430. /**
  58431. * Length of the particle shape in the "indices" array
  58432. */
  58433. this.indicesLength = 0;
  58434. /**
  58435. * Squared distance from the particle to the camera
  58436. */
  58437. this.sqDistance = 0.0;
  58438. }
  58439. return DepthSortedParticle;
  58440. }());
  58441. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58442. })(BABYLON || (BABYLON = {}));
  58443. //# sourceMappingURL=babylon.solidParticle.js.map
  58444. var BABYLON;
  58445. (function (BABYLON) {
  58446. /**
  58447. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58448. *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.
  58449. * The SPS is also a particle system. It provides some methods to manage the particles.
  58450. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58451. *
  58452. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58453. */
  58454. var SolidParticleSystem = /** @class */ (function () {
  58455. /**
  58456. * Creates a SPS (Solid Particle System) object.
  58457. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58458. * @param scene (Scene) is the scene in which the SPS is added.
  58459. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58460. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58461. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58462. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58463. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58464. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58465. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58466. */
  58467. function SolidParticleSystem(name, scene, options) {
  58468. /**
  58469. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58470. * Example : var p = SPS.particles[i];
  58471. */
  58472. this.particles = new Array();
  58473. /**
  58474. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58475. */
  58476. this.nbParticles = 0;
  58477. /**
  58478. * If the particles must ever face the camera (default false). Useful for planar particles.
  58479. */
  58480. this.billboard = false;
  58481. /**
  58482. * Recompute normals when adding a shape
  58483. */
  58484. this.recomputeNormals = true;
  58485. /**
  58486. * This a counter ofr your own usage. It's not set by any SPS functions.
  58487. */
  58488. this.counter = 0;
  58489. /**
  58490. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58491. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58492. */
  58493. this.vars = {};
  58494. /**
  58495. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58496. */
  58497. this._bSphereOnly = false;
  58498. /**
  58499. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58500. */
  58501. this._bSphereRadiusFactor = 1.0;
  58502. this._positions = new Array();
  58503. this._indices = new Array();
  58504. this._normals = new Array();
  58505. this._colors = new Array();
  58506. this._uvs = new Array();
  58507. this._index = 0; // indices index
  58508. this._updatable = true;
  58509. this._pickable = false;
  58510. this._isVisibilityBoxLocked = false;
  58511. this._alwaysVisible = false;
  58512. this._depthSort = false;
  58513. this._shapeCounter = 0;
  58514. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58515. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58516. this._computeParticleColor = true;
  58517. this._computeParticleTexture = true;
  58518. this._computeParticleRotation = true;
  58519. this._computeParticleVertex = false;
  58520. this._computeBoundingBox = false;
  58521. this._depthSortParticles = true;
  58522. this._cam_axisZ = BABYLON.Vector3.Zero();
  58523. this._cam_axisY = BABYLON.Vector3.Zero();
  58524. this._cam_axisX = BABYLON.Vector3.Zero();
  58525. this._axisZ = BABYLON.Axis.Z;
  58526. this._camDir = BABYLON.Vector3.Zero();
  58527. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58528. this._rotMatrix = new BABYLON.Matrix();
  58529. this._invertMatrix = new BABYLON.Matrix();
  58530. this._rotated = BABYLON.Vector3.Zero();
  58531. this._quaternion = new BABYLON.Quaternion();
  58532. this._vertex = BABYLON.Vector3.Zero();
  58533. this._normal = BABYLON.Vector3.Zero();
  58534. this._yaw = 0.0;
  58535. this._pitch = 0.0;
  58536. this._roll = 0.0;
  58537. this._halfroll = 0.0;
  58538. this._halfpitch = 0.0;
  58539. this._halfyaw = 0.0;
  58540. this._sinRoll = 0.0;
  58541. this._cosRoll = 0.0;
  58542. this._sinPitch = 0.0;
  58543. this._cosPitch = 0.0;
  58544. this._sinYaw = 0.0;
  58545. this._cosYaw = 0.0;
  58546. this._mustUnrotateFixedNormals = false;
  58547. this._minimum = BABYLON.Vector3.Zero();
  58548. this._maximum = BABYLON.Vector3.Zero();
  58549. this._minBbox = BABYLON.Vector3.Zero();
  58550. this._maxBbox = BABYLON.Vector3.Zero();
  58551. this._particlesIntersect = false;
  58552. this._depthSortFunction = function (p1, p2) {
  58553. return (p2.sqDistance - p1.sqDistance);
  58554. };
  58555. this._needs32Bits = false;
  58556. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58557. this._scaledPivot = BABYLON.Vector3.Zero();
  58558. this._particleHasParent = false;
  58559. this.name = name;
  58560. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58561. this._camera = scene.activeCamera;
  58562. this._pickable = options ? options.isPickable : false;
  58563. this._depthSort = options ? options.enableDepthSort : false;
  58564. this._particlesIntersect = options ? options.particleIntersection : false;
  58565. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58566. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58567. if (options && options.updatable !== undefined) {
  58568. this._updatable = options.updatable;
  58569. }
  58570. else {
  58571. this._updatable = true;
  58572. }
  58573. if (this._pickable) {
  58574. this.pickedParticles = [];
  58575. }
  58576. if (this._depthSort) {
  58577. this.depthSortedParticles = [];
  58578. }
  58579. }
  58580. /**
  58581. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58582. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58583. * @returns the created mesh
  58584. */
  58585. SolidParticleSystem.prototype.buildMesh = function () {
  58586. if (this.nbParticles === 0) {
  58587. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58588. this.addShape(triangle, 1);
  58589. triangle.dispose();
  58590. }
  58591. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58592. this._positions32 = new Float32Array(this._positions);
  58593. this._uvs32 = new Float32Array(this._uvs);
  58594. this._colors32 = new Float32Array(this._colors);
  58595. if (this.recomputeNormals) {
  58596. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58597. }
  58598. this._normals32 = new Float32Array(this._normals);
  58599. this._fixedNormal32 = new Float32Array(this._normals);
  58600. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58601. this._unrotateFixedNormals();
  58602. }
  58603. var vertexData = new BABYLON.VertexData();
  58604. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58605. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58606. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58607. if (this._uvs32.length > 0) {
  58608. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58609. }
  58610. if (this._colors32.length > 0) {
  58611. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58612. }
  58613. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58614. vertexData.applyToMesh(mesh, this._updatable);
  58615. this.mesh = mesh;
  58616. this.mesh.isPickable = this._pickable;
  58617. // free memory
  58618. if (!this._depthSort) {
  58619. this._indices = null;
  58620. }
  58621. this._positions = null;
  58622. this._normals = null;
  58623. this._uvs = null;
  58624. this._colors = null;
  58625. if (!this._updatable) {
  58626. this.particles.length = 0;
  58627. }
  58628. return mesh;
  58629. };
  58630. /**
  58631. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58632. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58633. * Thus the particles generated from `digest()` have their property `position` set yet.
  58634. * @param mesh ( Mesh ) is the mesh to be digested
  58635. * @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
  58636. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58637. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58638. * @returns the current SPS
  58639. */
  58640. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58641. var size = (options && options.facetNb) || 1;
  58642. var number = (options && options.number) || 0;
  58643. var delta = (options && options.delta) || 0;
  58644. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58645. var meshInd = mesh.getIndices();
  58646. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58647. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58648. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58649. var f = 0; // facet counter
  58650. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58651. // compute size from number
  58652. if (number) {
  58653. number = (number > totalFacets) ? totalFacets : number;
  58654. size = Math.round(totalFacets / number);
  58655. delta = 0;
  58656. }
  58657. else {
  58658. size = (size > totalFacets) ? totalFacets : size;
  58659. }
  58660. var facetPos = []; // submesh positions
  58661. var facetInd = []; // submesh indices
  58662. var facetUV = []; // submesh UV
  58663. var facetCol = []; // submesh colors
  58664. var barycenter = BABYLON.Vector3.Zero();
  58665. var sizeO = size;
  58666. while (f < totalFacets) {
  58667. size = sizeO + Math.floor((1 + delta) * Math.random());
  58668. if (f > totalFacets - size) {
  58669. size = totalFacets - f;
  58670. }
  58671. // reset temp arrays
  58672. facetPos.length = 0;
  58673. facetInd.length = 0;
  58674. facetUV.length = 0;
  58675. facetCol.length = 0;
  58676. // iterate over "size" facets
  58677. var fi = 0;
  58678. for (var j = f * 3; j < (f + size) * 3; j++) {
  58679. facetInd.push(fi);
  58680. var i = meshInd[j];
  58681. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58682. if (meshUV) {
  58683. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58684. }
  58685. if (meshCol) {
  58686. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58687. }
  58688. fi++;
  58689. }
  58690. // create a model shape for each single particle
  58691. var idx = this.nbParticles;
  58692. var shape = this._posToShape(facetPos);
  58693. var shapeUV = this._uvsToShapeUV(facetUV);
  58694. // compute the barycenter of the shape
  58695. var v;
  58696. for (v = 0; v < shape.length; v++) {
  58697. barycenter.addInPlace(shape[v]);
  58698. }
  58699. barycenter.scaleInPlace(1 / shape.length);
  58700. // shift the shape from its barycenter to the origin
  58701. for (v = 0; v < shape.length; v++) {
  58702. shape[v].subtractInPlace(barycenter);
  58703. }
  58704. var bInfo;
  58705. if (this._particlesIntersect) {
  58706. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58707. }
  58708. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58709. // add the particle in the SPS
  58710. var currentPos = this._positions.length;
  58711. var currentInd = this._indices.length;
  58712. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58713. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58714. // initialize the particle position
  58715. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58716. this._index += shape.length;
  58717. idx++;
  58718. this.nbParticles++;
  58719. this._shapeCounter++;
  58720. f += size;
  58721. }
  58722. return this;
  58723. };
  58724. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58725. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58726. var index = 0;
  58727. var idx = 0;
  58728. for (var p = 0; p < this.particles.length; p++) {
  58729. this._particle = this.particles[p];
  58730. this._shape = this._particle._model._shape;
  58731. if (this._particle.rotationQuaternion) {
  58732. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58733. }
  58734. else {
  58735. this._yaw = this._particle.rotation.y;
  58736. this._pitch = this._particle.rotation.x;
  58737. this._roll = this._particle.rotation.z;
  58738. this._quaternionRotationYPR();
  58739. }
  58740. this._quaternionToRotationMatrix();
  58741. this._rotMatrix.invertToRef(this._invertMatrix);
  58742. for (var pt = 0; pt < this._shape.length; pt++) {
  58743. idx = index + pt * 3;
  58744. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58745. this._fixedNormal32[idx] = this._normal.x;
  58746. this._fixedNormal32[idx + 1] = this._normal.y;
  58747. this._fixedNormal32[idx + 2] = this._normal.z;
  58748. }
  58749. index = idx + 3;
  58750. }
  58751. };
  58752. //reset copy
  58753. SolidParticleSystem.prototype._resetCopy = function () {
  58754. this._copy.position.x = 0;
  58755. this._copy.position.y = 0;
  58756. this._copy.position.z = 0;
  58757. this._copy.rotation.x = 0;
  58758. this._copy.rotation.y = 0;
  58759. this._copy.rotation.z = 0;
  58760. this._copy.rotationQuaternion = null;
  58761. this._copy.scaling.x = 1.0;
  58762. this._copy.scaling.y = 1.0;
  58763. this._copy.scaling.z = 1.0;
  58764. this._copy.uvs.x = 0;
  58765. this._copy.uvs.y = 0;
  58766. this._copy.uvs.z = 1.0;
  58767. this._copy.uvs.w = 1.0;
  58768. this._copy.color = null;
  58769. this._copy.translateFromPivot = false;
  58770. };
  58771. // _meshBuilder : inserts the shape model in the global SPS mesh
  58772. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58773. var i;
  58774. var u = 0;
  58775. var c = 0;
  58776. var n = 0;
  58777. this._resetCopy();
  58778. if (options && options.positionFunction) { // call to custom positionFunction
  58779. options.positionFunction(this._copy, idx, idxInShape);
  58780. this._mustUnrotateFixedNormals = true;
  58781. }
  58782. if (this._copy.rotationQuaternion) {
  58783. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58784. }
  58785. else {
  58786. this._yaw = this._copy.rotation.y;
  58787. this._pitch = this._copy.rotation.x;
  58788. this._roll = this._copy.rotation.z;
  58789. this._quaternionRotationYPR();
  58790. }
  58791. this._quaternionToRotationMatrix();
  58792. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58793. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58794. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58795. if (this._copy.translateFromPivot) {
  58796. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58797. }
  58798. else {
  58799. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58800. }
  58801. for (i = 0; i < shape.length; i++) {
  58802. this._vertex.x = shape[i].x;
  58803. this._vertex.y = shape[i].y;
  58804. this._vertex.z = shape[i].z;
  58805. if (options && options.vertexFunction) {
  58806. options.vertexFunction(this._copy, this._vertex, i);
  58807. }
  58808. this._vertex.x *= this._copy.scaling.x;
  58809. this._vertex.y *= this._copy.scaling.y;
  58810. this._vertex.z *= this._copy.scaling.z;
  58811. this._vertex.x -= this._scaledPivot.x;
  58812. this._vertex.y -= this._scaledPivot.y;
  58813. this._vertex.z -= this._scaledPivot.z;
  58814. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58815. this._rotated.addInPlace(this._pivotBackTranslation);
  58816. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58817. if (meshUV) {
  58818. 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);
  58819. u += 2;
  58820. }
  58821. if (this._copy.color) {
  58822. this._color = this._copy.color;
  58823. }
  58824. else if (meshCol && meshCol[c] !== undefined) {
  58825. this._color.r = meshCol[c];
  58826. this._color.g = meshCol[c + 1];
  58827. this._color.b = meshCol[c + 2];
  58828. this._color.a = meshCol[c + 3];
  58829. }
  58830. else {
  58831. this._color.r = 1.0;
  58832. this._color.g = 1.0;
  58833. this._color.b = 1.0;
  58834. this._color.a = 1.0;
  58835. }
  58836. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58837. c += 4;
  58838. if (!this.recomputeNormals && meshNor) {
  58839. this._normal.x = meshNor[n];
  58840. this._normal.y = meshNor[n + 1];
  58841. this._normal.z = meshNor[n + 2];
  58842. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58843. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58844. n += 3;
  58845. }
  58846. }
  58847. for (i = 0; i < meshInd.length; i++) {
  58848. var current_ind = p + meshInd[i];
  58849. indices.push(current_ind);
  58850. if (current_ind > 65535) {
  58851. this._needs32Bits = true;
  58852. }
  58853. }
  58854. if (this._pickable) {
  58855. var nbfaces = meshInd.length / 3;
  58856. for (i = 0; i < nbfaces; i++) {
  58857. this.pickedParticles.push({ idx: idx, faceId: i });
  58858. }
  58859. }
  58860. if (this._depthSort) {
  58861. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58862. }
  58863. return this._copy;
  58864. };
  58865. // returns a shape array from positions array
  58866. SolidParticleSystem.prototype._posToShape = function (positions) {
  58867. var shape = [];
  58868. for (var i = 0; i < positions.length; i += 3) {
  58869. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58870. }
  58871. return shape;
  58872. };
  58873. // returns a shapeUV array from a Vector4 uvs
  58874. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58875. var shapeUV = [];
  58876. if (uvs) {
  58877. for (var i = 0; i < uvs.length; i++)
  58878. shapeUV.push(uvs[i]);
  58879. }
  58880. return shapeUV;
  58881. };
  58882. // adds a new particle object in the particles array
  58883. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58884. if (bInfo === void 0) { bInfo = null; }
  58885. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58886. this.particles.push(sp);
  58887. return sp;
  58888. };
  58889. /**
  58890. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58891. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58892. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58893. * @param nb (positive integer) the number of particles to be created from this model
  58894. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58895. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58896. * @returns the number of shapes in the system
  58897. */
  58898. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58899. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58900. var meshInd = mesh.getIndices();
  58901. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58902. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58903. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58904. var bbInfo;
  58905. if (this._particlesIntersect) {
  58906. bbInfo = mesh.getBoundingInfo();
  58907. }
  58908. var shape = this._posToShape(meshPos);
  58909. var shapeUV = this._uvsToShapeUV(meshUV);
  58910. var posfunc = options ? options.positionFunction : null;
  58911. var vtxfunc = options ? options.vertexFunction : null;
  58912. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58913. // particles
  58914. var sp;
  58915. var currentCopy;
  58916. var idx = this.nbParticles;
  58917. for (var i = 0; i < nb; i++) {
  58918. var currentPos = this._positions.length;
  58919. var currentInd = this._indices.length;
  58920. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58921. if (this._updatable) {
  58922. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58923. sp.position.copyFrom(currentCopy.position);
  58924. sp.rotation.copyFrom(currentCopy.rotation);
  58925. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58926. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58927. }
  58928. if (currentCopy.color && sp.color) {
  58929. sp.color.copyFrom(currentCopy.color);
  58930. }
  58931. sp.scaling.copyFrom(currentCopy.scaling);
  58932. sp.uvs.copyFrom(currentCopy.uvs);
  58933. }
  58934. this._index += shape.length;
  58935. idx++;
  58936. }
  58937. this.nbParticles += nb;
  58938. this._shapeCounter++;
  58939. return this._shapeCounter - 1;
  58940. };
  58941. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58942. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58943. this._resetCopy();
  58944. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58945. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58946. }
  58947. if (this._copy.rotationQuaternion) {
  58948. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58949. }
  58950. else {
  58951. this._yaw = this._copy.rotation.y;
  58952. this._pitch = this._copy.rotation.x;
  58953. this._roll = this._copy.rotation.z;
  58954. this._quaternionRotationYPR();
  58955. }
  58956. this._quaternionToRotationMatrix();
  58957. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58958. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58959. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58960. if (this._copy.translateFromPivot) {
  58961. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58962. }
  58963. else {
  58964. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58965. }
  58966. this._shape = particle._model._shape;
  58967. for (var pt = 0; pt < this._shape.length; pt++) {
  58968. this._vertex.x = this._shape[pt].x;
  58969. this._vertex.y = this._shape[pt].y;
  58970. this._vertex.z = this._shape[pt].z;
  58971. if (particle._model._vertexFunction) {
  58972. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58973. }
  58974. this._vertex.x *= this._copy.scaling.x;
  58975. this._vertex.y *= this._copy.scaling.y;
  58976. this._vertex.z *= this._copy.scaling.z;
  58977. this._vertex.x -= this._scaledPivot.x;
  58978. this._vertex.y -= this._scaledPivot.y;
  58979. this._vertex.z -= this._scaledPivot.z;
  58980. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58981. this._rotated.addInPlace(this._pivotBackTranslation);
  58982. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58983. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58984. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58985. }
  58986. particle.position.x = 0.0;
  58987. particle.position.y = 0.0;
  58988. particle.position.z = 0.0;
  58989. particle.rotation.x = 0.0;
  58990. particle.rotation.y = 0.0;
  58991. particle.rotation.z = 0.0;
  58992. particle.rotationQuaternion = null;
  58993. particle.scaling.x = 1.0;
  58994. particle.scaling.y = 1.0;
  58995. particle.scaling.z = 1.0;
  58996. particle.uvs.x = 0.0;
  58997. particle.uvs.y = 0.0;
  58998. particle.uvs.z = 1.0;
  58999. particle.uvs.w = 1.0;
  59000. particle.pivot.x = 0.0;
  59001. particle.pivot.y = 0.0;
  59002. particle.pivot.z = 0.0;
  59003. particle.translateFromPivot = false;
  59004. particle.parentId = null;
  59005. };
  59006. /**
  59007. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59008. * @returns the SPS.
  59009. */
  59010. SolidParticleSystem.prototype.rebuildMesh = function () {
  59011. for (var p = 0; p < this.particles.length; p++) {
  59012. this._rebuildParticle(this.particles[p]);
  59013. }
  59014. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59015. return this;
  59016. };
  59017. /**
  59018. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59019. * This method calls `updateParticle()` for each particle of the SPS.
  59020. * For an animated SPS, it is usually called within the render loop.
  59021. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59022. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59023. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59024. * @returns the SPS.
  59025. */
  59026. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59027. if (start === void 0) { start = 0; }
  59028. if (end === void 0) { end = this.nbParticles - 1; }
  59029. if (update === void 0) { update = true; }
  59030. if (!this._updatable) {
  59031. return this;
  59032. }
  59033. // custom beforeUpdate
  59034. this.beforeUpdateParticles(start, end, update);
  59035. this._cam_axisX.x = 1.0;
  59036. this._cam_axisX.y = 0.0;
  59037. this._cam_axisX.z = 0.0;
  59038. this._cam_axisY.x = 0.0;
  59039. this._cam_axisY.y = 1.0;
  59040. this._cam_axisY.z = 0.0;
  59041. this._cam_axisZ.x = 0.0;
  59042. this._cam_axisZ.y = 0.0;
  59043. this._cam_axisZ.z = 1.0;
  59044. // cases when the World Matrix is to be computed first
  59045. if (this.billboard || this._depthSort) {
  59046. this.mesh.computeWorldMatrix(true);
  59047. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59048. }
  59049. // if the particles will always face the camera
  59050. if (this.billboard) {
  59051. // compute the camera position and un-rotate it by the current mesh rotation
  59052. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59053. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59054. this._cam_axisZ.normalize();
  59055. // same for camera up vector extracted from the cam view matrix
  59056. var view = this._camera.getViewMatrix(true);
  59057. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59058. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59059. this._cam_axisY.normalize();
  59060. this._cam_axisX.normalize();
  59061. }
  59062. // if depthSort, compute the camera global position in the mesh local system
  59063. if (this._depthSort) {
  59064. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59065. }
  59066. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59067. var idx = 0; // current position index in the global array positions32
  59068. var index = 0; // position start index in the global array positions32 of the current particle
  59069. var colidx = 0; // current color index in the global array colors32
  59070. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59071. var uvidx = 0; // current uv index in the global array uvs32
  59072. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59073. var pt = 0; // current index in the particle model shape
  59074. if (this.mesh.isFacetDataEnabled) {
  59075. this._computeBoundingBox = true;
  59076. }
  59077. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59078. if (this._computeBoundingBox) {
  59079. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59080. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59081. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59082. }
  59083. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59084. if (this.mesh._boundingInfo) {
  59085. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59086. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59087. }
  59088. }
  59089. }
  59090. // particle loop
  59091. index = this.particles[start]._pos;
  59092. var vpos = (index / 3) | 0;
  59093. colorIndex = vpos * 4;
  59094. uvIndex = vpos * 2;
  59095. for (var p = start; p <= end; p++) {
  59096. this._particle = this.particles[p];
  59097. this._shape = this._particle._model._shape;
  59098. this._shapeUV = this._particle._model._shapeUV;
  59099. // call to custom user function to update the particle properties
  59100. this.updateParticle(this._particle);
  59101. // camera-particle distance for depth sorting
  59102. if (this._depthSort && this._depthSortParticles) {
  59103. var dsp = this.depthSortedParticles[p];
  59104. dsp.ind = this._particle._ind;
  59105. dsp.indicesLength = this._particle._model._indicesLength;
  59106. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59107. }
  59108. // skip the computations for inactive or already invisible particles
  59109. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59110. // increment indexes for the next particle
  59111. pt = this._shape.length;
  59112. index += pt * 3;
  59113. colorIndex += pt * 4;
  59114. uvIndex += pt * 2;
  59115. continue;
  59116. }
  59117. if (this._particle.isVisible) {
  59118. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59119. this._particleHasParent = (this._particle.parentId !== null);
  59120. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59121. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59122. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59123. // particle rotation matrix
  59124. if (this.billboard) {
  59125. this._particle.rotation.x = 0.0;
  59126. this._particle.rotation.y = 0.0;
  59127. }
  59128. if (this._computeParticleRotation || this.billboard) {
  59129. if (this._particle.rotationQuaternion) {
  59130. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59131. }
  59132. else {
  59133. this._yaw = this._particle.rotation.y;
  59134. this._pitch = this._particle.rotation.x;
  59135. this._roll = this._particle.rotation.z;
  59136. this._quaternionRotationYPR();
  59137. }
  59138. this._quaternionToRotationMatrix();
  59139. }
  59140. if (this._particleHasParent) {
  59141. this._parent = this.particles[this._particle.parentId];
  59142. 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];
  59143. 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];
  59144. 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];
  59145. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59146. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59147. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59148. if (this._computeParticleRotation || this.billboard) {
  59149. 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];
  59150. 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];
  59151. 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];
  59152. 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];
  59153. 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];
  59154. 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];
  59155. 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];
  59156. 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];
  59157. 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];
  59158. }
  59159. }
  59160. else {
  59161. this._particle._globalPosition.x = this._particle.position.x;
  59162. this._particle._globalPosition.y = this._particle.position.y;
  59163. this._particle._globalPosition.z = this._particle.position.z;
  59164. if (this._computeParticleRotation || this.billboard) {
  59165. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59166. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59167. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59168. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59169. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59170. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59171. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59172. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59173. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59174. }
  59175. }
  59176. if (this._particle.translateFromPivot) {
  59177. this._pivotBackTranslation.x = 0.0;
  59178. this._pivotBackTranslation.y = 0.0;
  59179. this._pivotBackTranslation.z = 0.0;
  59180. }
  59181. else {
  59182. this._pivotBackTranslation.x = this._scaledPivot.x;
  59183. this._pivotBackTranslation.y = this._scaledPivot.y;
  59184. this._pivotBackTranslation.z = this._scaledPivot.z;
  59185. }
  59186. // particle vertex loop
  59187. for (pt = 0; pt < this._shape.length; pt++) {
  59188. idx = index + pt * 3;
  59189. colidx = colorIndex + pt * 4;
  59190. uvidx = uvIndex + pt * 2;
  59191. this._vertex.x = this._shape[pt].x;
  59192. this._vertex.y = this._shape[pt].y;
  59193. this._vertex.z = this._shape[pt].z;
  59194. if (this._computeParticleVertex) {
  59195. this.updateParticleVertex(this._particle, this._vertex, pt);
  59196. }
  59197. // positions
  59198. this._vertex.x *= this._particle.scaling.x;
  59199. this._vertex.y *= this._particle.scaling.y;
  59200. this._vertex.z *= this._particle.scaling.z;
  59201. this._vertex.x -= this._scaledPivot.x;
  59202. this._vertex.y -= this._scaledPivot.y;
  59203. this._vertex.z -= this._scaledPivot.z;
  59204. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59205. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59206. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59207. this._rotated.x += this._pivotBackTranslation.x;
  59208. this._rotated.y += this._pivotBackTranslation.y;
  59209. this._rotated.z += this._pivotBackTranslation.z;
  59210. 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;
  59211. 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;
  59212. 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;
  59213. if (this._computeBoundingBox) {
  59214. if (this._positions32[idx] < this._minimum.x) {
  59215. this._minimum.x = this._positions32[idx];
  59216. }
  59217. if (this._positions32[idx] > this._maximum.x) {
  59218. this._maximum.x = this._positions32[idx];
  59219. }
  59220. if (this._positions32[idx + 1] < this._minimum.y) {
  59221. this._minimum.y = this._positions32[idx + 1];
  59222. }
  59223. if (this._positions32[idx + 1] > this._maximum.y) {
  59224. this._maximum.y = this._positions32[idx + 1];
  59225. }
  59226. if (this._positions32[idx + 2] < this._minimum.z) {
  59227. this._minimum.z = this._positions32[idx + 2];
  59228. }
  59229. if (this._positions32[idx + 2] > this._maximum.z) {
  59230. this._maximum.z = this._positions32[idx + 2];
  59231. }
  59232. }
  59233. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59234. if (!this._computeParticleVertex) {
  59235. this._normal.x = this._fixedNormal32[idx];
  59236. this._normal.y = this._fixedNormal32[idx + 1];
  59237. this._normal.z = this._fixedNormal32[idx + 2];
  59238. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59239. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59240. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59241. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59242. 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;
  59243. 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;
  59244. }
  59245. if (this._computeParticleColor && this._particle.color) {
  59246. this._colors32[colidx] = this._particle.color.r;
  59247. this._colors32[colidx + 1] = this._particle.color.g;
  59248. this._colors32[colidx + 2] = this._particle.color.b;
  59249. this._colors32[colidx + 3] = this._particle.color.a;
  59250. }
  59251. if (this._computeParticleTexture) {
  59252. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59253. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59254. }
  59255. }
  59256. }
  59257. // particle just set invisible : scaled to zero and positioned at the origin
  59258. else {
  59259. this._particle._stillInvisible = true; // mark the particle as invisible
  59260. for (pt = 0; pt < this._shape.length; pt++) {
  59261. idx = index + pt * 3;
  59262. colidx = colorIndex + pt * 4;
  59263. uvidx = uvIndex + pt * 2;
  59264. this._positions32[idx] = 0.0;
  59265. this._positions32[idx + 1] = 0.0;
  59266. this._positions32[idx + 2] = 0.0;
  59267. this._normals32[idx] = 0.0;
  59268. this._normals32[idx + 1] = 0.0;
  59269. this._normals32[idx + 2] = 0.0;
  59270. if (this._computeParticleColor && this._particle.color) {
  59271. this._colors32[colidx] = this._particle.color.r;
  59272. this._colors32[colidx + 1] = this._particle.color.g;
  59273. this._colors32[colidx + 2] = this._particle.color.b;
  59274. this._colors32[colidx + 3] = this._particle.color.a;
  59275. }
  59276. if (this._computeParticleTexture) {
  59277. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59278. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59279. }
  59280. }
  59281. }
  59282. // if the particle intersections must be computed : update the bbInfo
  59283. if (this._particlesIntersect) {
  59284. var bInfo = this._particle._boundingInfo;
  59285. var bBox = bInfo.boundingBox;
  59286. var bSphere = bInfo.boundingSphere;
  59287. if (!this._bSphereOnly) {
  59288. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59289. for (var b = 0; b < bBox.vectors.length; b++) {
  59290. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59291. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59292. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59293. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59294. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59295. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59296. 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;
  59297. 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;
  59298. 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;
  59299. }
  59300. bBox._update(this.mesh._worldMatrix);
  59301. }
  59302. // place and scale the particle bouding sphere in the SPS local system, then update it
  59303. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59304. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59305. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59306. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59307. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59308. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59309. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59310. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59311. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59312. 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));
  59313. bSphere._update(this.mesh._worldMatrix);
  59314. }
  59315. // increment indexes for the next particle
  59316. index = idx + 3;
  59317. colorIndex = colidx + 4;
  59318. uvIndex = uvidx + 2;
  59319. }
  59320. // if the VBO must be updated
  59321. if (update) {
  59322. if (this._computeParticleColor) {
  59323. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59324. }
  59325. if (this._computeParticleTexture) {
  59326. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59327. }
  59328. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59329. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59330. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59331. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59332. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59333. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59334. for (var i = 0; i < this._normals32.length; i++) {
  59335. this._fixedNormal32[i] = this._normals32[i];
  59336. }
  59337. }
  59338. if (!this.mesh.areNormalsFrozen) {
  59339. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59340. }
  59341. }
  59342. if (this._depthSort && this._depthSortParticles) {
  59343. this.depthSortedParticles.sort(this._depthSortFunction);
  59344. var dspl = this.depthSortedParticles.length;
  59345. var sorted = 0;
  59346. var lind = 0;
  59347. var sind = 0;
  59348. var sid = 0;
  59349. for (sorted = 0; sorted < dspl; sorted++) {
  59350. lind = this.depthSortedParticles[sorted].indicesLength;
  59351. sind = this.depthSortedParticles[sorted].ind;
  59352. for (var i = 0; i < lind; i++) {
  59353. this._indices32[sid] = this._indices[sind + i];
  59354. sid++;
  59355. }
  59356. }
  59357. this.mesh.updateIndices(this._indices32);
  59358. }
  59359. }
  59360. if (this._computeBoundingBox) {
  59361. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59362. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59363. }
  59364. this.afterUpdateParticles(start, end, update);
  59365. return this;
  59366. };
  59367. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59368. this._halfroll = this._roll * 0.5;
  59369. this._halfpitch = this._pitch * 0.5;
  59370. this._halfyaw = this._yaw * 0.5;
  59371. this._sinRoll = Math.sin(this._halfroll);
  59372. this._cosRoll = Math.cos(this._halfroll);
  59373. this._sinPitch = Math.sin(this._halfpitch);
  59374. this._cosPitch = Math.cos(this._halfpitch);
  59375. this._sinYaw = Math.sin(this._halfyaw);
  59376. this._cosYaw = Math.cos(this._halfyaw);
  59377. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59378. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59379. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59380. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59381. };
  59382. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59383. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59384. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59385. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59386. this._rotMatrix.m[3] = 0;
  59387. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59388. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59389. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59390. this._rotMatrix.m[7] = 0;
  59391. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59392. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59393. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59394. this._rotMatrix.m[11] = 0;
  59395. this._rotMatrix.m[12] = 0;
  59396. this._rotMatrix.m[13] = 0;
  59397. this._rotMatrix.m[14] = 0;
  59398. this._rotMatrix.m[15] = 1.0;
  59399. };
  59400. /**
  59401. * Disposes the SPS.
  59402. */
  59403. SolidParticleSystem.prototype.dispose = function () {
  59404. this.mesh.dispose();
  59405. this.vars = null;
  59406. // drop references to internal big arrays for the GC
  59407. this._positions = null;
  59408. this._indices = null;
  59409. this._normals = null;
  59410. this._uvs = null;
  59411. this._colors = null;
  59412. this._indices32 = null;
  59413. this._positions32 = null;
  59414. this._normals32 = null;
  59415. this._fixedNormal32 = null;
  59416. this._uvs32 = null;
  59417. this._colors32 = null;
  59418. this.pickedParticles = null;
  59419. };
  59420. /**
  59421. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59422. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59423. * @returns the SPS.
  59424. */
  59425. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59426. if (!this._isVisibilityBoxLocked) {
  59427. this.mesh.refreshBoundingInfo();
  59428. }
  59429. return this;
  59430. };
  59431. /**
  59432. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59433. * @param size the size (float) of the visibility box
  59434. * note : this doesn't lock the SPS mesh bounding box.
  59435. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59436. */
  59437. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59438. var vis = size / 2;
  59439. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59440. };
  59441. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59442. /**
  59443. * Gets whether the SPS as always visible or not
  59444. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59445. */
  59446. get: function () {
  59447. return this._alwaysVisible;
  59448. },
  59449. /**
  59450. * Sets the SPS as always visible or not
  59451. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59452. */
  59453. set: function (val) {
  59454. this._alwaysVisible = val;
  59455. this.mesh.alwaysSelectAsActiveMesh = val;
  59456. },
  59457. enumerable: true,
  59458. configurable: true
  59459. });
  59460. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59461. /**
  59462. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59463. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59464. */
  59465. get: function () {
  59466. return this._isVisibilityBoxLocked;
  59467. },
  59468. /**
  59469. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59470. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59471. */
  59472. set: function (val) {
  59473. this._isVisibilityBoxLocked = val;
  59474. var boundingInfo = this.mesh.getBoundingInfo();
  59475. boundingInfo.isLocked = val;
  59476. },
  59477. enumerable: true,
  59478. configurable: true
  59479. });
  59480. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59481. /**
  59482. * Gets if `setParticles()` computes the particle rotations or not.
  59483. * Default value : true. The SPS is faster when it's set to false.
  59484. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59485. */
  59486. get: function () {
  59487. return this._computeParticleRotation;
  59488. },
  59489. /**
  59490. * Tells to `setParticles()` to compute the particle rotations or not.
  59491. * Default value : true. The SPS is faster when it's set to false.
  59492. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59493. */
  59494. set: function (val) {
  59495. this._computeParticleRotation = val;
  59496. },
  59497. enumerable: true,
  59498. configurable: true
  59499. });
  59500. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59501. /**
  59502. * Gets if `setParticles()` computes the particle colors or not.
  59503. * Default value : true. The SPS is faster when it's set to false.
  59504. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59505. */
  59506. get: function () {
  59507. return this._computeParticleColor;
  59508. },
  59509. /**
  59510. * Tells to `setParticles()` to compute the particle colors or not.
  59511. * Default value : true. The SPS is faster when it's set to false.
  59512. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59513. */
  59514. set: function (val) {
  59515. this._computeParticleColor = val;
  59516. },
  59517. enumerable: true,
  59518. configurable: true
  59519. });
  59520. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59521. /**
  59522. * Gets if `setParticles()` computes the particle textures or not.
  59523. * Default value : true. The SPS is faster when it's set to false.
  59524. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59525. */
  59526. get: function () {
  59527. return this._computeParticleTexture;
  59528. },
  59529. set: function (val) {
  59530. this._computeParticleTexture = val;
  59531. },
  59532. enumerable: true,
  59533. configurable: true
  59534. });
  59535. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59536. /**
  59537. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59538. * Default value : false. The SPS is faster when it's set to false.
  59539. * Note : the particle custom vertex positions aren't stored values.
  59540. */
  59541. get: function () {
  59542. return this._computeParticleVertex;
  59543. },
  59544. /**
  59545. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59546. * Default value : false. The SPS is faster when it's set to false.
  59547. * Note : the particle custom vertex positions aren't stored values.
  59548. */
  59549. set: function (val) {
  59550. this._computeParticleVertex = val;
  59551. },
  59552. enumerable: true,
  59553. configurable: true
  59554. });
  59555. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59556. /**
  59557. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59558. */
  59559. get: function () {
  59560. return this._computeBoundingBox;
  59561. },
  59562. /**
  59563. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59564. */
  59565. set: function (val) {
  59566. this._computeBoundingBox = val;
  59567. },
  59568. enumerable: true,
  59569. configurable: true
  59570. });
  59571. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59572. /**
  59573. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59574. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59575. * Default : `true`
  59576. */
  59577. get: function () {
  59578. return this._depthSortParticles;
  59579. },
  59580. /**
  59581. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59582. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59583. * Default : `true`
  59584. */
  59585. set: function (val) {
  59586. this._depthSortParticles = val;
  59587. },
  59588. enumerable: true,
  59589. configurable: true
  59590. });
  59591. // =======================================================================
  59592. // Particle behavior logic
  59593. // these following methods may be overwritten by the user to fit his needs
  59594. /**
  59595. * This function does nothing. It may be overwritten to set all the particle first values.
  59596. * The SPS doesn't call this function, you may have to call it by your own.
  59597. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59598. */
  59599. SolidParticleSystem.prototype.initParticles = function () {
  59600. };
  59601. /**
  59602. * This function does nothing. It may be overwritten to recycle a particle.
  59603. * The SPS doesn't call this function, you may have to call it by your own.
  59604. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59605. * @param particle The particle to recycle
  59606. * @returns the recycled particle
  59607. */
  59608. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59609. return particle;
  59610. };
  59611. /**
  59612. * Updates a particle : this function should be overwritten by the user.
  59613. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59614. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59615. * @example : just set a particle position or velocity and recycle conditions
  59616. * @param particle The particle to update
  59617. * @returns the updated particle
  59618. */
  59619. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59620. return particle;
  59621. };
  59622. /**
  59623. * Updates a vertex of a particle : it can be overwritten by the user.
  59624. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59625. * @param particle the current particle
  59626. * @param vertex the current index of the current particle
  59627. * @param pt the index of the current vertex in the particle shape
  59628. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59629. * @example : just set a vertex particle position
  59630. * @returns the updated vertex
  59631. */
  59632. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59633. return vertex;
  59634. };
  59635. /**
  59636. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59637. * This does nothing and may be overwritten by the user.
  59638. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59639. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59640. * @param update the boolean update value actually passed to setParticles()
  59641. */
  59642. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59643. };
  59644. /**
  59645. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59646. * This will be passed three parameters.
  59647. * This does nothing and may be overwritten by the user.
  59648. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59649. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59650. * @param update the boolean update value actually passed to setParticles()
  59651. */
  59652. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59653. };
  59654. return SolidParticleSystem;
  59655. }());
  59656. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59657. })(BABYLON || (BABYLON = {}));
  59658. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59659. var BABYLON;
  59660. (function (BABYLON) {
  59661. var ShaderMaterial = /** @class */ (function (_super) {
  59662. __extends(ShaderMaterial, _super);
  59663. function ShaderMaterial(name, scene, shaderPath, options) {
  59664. var _this = _super.call(this, name, scene) || this;
  59665. _this._textures = {};
  59666. _this._textureArrays = {};
  59667. _this._floats = {};
  59668. _this._ints = {};
  59669. _this._floatsArrays = {};
  59670. _this._colors3 = {};
  59671. _this._colors3Arrays = {};
  59672. _this._colors4 = {};
  59673. _this._vectors2 = {};
  59674. _this._vectors3 = {};
  59675. _this._vectors4 = {};
  59676. _this._matrices = {};
  59677. _this._matrices3x3 = {};
  59678. _this._matrices2x2 = {};
  59679. _this._vectors2Arrays = {};
  59680. _this._vectors3Arrays = {};
  59681. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59682. _this._shaderPath = shaderPath;
  59683. options.needAlphaBlending = options.needAlphaBlending || false;
  59684. options.needAlphaTesting = options.needAlphaTesting || false;
  59685. options.attributes = options.attributes || ["position", "normal", "uv"];
  59686. options.uniforms = options.uniforms || ["worldViewProjection"];
  59687. options.uniformBuffers = options.uniformBuffers || [];
  59688. options.samplers = options.samplers || [];
  59689. options.defines = options.defines || [];
  59690. _this._options = options;
  59691. return _this;
  59692. }
  59693. ShaderMaterial.prototype.getClassName = function () {
  59694. return "ShaderMaterial";
  59695. };
  59696. ShaderMaterial.prototype.needAlphaBlending = function () {
  59697. return this._options.needAlphaBlending;
  59698. };
  59699. ShaderMaterial.prototype.needAlphaTesting = function () {
  59700. return this._options.needAlphaTesting;
  59701. };
  59702. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59703. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59704. this._options.uniforms.push(uniformName);
  59705. }
  59706. };
  59707. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59708. if (this._options.samplers.indexOf(name) === -1) {
  59709. this._options.samplers.push(name);
  59710. }
  59711. this._textures[name] = texture;
  59712. return this;
  59713. };
  59714. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59715. if (this._options.samplers.indexOf(name) === -1) {
  59716. this._options.samplers.push(name);
  59717. }
  59718. this._checkUniform(name);
  59719. this._textureArrays[name] = textures;
  59720. return this;
  59721. };
  59722. ShaderMaterial.prototype.setFloat = function (name, value) {
  59723. this._checkUniform(name);
  59724. this._floats[name] = value;
  59725. return this;
  59726. };
  59727. ShaderMaterial.prototype.setInt = function (name, value) {
  59728. this._checkUniform(name);
  59729. this._ints[name] = value;
  59730. return this;
  59731. };
  59732. ShaderMaterial.prototype.setFloats = function (name, value) {
  59733. this._checkUniform(name);
  59734. this._floatsArrays[name] = value;
  59735. return this;
  59736. };
  59737. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59738. this._checkUniform(name);
  59739. this._colors3[name] = value;
  59740. return this;
  59741. };
  59742. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59743. this._checkUniform(name);
  59744. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59745. color.toArray(arr, arr.length);
  59746. return arr;
  59747. }, []);
  59748. return this;
  59749. };
  59750. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59751. this._checkUniform(name);
  59752. this._colors4[name] = value;
  59753. return this;
  59754. };
  59755. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59756. this._checkUniform(name);
  59757. this._vectors2[name] = value;
  59758. return this;
  59759. };
  59760. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59761. this._checkUniform(name);
  59762. this._vectors3[name] = value;
  59763. return this;
  59764. };
  59765. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59766. this._checkUniform(name);
  59767. this._vectors4[name] = value;
  59768. return this;
  59769. };
  59770. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59771. this._checkUniform(name);
  59772. this._matrices[name] = value;
  59773. return this;
  59774. };
  59775. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59776. this._checkUniform(name);
  59777. this._matrices3x3[name] = value;
  59778. return this;
  59779. };
  59780. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59781. this._checkUniform(name);
  59782. this._matrices2x2[name] = value;
  59783. return this;
  59784. };
  59785. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59786. this._checkUniform(name);
  59787. this._vectors2Arrays[name] = value;
  59788. return this;
  59789. };
  59790. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59791. this._checkUniform(name);
  59792. this._vectors3Arrays[name] = value;
  59793. return this;
  59794. };
  59795. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59796. if (!mesh) {
  59797. return true;
  59798. }
  59799. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59800. return false;
  59801. }
  59802. return false;
  59803. };
  59804. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59805. var scene = this.getScene();
  59806. var engine = scene.getEngine();
  59807. if (!this.checkReadyOnEveryCall) {
  59808. if (this._renderId === scene.getRenderId()) {
  59809. if (this._checkCache(scene, mesh, useInstances)) {
  59810. return true;
  59811. }
  59812. }
  59813. }
  59814. // Instances
  59815. var defines = [];
  59816. var attribs = [];
  59817. var fallbacks = new BABYLON.EffectFallbacks();
  59818. if (useInstances) {
  59819. defines.push("#define INSTANCES");
  59820. }
  59821. for (var index = 0; index < this._options.defines.length; index++) {
  59822. defines.push(this._options.defines[index]);
  59823. }
  59824. for (var index = 0; index < this._options.attributes.length; index++) {
  59825. attribs.push(this._options.attributes[index]);
  59826. }
  59827. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59828. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59829. defines.push("#define VERTEXCOLOR");
  59830. }
  59831. // Bones
  59832. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59833. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59834. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59835. if (mesh.numBoneInfluencers > 4) {
  59836. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59837. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59838. }
  59839. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59840. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59841. fallbacks.addCPUSkinningFallback(0, mesh);
  59842. if (this._options.uniforms.indexOf("mBones") === -1) {
  59843. this._options.uniforms.push("mBones");
  59844. }
  59845. }
  59846. else {
  59847. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59848. }
  59849. // Textures
  59850. for (var name in this._textures) {
  59851. if (!this._textures[name].isReady()) {
  59852. return false;
  59853. }
  59854. }
  59855. // Alpha test
  59856. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59857. defines.push("#define ALPHATEST");
  59858. }
  59859. var previousEffect = this._effect;
  59860. var join = defines.join("\n");
  59861. this._effect = engine.createEffect(this._shaderPath, {
  59862. attributes: attribs,
  59863. uniformsNames: this._options.uniforms,
  59864. uniformBuffersNames: this._options.uniformBuffers,
  59865. samplers: this._options.samplers,
  59866. defines: join,
  59867. fallbacks: fallbacks,
  59868. onCompiled: this.onCompiled,
  59869. onError: this.onError
  59870. }, engine);
  59871. if (!this._effect.isReady()) {
  59872. return false;
  59873. }
  59874. if (previousEffect !== this._effect) {
  59875. scene.resetCachedMaterial();
  59876. }
  59877. this._renderId = scene.getRenderId();
  59878. return true;
  59879. };
  59880. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59881. var scene = this.getScene();
  59882. if (!this._effect) {
  59883. return;
  59884. }
  59885. if (this._options.uniforms.indexOf("world") !== -1) {
  59886. this._effect.setMatrix("world", world);
  59887. }
  59888. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59889. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59890. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59891. }
  59892. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59893. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59894. }
  59895. };
  59896. ShaderMaterial.prototype.bind = function (world, mesh) {
  59897. // Std values
  59898. this.bindOnlyWorldMatrix(world);
  59899. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59900. if (this._options.uniforms.indexOf("view") !== -1) {
  59901. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59902. }
  59903. if (this._options.uniforms.indexOf("projection") !== -1) {
  59904. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59905. }
  59906. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59907. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59908. }
  59909. // Bones
  59910. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59911. var name;
  59912. // Texture
  59913. for (name in this._textures) {
  59914. this._effect.setTexture(name, this._textures[name]);
  59915. }
  59916. // Texture arrays
  59917. for (name in this._textureArrays) {
  59918. this._effect.setTextureArray(name, this._textureArrays[name]);
  59919. }
  59920. // Int
  59921. for (name in this._ints) {
  59922. this._effect.setInt(name, this._ints[name]);
  59923. }
  59924. // Float
  59925. for (name in this._floats) {
  59926. this._effect.setFloat(name, this._floats[name]);
  59927. }
  59928. // Floats
  59929. for (name in this._floatsArrays) {
  59930. this._effect.setArray(name, this._floatsArrays[name]);
  59931. }
  59932. // Color3
  59933. for (name in this._colors3) {
  59934. this._effect.setColor3(name, this._colors3[name]);
  59935. }
  59936. for (name in this._colors3Arrays) {
  59937. this._effect.setArray3(name, this._colors3Arrays[name]);
  59938. }
  59939. // Color4
  59940. for (name in this._colors4) {
  59941. var color = this._colors4[name];
  59942. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59943. }
  59944. // Vector2
  59945. for (name in this._vectors2) {
  59946. this._effect.setVector2(name, this._vectors2[name]);
  59947. }
  59948. // Vector3
  59949. for (name in this._vectors3) {
  59950. this._effect.setVector3(name, this._vectors3[name]);
  59951. }
  59952. // Vector4
  59953. for (name in this._vectors4) {
  59954. this._effect.setVector4(name, this._vectors4[name]);
  59955. }
  59956. // Matrix
  59957. for (name in this._matrices) {
  59958. this._effect.setMatrix(name, this._matrices[name]);
  59959. }
  59960. // Matrix 3x3
  59961. for (name in this._matrices3x3) {
  59962. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59963. }
  59964. // Matrix 2x2
  59965. for (name in this._matrices2x2) {
  59966. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59967. }
  59968. // Vector2Array
  59969. for (name in this._vectors2Arrays) {
  59970. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59971. }
  59972. // Vector3Array
  59973. for (name in this._vectors3Arrays) {
  59974. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59975. }
  59976. }
  59977. this._afterBind(mesh);
  59978. };
  59979. ShaderMaterial.prototype.getActiveTextures = function () {
  59980. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59981. for (var name in this._textures) {
  59982. activeTextures.push(this._textures[name]);
  59983. }
  59984. for (var name in this._textureArrays) {
  59985. var array = this._textureArrays[name];
  59986. for (var index = 0; index < array.length; index++) {
  59987. activeTextures.push(array[index]);
  59988. }
  59989. }
  59990. return activeTextures;
  59991. };
  59992. ShaderMaterial.prototype.hasTexture = function (texture) {
  59993. if (_super.prototype.hasTexture.call(this, texture)) {
  59994. return true;
  59995. }
  59996. for (var name in this._textures) {
  59997. if (this._textures[name] === texture) {
  59998. return true;
  59999. }
  60000. }
  60001. for (var name in this._textureArrays) {
  60002. var array = this._textureArrays[name];
  60003. for (var index = 0; index < array.length; index++) {
  60004. if (array[index] === texture) {
  60005. return true;
  60006. }
  60007. }
  60008. }
  60009. return false;
  60010. };
  60011. ShaderMaterial.prototype.clone = function (name) {
  60012. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60013. return newShaderMaterial;
  60014. };
  60015. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60016. if (forceDisposeTextures) {
  60017. var name;
  60018. for (name in this._textures) {
  60019. this._textures[name].dispose();
  60020. }
  60021. for (name in this._textureArrays) {
  60022. var array = this._textureArrays[name];
  60023. for (var index = 0; index < array.length; index++) {
  60024. array[index].dispose();
  60025. }
  60026. }
  60027. }
  60028. this._textures = {};
  60029. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60030. };
  60031. ShaderMaterial.prototype.serialize = function () {
  60032. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60033. serializationObject.customType = "BABYLON.ShaderMaterial";
  60034. serializationObject.options = this._options;
  60035. serializationObject.shaderPath = this._shaderPath;
  60036. var name;
  60037. // Texture
  60038. serializationObject.textures = {};
  60039. for (name in this._textures) {
  60040. serializationObject.textures[name] = this._textures[name].serialize();
  60041. }
  60042. // Texture arrays
  60043. serializationObject.textureArrays = {};
  60044. for (name in this._textureArrays) {
  60045. serializationObject.textureArrays[name] = [];
  60046. var array = this._textureArrays[name];
  60047. for (var index = 0; index < array.length; index++) {
  60048. serializationObject.textureArrays[name].push(array[index].serialize());
  60049. }
  60050. }
  60051. // Float
  60052. serializationObject.floats = {};
  60053. for (name in this._floats) {
  60054. serializationObject.floats[name] = this._floats[name];
  60055. }
  60056. // Float s
  60057. serializationObject.FloatArrays = {};
  60058. for (name in this._floatsArrays) {
  60059. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60060. }
  60061. // Color3
  60062. serializationObject.colors3 = {};
  60063. for (name in this._colors3) {
  60064. serializationObject.colors3[name] = this._colors3[name].asArray();
  60065. }
  60066. // Color3 array
  60067. serializationObject.colors3Arrays = {};
  60068. for (name in this._colors3Arrays) {
  60069. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60070. }
  60071. // Color4
  60072. serializationObject.colors4 = {};
  60073. for (name in this._colors4) {
  60074. serializationObject.colors4[name] = this._colors4[name].asArray();
  60075. }
  60076. // Vector2
  60077. serializationObject.vectors2 = {};
  60078. for (name in this._vectors2) {
  60079. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60080. }
  60081. // Vector3
  60082. serializationObject.vectors3 = {};
  60083. for (name in this._vectors3) {
  60084. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60085. }
  60086. // Vector4
  60087. serializationObject.vectors4 = {};
  60088. for (name in this._vectors4) {
  60089. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60090. }
  60091. // Matrix
  60092. serializationObject.matrices = {};
  60093. for (name in this._matrices) {
  60094. serializationObject.matrices[name] = this._matrices[name].asArray();
  60095. }
  60096. // Matrix 3x3
  60097. serializationObject.matrices3x3 = {};
  60098. for (name in this._matrices3x3) {
  60099. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60100. }
  60101. // Matrix 2x2
  60102. serializationObject.matrices2x2 = {};
  60103. for (name in this._matrices2x2) {
  60104. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60105. }
  60106. // Vector2Array
  60107. serializationObject.vectors2Arrays = {};
  60108. for (name in this._vectors2Arrays) {
  60109. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60110. }
  60111. // Vector3Array
  60112. serializationObject.vectors3Arrays = {};
  60113. for (name in this._vectors3Arrays) {
  60114. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60115. }
  60116. return serializationObject;
  60117. };
  60118. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60119. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60120. var name;
  60121. // Texture
  60122. for (name in source.textures) {
  60123. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60124. }
  60125. // Texture arrays
  60126. for (name in source.textureArrays) {
  60127. var array = source.textureArrays[name];
  60128. var textureArray = new Array();
  60129. for (var index = 0; index < array.length; index++) {
  60130. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60131. }
  60132. material.setTextureArray(name, textureArray);
  60133. }
  60134. // Float
  60135. for (name in source.floats) {
  60136. material.setFloat(name, source.floats[name]);
  60137. }
  60138. // Float s
  60139. for (name in source.floatsArrays) {
  60140. material.setFloats(name, source.floatsArrays[name]);
  60141. }
  60142. // Color3
  60143. for (name in source.colors3) {
  60144. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60145. }
  60146. // Color3 arrays
  60147. for (name in source.colors3Arrays) {
  60148. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60149. if (i % 3 === 0) {
  60150. arr.push([num]);
  60151. }
  60152. else {
  60153. arr[arr.length - 1].push(num);
  60154. }
  60155. return arr;
  60156. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60157. material.setColor3Array(name, colors);
  60158. }
  60159. // Color4
  60160. for (name in source.colors4) {
  60161. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60162. }
  60163. // Vector2
  60164. for (name in source.vectors2) {
  60165. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60166. }
  60167. // Vector3
  60168. for (name in source.vectors3) {
  60169. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60170. }
  60171. // Vector4
  60172. for (name in source.vectors4) {
  60173. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60174. }
  60175. // Matrix
  60176. for (name in source.matrices) {
  60177. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60178. }
  60179. // Matrix 3x3
  60180. for (name in source.matrices3x3) {
  60181. material.setMatrix3x3(name, source.matrices3x3[name]);
  60182. }
  60183. // Matrix 2x2
  60184. for (name in source.matrices2x2) {
  60185. material.setMatrix2x2(name, source.matrices2x2[name]);
  60186. }
  60187. // Vector2Array
  60188. for (name in source.vectors2Arrays) {
  60189. material.setArray2(name, source.vectors2Arrays[name]);
  60190. }
  60191. // Vector3Array
  60192. for (name in source.vectors3Arrays) {
  60193. material.setArray3(name, source.vectors3Arrays[name]);
  60194. }
  60195. return material;
  60196. };
  60197. return ShaderMaterial;
  60198. }(BABYLON.Material));
  60199. BABYLON.ShaderMaterial = ShaderMaterial;
  60200. })(BABYLON || (BABYLON = {}));
  60201. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60202. var BABYLON;
  60203. (function (BABYLON) {
  60204. var GroundMesh = /** @class */ (function (_super) {
  60205. __extends(GroundMesh, _super);
  60206. function GroundMesh(name, scene) {
  60207. var _this = _super.call(this, name, scene) || this;
  60208. _this.generateOctree = false;
  60209. return _this;
  60210. }
  60211. GroundMesh.prototype.getClassName = function () {
  60212. return "GroundMesh";
  60213. };
  60214. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60215. get: function () {
  60216. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60217. },
  60218. enumerable: true,
  60219. configurable: true
  60220. });
  60221. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60222. get: function () {
  60223. return this._subdivisionsX;
  60224. },
  60225. enumerable: true,
  60226. configurable: true
  60227. });
  60228. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60229. get: function () {
  60230. return this._subdivisionsY;
  60231. },
  60232. enumerable: true,
  60233. configurable: true
  60234. });
  60235. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60236. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60237. this._subdivisionsX = chunksCount;
  60238. this._subdivisionsY = chunksCount;
  60239. this.subdivide(chunksCount);
  60240. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60241. };
  60242. /**
  60243. * Returns a height (y) value in the Worl system :
  60244. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60245. * Returns the ground y position if (x, z) are outside the ground surface.
  60246. */
  60247. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60248. var world = this.getWorldMatrix();
  60249. var invMat = BABYLON.Tmp.Matrix[5];
  60250. world.invertToRef(invMat);
  60251. var tmpVect = BABYLON.Tmp.Vector3[8];
  60252. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60253. x = tmpVect.x;
  60254. z = tmpVect.z;
  60255. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60256. return this.position.y;
  60257. }
  60258. if (!this._heightQuads || this._heightQuads.length == 0) {
  60259. this._initHeightQuads();
  60260. this._computeHeightQuads();
  60261. }
  60262. var facet = this._getFacetAt(x, z);
  60263. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60264. // return y in the World system
  60265. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60266. return tmpVect.y;
  60267. };
  60268. /**
  60269. * Returns a normalized vector (Vector3) orthogonal to the ground
  60270. * at the ground coordinates (x, z) expressed in the World system.
  60271. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60272. */
  60273. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60274. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60275. this.getNormalAtCoordinatesToRef(x, z, normal);
  60276. return normal;
  60277. };
  60278. /**
  60279. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60280. * at the ground coordinates (x, z) expressed in the World system.
  60281. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60282. * Returns the GroundMesh.
  60283. */
  60284. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60285. var world = this.getWorldMatrix();
  60286. var tmpMat = BABYLON.Tmp.Matrix[5];
  60287. world.invertToRef(tmpMat);
  60288. var tmpVect = BABYLON.Tmp.Vector3[8];
  60289. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60290. x = tmpVect.x;
  60291. z = tmpVect.z;
  60292. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60293. return this;
  60294. }
  60295. if (!this._heightQuads || this._heightQuads.length == 0) {
  60296. this._initHeightQuads();
  60297. this._computeHeightQuads();
  60298. }
  60299. var facet = this._getFacetAt(x, z);
  60300. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60301. return this;
  60302. };
  60303. /**
  60304. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60305. * if the ground has been updated.
  60306. * This can be used in the render loop.
  60307. * Returns the GroundMesh.
  60308. */
  60309. GroundMesh.prototype.updateCoordinateHeights = function () {
  60310. if (!this._heightQuads || this._heightQuads.length == 0) {
  60311. this._initHeightQuads();
  60312. }
  60313. this._computeHeightQuads();
  60314. return this;
  60315. };
  60316. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60317. GroundMesh.prototype._getFacetAt = function (x, z) {
  60318. // retrieve col and row from x, z coordinates in the ground local system
  60319. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60320. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60321. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60322. var facet;
  60323. if (z < quad.slope.x * x + quad.slope.y) {
  60324. facet = quad.facet1;
  60325. }
  60326. else {
  60327. facet = quad.facet2;
  60328. }
  60329. return facet;
  60330. };
  60331. // Creates and populates the heightMap array with "facet" elements :
  60332. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60333. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60334. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60335. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60336. // Returns the GroundMesh.
  60337. GroundMesh.prototype._initHeightQuads = function () {
  60338. var subdivisionsX = this._subdivisionsX;
  60339. var subdivisionsY = this._subdivisionsY;
  60340. this._heightQuads = new Array();
  60341. for (var row = 0; row < subdivisionsY; row++) {
  60342. for (var col = 0; col < subdivisionsX; col++) {
  60343. 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) };
  60344. this._heightQuads[row * subdivisionsX + col] = quad;
  60345. }
  60346. }
  60347. return this;
  60348. };
  60349. // Compute each quad element values and update the the heightMap array :
  60350. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60351. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60352. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60353. // Returns the GroundMesh.
  60354. GroundMesh.prototype._computeHeightQuads = function () {
  60355. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60356. if (!positions) {
  60357. return this;
  60358. }
  60359. var v1 = BABYLON.Tmp.Vector3[3];
  60360. var v2 = BABYLON.Tmp.Vector3[2];
  60361. var v3 = BABYLON.Tmp.Vector3[1];
  60362. var v4 = BABYLON.Tmp.Vector3[0];
  60363. var v1v2 = BABYLON.Tmp.Vector3[4];
  60364. var v1v3 = BABYLON.Tmp.Vector3[5];
  60365. var v1v4 = BABYLON.Tmp.Vector3[6];
  60366. var norm1 = BABYLON.Tmp.Vector3[7];
  60367. var norm2 = BABYLON.Tmp.Vector3[8];
  60368. var i = 0;
  60369. var j = 0;
  60370. var k = 0;
  60371. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60372. var h = 0;
  60373. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60374. var d2 = 0;
  60375. var subdivisionsX = this._subdivisionsX;
  60376. var subdivisionsY = this._subdivisionsY;
  60377. for (var row = 0; row < subdivisionsY; row++) {
  60378. for (var col = 0; col < subdivisionsX; col++) {
  60379. i = col * 3;
  60380. j = row * (subdivisionsX + 1) * 3;
  60381. k = (row + 1) * (subdivisionsX + 1) * 3;
  60382. v1.x = positions[j + i];
  60383. v1.y = positions[j + i + 1];
  60384. v1.z = positions[j + i + 2];
  60385. v2.x = positions[j + i + 3];
  60386. v2.y = positions[j + i + 4];
  60387. v2.z = positions[j + i + 5];
  60388. v3.x = positions[k + i];
  60389. v3.y = positions[k + i + 1];
  60390. v3.z = positions[k + i + 2];
  60391. v4.x = positions[k + i + 3];
  60392. v4.y = positions[k + i + 4];
  60393. v4.z = positions[k + i + 5];
  60394. // 2D slope V1V4
  60395. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60396. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60397. // facet equations :
  60398. // we compute each facet normal vector
  60399. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60400. // we compute the value d by applying the equation to v1 which belongs to the plane
  60401. // then we store the facet equation in a Vector4
  60402. v2.subtractToRef(v1, v1v2);
  60403. v3.subtractToRef(v1, v1v3);
  60404. v4.subtractToRef(v1, v1v4);
  60405. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60406. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60407. norm1.normalize();
  60408. norm2.normalize();
  60409. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60410. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60411. var quad = this._heightQuads[row * subdivisionsX + col];
  60412. quad.slope.copyFromFloats(cd, h);
  60413. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60414. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60415. }
  60416. }
  60417. return this;
  60418. };
  60419. GroundMesh.prototype.serialize = function (serializationObject) {
  60420. _super.prototype.serialize.call(this, serializationObject);
  60421. serializationObject.subdivisionsX = this._subdivisionsX;
  60422. serializationObject.subdivisionsY = this._subdivisionsY;
  60423. serializationObject.minX = this._minX;
  60424. serializationObject.maxX = this._maxX;
  60425. serializationObject.minZ = this._minZ;
  60426. serializationObject.maxZ = this._maxZ;
  60427. serializationObject.width = this._width;
  60428. serializationObject.height = this._height;
  60429. };
  60430. GroundMesh.Parse = function (parsedMesh, scene) {
  60431. var result = new GroundMesh(parsedMesh.name, scene);
  60432. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60433. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60434. result._minX = parsedMesh.minX;
  60435. result._maxX = parsedMesh.maxX;
  60436. result._minZ = parsedMesh.minZ;
  60437. result._maxZ = parsedMesh.maxZ;
  60438. result._width = parsedMesh.width;
  60439. result._height = parsedMesh.height;
  60440. return result;
  60441. };
  60442. return GroundMesh;
  60443. }(BABYLON.Mesh));
  60444. BABYLON.GroundMesh = GroundMesh;
  60445. })(BABYLON || (BABYLON = {}));
  60446. //# sourceMappingURL=babylon.groundMesh.js.map
  60447. var BABYLON;
  60448. (function (BABYLON) {
  60449. /**
  60450. * Creates an instance based on a source mesh.
  60451. */
  60452. var InstancedMesh = /** @class */ (function (_super) {
  60453. __extends(InstancedMesh, _super);
  60454. function InstancedMesh(name, source) {
  60455. var _this = _super.call(this, name, source.getScene()) || this;
  60456. source.instances.push(_this);
  60457. _this._sourceMesh = source;
  60458. _this.position.copyFrom(source.position);
  60459. _this.rotation.copyFrom(source.rotation);
  60460. _this.scaling.copyFrom(source.scaling);
  60461. if (source.rotationQuaternion) {
  60462. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60463. }
  60464. _this.infiniteDistance = source.infiniteDistance;
  60465. _this.setPivotMatrix(source.getPivotMatrix());
  60466. _this.refreshBoundingInfo();
  60467. _this._syncSubMeshes();
  60468. return _this;
  60469. }
  60470. /**
  60471. * Returns the string "InstancedMesh".
  60472. */
  60473. InstancedMesh.prototype.getClassName = function () {
  60474. return "InstancedMesh";
  60475. };
  60476. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60477. // Methods
  60478. get: function () {
  60479. return this._sourceMesh.receiveShadows;
  60480. },
  60481. enumerable: true,
  60482. configurable: true
  60483. });
  60484. Object.defineProperty(InstancedMesh.prototype, "material", {
  60485. get: function () {
  60486. return this._sourceMesh.material;
  60487. },
  60488. enumerable: true,
  60489. configurable: true
  60490. });
  60491. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60492. get: function () {
  60493. return this._sourceMesh.visibility;
  60494. },
  60495. enumerable: true,
  60496. configurable: true
  60497. });
  60498. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60499. get: function () {
  60500. return this._sourceMesh.skeleton;
  60501. },
  60502. enumerable: true,
  60503. configurable: true
  60504. });
  60505. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60506. get: function () {
  60507. return this._sourceMesh.renderingGroupId;
  60508. },
  60509. set: function (value) {
  60510. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60511. return;
  60512. }
  60513. //no-op with warning
  60514. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60515. },
  60516. enumerable: true,
  60517. configurable: true
  60518. });
  60519. /**
  60520. * Returns the total number of vertices (integer).
  60521. */
  60522. InstancedMesh.prototype.getTotalVertices = function () {
  60523. return this._sourceMesh.getTotalVertices();
  60524. };
  60525. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60526. get: function () {
  60527. return this._sourceMesh;
  60528. },
  60529. enumerable: true,
  60530. configurable: true
  60531. });
  60532. /**
  60533. * Is this node ready to be used/rendered
  60534. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60535. * @return {boolean} is it ready
  60536. */
  60537. InstancedMesh.prototype.isReady = function (completeCheck) {
  60538. if (completeCheck === void 0) { completeCheck = false; }
  60539. return this._sourceMesh.isReady(completeCheck, true);
  60540. };
  60541. /**
  60542. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60543. */
  60544. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60545. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60546. };
  60547. /**
  60548. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60549. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60550. * The `data` are either a numeric array either a Float32Array.
  60551. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60552. * 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).
  60553. * Note that a new underlying VertexBuffer object is created each call.
  60554. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60555. *
  60556. * Possible `kind` values :
  60557. * - BABYLON.VertexBuffer.PositionKind
  60558. * - BABYLON.VertexBuffer.UVKind
  60559. * - BABYLON.VertexBuffer.UV2Kind
  60560. * - BABYLON.VertexBuffer.UV3Kind
  60561. * - BABYLON.VertexBuffer.UV4Kind
  60562. * - BABYLON.VertexBuffer.UV5Kind
  60563. * - BABYLON.VertexBuffer.UV6Kind
  60564. * - BABYLON.VertexBuffer.ColorKind
  60565. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60566. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60567. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60568. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60569. *
  60570. * Returns the Mesh.
  60571. */
  60572. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60573. if (this.sourceMesh) {
  60574. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60575. }
  60576. return this.sourceMesh;
  60577. };
  60578. /**
  60579. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60580. * If the mesh has no geometry, it is simply returned as it is.
  60581. * The `data` are either a numeric array either a Float32Array.
  60582. * No new underlying VertexBuffer object is created.
  60583. * 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.
  60584. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60585. *
  60586. * Possible `kind` values :
  60587. * - BABYLON.VertexBuffer.PositionKind
  60588. * - BABYLON.VertexBuffer.UVKind
  60589. * - BABYLON.VertexBuffer.UV2Kind
  60590. * - BABYLON.VertexBuffer.UV3Kind
  60591. * - BABYLON.VertexBuffer.UV4Kind
  60592. * - BABYLON.VertexBuffer.UV5Kind
  60593. * - BABYLON.VertexBuffer.UV6Kind
  60594. * - BABYLON.VertexBuffer.ColorKind
  60595. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60596. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60597. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60598. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60599. *
  60600. * Returns the Mesh.
  60601. */
  60602. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60603. if (this.sourceMesh) {
  60604. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60605. }
  60606. return this.sourceMesh;
  60607. };
  60608. /**
  60609. * Sets the mesh indices.
  60610. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60611. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60612. * This method creates a new index buffer each call.
  60613. * Returns the Mesh.
  60614. */
  60615. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60616. if (totalVertices === void 0) { totalVertices = null; }
  60617. if (this.sourceMesh) {
  60618. this.sourceMesh.setIndices(indices, totalVertices);
  60619. }
  60620. return this.sourceMesh;
  60621. };
  60622. /**
  60623. * Boolean : True if the mesh owns the requested kind of data.
  60624. */
  60625. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60626. return this._sourceMesh.isVerticesDataPresent(kind);
  60627. };
  60628. /**
  60629. * Returns an array of indices (IndicesArray).
  60630. */
  60631. InstancedMesh.prototype.getIndices = function () {
  60632. return this._sourceMesh.getIndices();
  60633. };
  60634. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60635. get: function () {
  60636. return this._sourceMesh._positions;
  60637. },
  60638. enumerable: true,
  60639. configurable: true
  60640. });
  60641. /**
  60642. * Sets a new updated BoundingInfo to the mesh.
  60643. * Returns the mesh.
  60644. */
  60645. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60646. var meshBB = this._sourceMesh.getBoundingInfo();
  60647. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60648. this._updateBoundingInfo();
  60649. return this;
  60650. };
  60651. InstancedMesh.prototype._preActivate = function () {
  60652. if (this._currentLOD) {
  60653. this._currentLOD._preActivate();
  60654. }
  60655. return this;
  60656. };
  60657. InstancedMesh.prototype._activate = function (renderId) {
  60658. if (this._currentLOD) {
  60659. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60660. }
  60661. return this;
  60662. };
  60663. /**
  60664. * Returns the current associated LOD AbstractMesh.
  60665. */
  60666. InstancedMesh.prototype.getLOD = function (camera) {
  60667. if (!camera) {
  60668. return this;
  60669. }
  60670. var boundingInfo = this.getBoundingInfo();
  60671. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60672. if (this._currentLOD === this.sourceMesh) {
  60673. return this;
  60674. }
  60675. return this._currentLOD;
  60676. };
  60677. InstancedMesh.prototype._syncSubMeshes = function () {
  60678. this.releaseSubMeshes();
  60679. if (this._sourceMesh.subMeshes) {
  60680. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60681. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60682. }
  60683. }
  60684. return this;
  60685. };
  60686. InstancedMesh.prototype._generatePointsArray = function () {
  60687. return this._sourceMesh._generatePointsArray();
  60688. };
  60689. /**
  60690. * Creates a new InstancedMesh from the current mesh.
  60691. * - name (string) : the cloned mesh name
  60692. * - newParent (optional Node) : the optional Node to parent the clone to.
  60693. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60694. *
  60695. * Returns the clone.
  60696. */
  60697. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60698. var result = this._sourceMesh.createInstance(name);
  60699. // Deep copy
  60700. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60701. // Bounding info
  60702. this.refreshBoundingInfo();
  60703. // Parent
  60704. if (newParent) {
  60705. result.parent = newParent;
  60706. }
  60707. if (!doNotCloneChildren) {
  60708. // Children
  60709. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60710. var mesh = this.getScene().meshes[index];
  60711. if (mesh.parent === this) {
  60712. mesh.clone(mesh.name, result);
  60713. }
  60714. }
  60715. }
  60716. result.computeWorldMatrix(true);
  60717. return result;
  60718. };
  60719. /**
  60720. * Disposes the InstancedMesh.
  60721. * Returns nothing.
  60722. */
  60723. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60724. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60725. // Remove from mesh
  60726. var index = this._sourceMesh.instances.indexOf(this);
  60727. this._sourceMesh.instances.splice(index, 1);
  60728. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60729. };
  60730. return InstancedMesh;
  60731. }(BABYLON.AbstractMesh));
  60732. BABYLON.InstancedMesh = InstancedMesh;
  60733. })(BABYLON || (BABYLON = {}));
  60734. //# sourceMappingURL=babylon.instancedMesh.js.map
  60735. var BABYLON;
  60736. (function (BABYLON) {
  60737. var LinesMesh = /** @class */ (function (_super) {
  60738. __extends(LinesMesh, _super);
  60739. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60740. if (scene === void 0) { scene = null; }
  60741. if (parent === void 0) { parent = null; }
  60742. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60743. _this.useVertexColor = useVertexColor;
  60744. _this.useVertexAlpha = useVertexAlpha;
  60745. _this.color = new BABYLON.Color3(1, 1, 1);
  60746. _this.alpha = 1;
  60747. if (source) {
  60748. _this.color = source.color.clone();
  60749. _this.alpha = source.alpha;
  60750. _this.useVertexColor = source.useVertexColor;
  60751. _this.useVertexAlpha = source.useVertexAlpha;
  60752. }
  60753. _this._intersectionThreshold = 0.1;
  60754. var defines = [];
  60755. var options = {
  60756. attributes: [BABYLON.VertexBuffer.PositionKind],
  60757. uniforms: ["world", "viewProjection"],
  60758. needAlphaBlending: true,
  60759. defines: defines
  60760. };
  60761. if (useVertexAlpha === false) {
  60762. options.needAlphaBlending = false;
  60763. }
  60764. if (!useVertexColor) {
  60765. options.uniforms.push("color");
  60766. }
  60767. else {
  60768. options.defines.push("#define VERTEXCOLOR");
  60769. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60770. }
  60771. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60772. return _this;
  60773. }
  60774. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60775. /**
  60776. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60777. * This margin is expressed in world space coordinates, so its value may vary.
  60778. * Default value is 0.1
  60779. * @returns the intersection Threshold value.
  60780. */
  60781. get: function () {
  60782. return this._intersectionThreshold;
  60783. },
  60784. /**
  60785. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60786. * This margin is expressed in world space coordinates, so its value may vary.
  60787. * @param value the new threshold to apply
  60788. */
  60789. set: function (value) {
  60790. if (this._intersectionThreshold === value) {
  60791. return;
  60792. }
  60793. this._intersectionThreshold = value;
  60794. if (this.geometry) {
  60795. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60796. }
  60797. },
  60798. enumerable: true,
  60799. configurable: true
  60800. });
  60801. /**
  60802. * Returns the string "LineMesh"
  60803. */
  60804. LinesMesh.prototype.getClassName = function () {
  60805. return "LinesMesh";
  60806. };
  60807. Object.defineProperty(LinesMesh.prototype, "material", {
  60808. get: function () {
  60809. return this._colorShader;
  60810. },
  60811. set: function (value) {
  60812. // Do nothing
  60813. },
  60814. enumerable: true,
  60815. configurable: true
  60816. });
  60817. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60818. get: function () {
  60819. return false;
  60820. },
  60821. enumerable: true,
  60822. configurable: true
  60823. });
  60824. LinesMesh.prototype.createInstance = function (name) {
  60825. throw new Error("LinesMeshes do not support createInstance.");
  60826. };
  60827. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60828. if (!this._geometry) {
  60829. return this;
  60830. }
  60831. // VBOs
  60832. this._geometry._bind(this._colorShader.getEffect());
  60833. // Color
  60834. if (!this.useVertexColor) {
  60835. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60836. }
  60837. return this;
  60838. };
  60839. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60840. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60841. return this;
  60842. }
  60843. var engine = this.getScene().getEngine();
  60844. // Draw order
  60845. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60846. return this;
  60847. };
  60848. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60849. this._colorShader.dispose();
  60850. _super.prototype.dispose.call(this, doNotRecurse);
  60851. };
  60852. /**
  60853. * Returns a new LineMesh object cloned from the current one.
  60854. */
  60855. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60856. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60857. };
  60858. return LinesMesh;
  60859. }(BABYLON.Mesh));
  60860. BABYLON.LinesMesh = LinesMesh;
  60861. })(BABYLON || (BABYLON = {}));
  60862. //# sourceMappingURL=babylon.linesMesh.js.map
  60863. var BABYLON;
  60864. (function (BABYLON) {
  60865. /**
  60866. * Class containing static functions to help procedurally build meshes
  60867. */
  60868. var MeshBuilder = /** @class */ (function () {
  60869. function MeshBuilder() {
  60870. }
  60871. MeshBuilder.updateSideOrientation = function (orientation) {
  60872. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60873. return BABYLON.Mesh.DOUBLESIDE;
  60874. }
  60875. if (orientation === undefined || orientation === null) {
  60876. return BABYLON.Mesh.FRONTSIDE;
  60877. }
  60878. return orientation;
  60879. };
  60880. /**
  60881. * Creates a box mesh
  60882. * * The parameter `size` sets the size (float) of each box side (default 1)
  60883. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60884. * * 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)
  60885. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60886. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60887. * * 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
  60888. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60889. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60890. * @param name defines the name of the mesh
  60891. * @param options defines the options used to create the mesh
  60892. * @param scene defines the hosting scene
  60893. * @returns the box mesh
  60894. */
  60895. MeshBuilder.CreateBox = function (name, options, scene) {
  60896. if (scene === void 0) { scene = null; }
  60897. var box = new BABYLON.Mesh(name, scene);
  60898. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60899. box._originalBuilderSideOrientation = options.sideOrientation;
  60900. var vertexData = BABYLON.VertexData.CreateBox(options);
  60901. vertexData.applyToMesh(box, options.updatable);
  60902. return box;
  60903. };
  60904. /**
  60905. * Creates a sphere mesh
  60906. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60907. * * 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`)
  60908. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60909. * * 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
  60910. * * 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)
  60911. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60912. * * 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
  60913. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60914. * @param name defines the name of the mesh
  60915. * @param options defines the options used to create the mesh
  60916. * @param scene defines the hosting scene
  60917. * @returns the sphere mesh
  60918. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60919. */
  60920. MeshBuilder.CreateSphere = function (name, options, scene) {
  60921. var sphere = new BABYLON.Mesh(name, scene);
  60922. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60923. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60924. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60925. vertexData.applyToMesh(sphere, options.updatable);
  60926. return sphere;
  60927. };
  60928. /**
  60929. * Creates a plane polygonal mesh. By default, this is a disc
  60930. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60931. * * 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
  60932. * * 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
  60933. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60934. * * 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
  60935. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60936. * @param name defines the name of the mesh
  60937. * @param options defines the options used to create the mesh
  60938. * @param scene defines the hosting scene
  60939. * @returns the plane polygonal mesh
  60940. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60941. */
  60942. MeshBuilder.CreateDisc = function (name, options, scene) {
  60943. if (scene === void 0) { scene = null; }
  60944. var disc = new BABYLON.Mesh(name, scene);
  60945. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60946. disc._originalBuilderSideOrientation = options.sideOrientation;
  60947. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60948. vertexData.applyToMesh(disc, options.updatable);
  60949. return disc;
  60950. };
  60951. /**
  60952. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60953. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60954. * * 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`)
  60955. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60956. * * 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
  60957. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60958. * * 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
  60959. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60960. * @param name defines the name of the mesh
  60961. * @param options defines the options used to create the mesh
  60962. * @param scene defines the hosting scene
  60963. * @returns the icosahedron mesh
  60964. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60965. */
  60966. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60967. var sphere = new BABYLON.Mesh(name, scene);
  60968. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60969. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60970. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60971. vertexData.applyToMesh(sphere, options.updatable);
  60972. return sphere;
  60973. };
  60974. ;
  60975. /**
  60976. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60977. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60978. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60979. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60980. * * 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
  60981. * * 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
  60982. * * 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
  60983. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60984. * * 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
  60985. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60986. * * 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
  60987. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60988. * * 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
  60989. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60990. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60991. * @param name defines the name of the mesh
  60992. * @param options defines the options used to create the mesh
  60993. * @param scene defines the hosting scene
  60994. * @returns the ribbon mesh
  60995. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60996. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60997. */
  60998. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60999. if (scene === void 0) { scene = null; }
  61000. var pathArray = options.pathArray;
  61001. var closeArray = options.closeArray;
  61002. var closePath = options.closePath;
  61003. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61004. var instance = options.instance;
  61005. var updatable = options.updatable;
  61006. if (instance) { // existing ribbon instance update
  61007. // positionFunction : ribbon case
  61008. // only pathArray and sideOrientation parameters are taken into account for positions update
  61009. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61010. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61011. var positionFunction = function (positions) {
  61012. var minlg = pathArray[0].length;
  61013. var i = 0;
  61014. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61015. for (var si = 1; si <= ns; si++) {
  61016. for (var p = 0; p < pathArray.length; p++) {
  61017. var path = pathArray[p];
  61018. var l = path.length;
  61019. minlg = (minlg < l) ? minlg : l;
  61020. var j = 0;
  61021. while (j < minlg) {
  61022. positions[i] = path[j].x;
  61023. positions[i + 1] = path[j].y;
  61024. positions[i + 2] = path[j].z;
  61025. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61026. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61027. }
  61028. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61029. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61030. }
  61031. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61032. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61033. }
  61034. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61035. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61036. }
  61037. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61038. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61039. }
  61040. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61041. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61042. }
  61043. j++;
  61044. i += 3;
  61045. }
  61046. if (instance._closePath) {
  61047. positions[i] = path[0].x;
  61048. positions[i + 1] = path[0].y;
  61049. positions[i + 2] = path[0].z;
  61050. i += 3;
  61051. }
  61052. }
  61053. }
  61054. };
  61055. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61056. positionFunction(positions);
  61057. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61058. instance._boundingInfo.update(instance._worldMatrix);
  61059. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61060. if (options.colors) {
  61061. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61062. for (var c = 0; c < options.colors.length; c++) {
  61063. colors[c * 4] = options.colors[c].r;
  61064. colors[c * 4 + 1] = options.colors[c].g;
  61065. colors[c * 4 + 2] = options.colors[c].b;
  61066. colors[c * 4 + 3] = options.colors[c].a;
  61067. }
  61068. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61069. }
  61070. if (options.uvs) {
  61071. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61072. for (var i = 0; i < options.uvs.length; i++) {
  61073. uvs[i * 2] = options.uvs[i].x;
  61074. uvs[i * 2 + 1] = options.uvs[i].y;
  61075. }
  61076. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61077. }
  61078. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61079. var indices = instance.getIndices();
  61080. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61081. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61082. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61083. if (instance._closePath) {
  61084. var indexFirst = 0;
  61085. var indexLast = 0;
  61086. for (var p = 0; p < pathArray.length; p++) {
  61087. indexFirst = instance._idx[p] * 3;
  61088. if (p + 1 < pathArray.length) {
  61089. indexLast = (instance._idx[p + 1] - 1) * 3;
  61090. }
  61091. else {
  61092. indexLast = normals.length - 3;
  61093. }
  61094. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61095. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61096. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61097. normals[indexLast] = normals[indexFirst];
  61098. normals[indexLast + 1] = normals[indexFirst + 1];
  61099. normals[indexLast + 2] = normals[indexFirst + 2];
  61100. }
  61101. }
  61102. if (!(instance.areNormalsFrozen)) {
  61103. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61104. }
  61105. }
  61106. return instance;
  61107. }
  61108. else { // new ribbon creation
  61109. var ribbon = new BABYLON.Mesh(name, scene);
  61110. ribbon._originalBuilderSideOrientation = sideOrientation;
  61111. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61112. if (closePath) {
  61113. ribbon._idx = vertexData._idx;
  61114. }
  61115. ribbon._closePath = closePath;
  61116. ribbon._closeArray = closeArray;
  61117. vertexData.applyToMesh(ribbon, updatable);
  61118. return ribbon;
  61119. }
  61120. };
  61121. /**
  61122. * Creates a cylinder or a cone mesh
  61123. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61124. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61125. * * 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.
  61126. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61127. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61128. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61129. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61130. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61131. * * 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).
  61132. * * 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
  61133. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61134. * * 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
  61135. * * 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.
  61136. * * If `enclose` is false, a ring surface is one element.
  61137. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61138. * * 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
  61139. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61140. * * 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
  61141. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61142. * @param name defines the name of the mesh
  61143. * @param options defines the options used to create the mesh
  61144. * @param scene defines the hosting scene
  61145. * @returns the cylinder mesh
  61146. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61147. */
  61148. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61149. var cylinder = new BABYLON.Mesh(name, scene);
  61150. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61151. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61152. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61153. vertexData.applyToMesh(cylinder, options.updatable);
  61154. return cylinder;
  61155. };
  61156. /**
  61157. * Creates a torus mesh
  61158. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61159. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61160. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61161. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61162. * * 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
  61163. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61164. * @param name defines the name of the mesh
  61165. * @param options defines the options used to create the mesh
  61166. * @param scene defines the hosting scene
  61167. * @returns the torus mesh
  61168. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61169. */
  61170. MeshBuilder.CreateTorus = function (name, options, scene) {
  61171. var torus = new BABYLON.Mesh(name, scene);
  61172. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61173. torus._originalBuilderSideOrientation = options.sideOrientation;
  61174. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61175. vertexData.applyToMesh(torus, options.updatable);
  61176. return torus;
  61177. };
  61178. /**
  61179. * Creates a torus knot mesh
  61180. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61181. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61182. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61183. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61184. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61185. * * 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
  61186. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61187. * @param name defines the name of the mesh
  61188. * @param options defines the options used to create the mesh
  61189. * @param scene defines the hosting scene
  61190. * @returns the torus knot mesh
  61191. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61192. */
  61193. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61194. var torusKnot = new BABYLON.Mesh(name, scene);
  61195. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61196. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61197. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61198. vertexData.applyToMesh(torusKnot, options.updatable);
  61199. return torusKnot;
  61200. };
  61201. /**
  61202. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61203. * * 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
  61204. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61205. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61206. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61207. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61208. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61209. * * 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
  61210. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61211. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61212. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61213. * @param name defines the name of the new line system
  61214. * @param options defines the options used to create the line system
  61215. * @param scene defines the hosting scene
  61216. * @returns a new line system mesh
  61217. */
  61218. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61219. var instance = options.instance;
  61220. var lines = options.lines;
  61221. var colors = options.colors;
  61222. if (instance) { // lines update
  61223. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61224. var vertexColor;
  61225. var lineColors;
  61226. if (colors) {
  61227. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61228. }
  61229. var i = 0;
  61230. var c = 0;
  61231. for (var l = 0; l < lines.length; l++) {
  61232. var points = lines[l];
  61233. for (var p = 0; p < points.length; p++) {
  61234. positions[i] = points[p].x;
  61235. positions[i + 1] = points[p].y;
  61236. positions[i + 2] = points[p].z;
  61237. if (colors && vertexColor) {
  61238. lineColors = colors[l];
  61239. vertexColor[c] = lineColors[p].r;
  61240. vertexColor[c + 1] = lineColors[p].g;
  61241. vertexColor[c + 2] = lineColors[p].b;
  61242. vertexColor[c + 3] = lineColors[p].a;
  61243. c += 4;
  61244. }
  61245. i += 3;
  61246. }
  61247. }
  61248. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61249. if (colors && vertexColor) {
  61250. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61251. }
  61252. return instance;
  61253. }
  61254. // line system creation
  61255. var useVertexColor = (colors) ? true : false;
  61256. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61257. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61258. vertexData.applyToMesh(lineSystem, options.updatable);
  61259. return lineSystem;
  61260. };
  61261. /**
  61262. * Creates a line mesh
  61263. * 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
  61264. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61265. * * The parameter `points` is an array successive Vector3
  61266. * * 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
  61267. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61268. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61269. * * When updating an instance, remember that only point positions can change, not the number of points
  61270. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61271. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61272. * @param name defines the name of the new line system
  61273. * @param options defines the options used to create the line system
  61274. * @param scene defines the hosting scene
  61275. * @returns a new line mesh
  61276. */
  61277. MeshBuilder.CreateLines = function (name, options, scene) {
  61278. if (scene === void 0) { scene = null; }
  61279. var colors = (options.colors) ? [options.colors] : null;
  61280. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61281. return lines;
  61282. };
  61283. /**
  61284. * Creates a dashed line mesh
  61285. * * 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
  61286. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61287. * * The parameter `points` is an array successive Vector3
  61288. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61289. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61290. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61291. * * 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
  61292. * * When updating an instance, remember that only point positions can change, not the number of points
  61293. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61294. * @param name defines the name of the mesh
  61295. * @param options defines the options used to create the mesh
  61296. * @param scene defines the hosting scene
  61297. * @returns the dashed line mesh
  61298. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61299. */
  61300. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61301. if (scene === void 0) { scene = null; }
  61302. var points = options.points;
  61303. var instance = options.instance;
  61304. var gapSize = options.gapSize || 1;
  61305. var dashSize = options.dashSize || 3;
  61306. if (instance) { // dashed lines update
  61307. var positionFunction = function (positions) {
  61308. var curvect = BABYLON.Vector3.Zero();
  61309. var nbSeg = positions.length / 6;
  61310. var lg = 0;
  61311. var nb = 0;
  61312. var shft = 0;
  61313. var dashshft = 0;
  61314. var curshft = 0;
  61315. var p = 0;
  61316. var i = 0;
  61317. var j = 0;
  61318. for (i = 0; i < points.length - 1; i++) {
  61319. points[i + 1].subtractToRef(points[i], curvect);
  61320. lg += curvect.length();
  61321. }
  61322. shft = lg / nbSeg;
  61323. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61324. for (i = 0; i < points.length - 1; i++) {
  61325. points[i + 1].subtractToRef(points[i], curvect);
  61326. nb = Math.floor(curvect.length() / shft);
  61327. curvect.normalize();
  61328. j = 0;
  61329. while (j < nb && p < positions.length) {
  61330. curshft = shft * j;
  61331. positions[p] = points[i].x + curshft * curvect.x;
  61332. positions[p + 1] = points[i].y + curshft * curvect.y;
  61333. positions[p + 2] = points[i].z + curshft * curvect.z;
  61334. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61335. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61336. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61337. p += 6;
  61338. j++;
  61339. }
  61340. }
  61341. while (p < positions.length) {
  61342. positions[p] = points[i].x;
  61343. positions[p + 1] = points[i].y;
  61344. positions[p + 2] = points[i].z;
  61345. p += 3;
  61346. }
  61347. };
  61348. instance.updateMeshPositions(positionFunction, false);
  61349. return instance;
  61350. }
  61351. // dashed lines creation
  61352. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61353. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61354. vertexData.applyToMesh(dashedLines, options.updatable);
  61355. dashedLines.dashSize = dashSize;
  61356. dashedLines.gapSize = gapSize;
  61357. return dashedLines;
  61358. };
  61359. /**
  61360. * 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.
  61361. * * 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.
  61362. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61363. * * 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.
  61364. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61365. * * 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
  61366. * * 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
  61367. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61368. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61369. * * 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
  61370. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61371. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61372. * @param name defines the name of the mesh
  61373. * @param options defines the options used to create the mesh
  61374. * @param scene defines the hosting scene
  61375. * @returns the extruded shape mesh
  61376. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61377. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61378. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61379. */
  61380. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61381. if (scene === void 0) { scene = null; }
  61382. var path = options.path;
  61383. var shape = options.shape;
  61384. var scale = options.scale || 1;
  61385. var rotation = options.rotation || 0;
  61386. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61387. var updatable = options.updatable;
  61388. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61389. var instance = options.instance || null;
  61390. var invertUV = options.invertUV || false;
  61391. 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);
  61392. };
  61393. /**
  61394. * Creates an custom extruded shape mesh.
  61395. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61396. * * 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.
  61397. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61398. * * 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
  61399. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61400. * * 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
  61401. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61402. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61403. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61404. * * 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
  61405. * * 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
  61406. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61407. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61408. * * 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
  61409. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61410. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61411. * @param name defines the name of the mesh
  61412. * @param options defines the options used to create the mesh
  61413. * @param scene defines the hosting scene
  61414. * @returns the custom extruded shape mesh
  61415. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61416. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61417. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61418. */
  61419. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61420. var path = options.path;
  61421. var shape = options.shape;
  61422. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61423. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61424. var ribbonCloseArray = options.ribbonCloseArray || false;
  61425. var ribbonClosePath = options.ribbonClosePath || false;
  61426. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61427. var updatable = options.updatable;
  61428. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61429. var instance = options.instance;
  61430. var invertUV = options.invertUV || false;
  61431. 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);
  61432. };
  61433. /**
  61434. * Creates lathe mesh.
  61435. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61436. * * 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
  61437. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61438. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61439. * * 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
  61440. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61441. * * 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
  61442. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61443. * * 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
  61444. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61445. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61446. * @param name defines the name of the mesh
  61447. * @param options defines the options used to create the mesh
  61448. * @param scene defines the hosting scene
  61449. * @returns the lathe mesh
  61450. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61451. */
  61452. MeshBuilder.CreateLathe = function (name, options, scene) {
  61453. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61454. var closed = (options.closed === undefined) ? true : options.closed;
  61455. var shape = options.shape;
  61456. var radius = options.radius || 1;
  61457. var tessellation = options.tessellation || 64;
  61458. var updatable = options.updatable;
  61459. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61460. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61461. var pi2 = Math.PI * 2;
  61462. var paths = new Array();
  61463. var invertUV = options.invertUV || false;
  61464. var i = 0;
  61465. var p = 0;
  61466. var step = pi2 / tessellation * arc;
  61467. var rotated;
  61468. var path = new Array();
  61469. for (i = 0; i <= tessellation; i++) {
  61470. var path = [];
  61471. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61472. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61473. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61474. }
  61475. for (p = 0; p < shape.length; p++) {
  61476. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61477. path.push(rotated);
  61478. }
  61479. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61480. 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));
  61481. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61482. }
  61483. paths.push(path);
  61484. }
  61485. // lathe ribbon
  61486. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61487. return lathe;
  61488. };
  61489. /**
  61490. * Creates a plane mesh
  61491. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61492. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61493. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61494. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61495. * * 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
  61496. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61497. * @param name defines the name of the mesh
  61498. * @param options defines the options used to create the mesh
  61499. * @param scene defines the hosting scene
  61500. * @returns the plane mesh
  61501. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61502. */
  61503. MeshBuilder.CreatePlane = function (name, options, scene) {
  61504. var plane = new BABYLON.Mesh(name, scene);
  61505. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61506. plane._originalBuilderSideOrientation = options.sideOrientation;
  61507. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61508. vertexData.applyToMesh(plane, options.updatable);
  61509. if (options.sourcePlane) {
  61510. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61511. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61512. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61513. plane.rotate(vectorProduct, product);
  61514. }
  61515. return plane;
  61516. };
  61517. /**
  61518. * Creates a ground mesh
  61519. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61520. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61521. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61522. * @param name defines the name of the mesh
  61523. * @param options defines the options used to create the mesh
  61524. * @param scene defines the hosting scene
  61525. * @returns the ground mesh
  61526. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61527. */
  61528. MeshBuilder.CreateGround = function (name, options, scene) {
  61529. var ground = new BABYLON.GroundMesh(name, scene);
  61530. ground._setReady(false);
  61531. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61532. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61533. ground._width = options.width || 1;
  61534. ground._height = options.height || 1;
  61535. ground._maxX = ground._width / 2;
  61536. ground._maxZ = ground._height / 2;
  61537. ground._minX = -ground._maxX;
  61538. ground._minZ = -ground._maxZ;
  61539. var vertexData = BABYLON.VertexData.CreateGround(options);
  61540. vertexData.applyToMesh(ground, options.updatable);
  61541. ground._setReady(true);
  61542. return ground;
  61543. };
  61544. /**
  61545. * Creates a tiled ground mesh
  61546. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61547. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61548. * * 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
  61549. * * 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
  61550. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61551. * @param name defines the name of the mesh
  61552. * @param options defines the options used to create the mesh
  61553. * @param scene defines the hosting scene
  61554. * @returns the tiled ground mesh
  61555. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61556. */
  61557. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61558. var tiledGround = new BABYLON.Mesh(name, scene);
  61559. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61560. vertexData.applyToMesh(tiledGround, options.updatable);
  61561. return tiledGround;
  61562. };
  61563. /**
  61564. * Creates a ground mesh from a height map
  61565. * * The parameter `url` sets the URL of the height map image resource.
  61566. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61567. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61568. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61569. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61570. * * 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.
  61571. * * 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).
  61572. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61573. * @param name defines the name of the mesh
  61574. * @param url defines the url to the height map
  61575. * @param options defines the options used to create the mesh
  61576. * @param scene defines the hosting scene
  61577. * @returns the ground mesh
  61578. * @see http://doc.babylonjs.com/babylon101/height_map
  61579. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61580. */
  61581. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61582. var width = options.width || 10.0;
  61583. var height = options.height || 10.0;
  61584. var subdivisions = options.subdivisions || 1 | 0;
  61585. var minHeight = options.minHeight || 0.0;
  61586. var maxHeight = options.maxHeight || 1.0;
  61587. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61588. var updatable = options.updatable;
  61589. var onReady = options.onReady;
  61590. var ground = new BABYLON.GroundMesh(name, scene);
  61591. ground._subdivisionsX = subdivisions;
  61592. ground._subdivisionsY = subdivisions;
  61593. ground._width = width;
  61594. ground._height = height;
  61595. ground._maxX = ground._width / 2.0;
  61596. ground._maxZ = ground._height / 2.0;
  61597. ground._minX = -ground._maxX;
  61598. ground._minZ = -ground._maxZ;
  61599. ground._setReady(false);
  61600. var onload = function (img) {
  61601. // Getting height map data
  61602. var canvas = document.createElement("canvas");
  61603. var context = canvas.getContext("2d");
  61604. if (!context) {
  61605. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61606. }
  61607. if (scene.isDisposed) {
  61608. return;
  61609. }
  61610. var bufferWidth = img.width;
  61611. var bufferHeight = img.height;
  61612. canvas.width = bufferWidth;
  61613. canvas.height = bufferHeight;
  61614. context.drawImage(img, 0, 0);
  61615. // Create VertexData from map data
  61616. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61617. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61618. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61619. width: width, height: height,
  61620. subdivisions: subdivisions,
  61621. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61622. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61623. });
  61624. vertexData.applyToMesh(ground, updatable);
  61625. //execute ready callback, if set
  61626. if (onReady) {
  61627. onReady(ground);
  61628. }
  61629. ground._setReady(true);
  61630. };
  61631. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61632. return ground;
  61633. };
  61634. /**
  61635. * Creates a polygon mesh
  61636. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61637. * * 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
  61638. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61639. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61640. * * 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)
  61641. * * Remember you can only change the shape positions, not their number when updating a polygon
  61642. * @param name defines the name of the mesh
  61643. * @param options defines the options used to create the mesh
  61644. * @param scene defines the hosting scene
  61645. * @returns the polygon mesh
  61646. */
  61647. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61648. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61649. var shape = options.shape;
  61650. var holes = options.holes || [];
  61651. var depth = options.depth || 0;
  61652. var contours = [];
  61653. var hole = [];
  61654. for (var i = 0; i < shape.length; i++) {
  61655. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61656. }
  61657. var epsilon = 0.00000001;
  61658. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61659. contours.pop();
  61660. }
  61661. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61662. for (var hNb = 0; hNb < holes.length; hNb++) {
  61663. hole = [];
  61664. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61665. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61666. }
  61667. polygonTriangulation.addHole(hole);
  61668. }
  61669. var polygon = polygonTriangulation.build(options.updatable, depth);
  61670. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61671. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61672. vertexData.applyToMesh(polygon, options.updatable);
  61673. return polygon;
  61674. };
  61675. ;
  61676. /**
  61677. * Creates an extruded polygon mesh, with depth in the Y direction.
  61678. * * 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)
  61679. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61680. * @param name defines the name of the mesh
  61681. * @param options defines the options used to create the mesh
  61682. * @param scene defines the hosting scene
  61683. * @returns the polygon mesh
  61684. */
  61685. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61686. return MeshBuilder.CreatePolygon(name, options, scene);
  61687. };
  61688. ;
  61689. /**
  61690. * Creates a tube mesh.
  61691. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61692. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61693. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61694. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61695. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61696. * * 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)
  61697. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61698. * * 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
  61699. * * 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
  61700. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61701. * * 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
  61702. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61703. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61704. * @param name defines the name of the mesh
  61705. * @param options defines the options used to create the mesh
  61706. * @param scene defines the hosting scene
  61707. * @returns the tube mesh
  61708. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61709. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61710. */
  61711. MeshBuilder.CreateTube = function (name, options, scene) {
  61712. var path = options.path;
  61713. var instance = options.instance;
  61714. var radius = 1.0;
  61715. if (instance) {
  61716. radius = instance.radius;
  61717. }
  61718. if (options.radius !== undefined) {
  61719. radius = options.radius;
  61720. }
  61721. ;
  61722. var tessellation = options.tessellation || 64 | 0;
  61723. var radiusFunction = options.radiusFunction || null;
  61724. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61725. var invertUV = options.invertUV || false;
  61726. var updatable = options.updatable;
  61727. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61728. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61729. // tube geometry
  61730. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61731. var tangents = path3D.getTangents();
  61732. var normals = path3D.getNormals();
  61733. var distances = path3D.getDistances();
  61734. var pi2 = Math.PI * 2;
  61735. var step = pi2 / tessellation * arc;
  61736. var returnRadius = function () { return radius; };
  61737. var radiusFunctionFinal = radiusFunction || returnRadius;
  61738. var circlePath;
  61739. var rad;
  61740. var normal;
  61741. var rotated;
  61742. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61743. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61744. for (var i = 0; i < path.length; i++) {
  61745. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61746. circlePath = Array(); // current circle array
  61747. normal = normals[i]; // current normal
  61748. for (var t = 0; t < tessellation; t++) {
  61749. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61750. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61751. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61752. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61753. circlePath[t] = rotated;
  61754. }
  61755. circlePaths[index] = circlePath;
  61756. index++;
  61757. }
  61758. // cap
  61759. var capPath = function (nbPoints, pathIndex) {
  61760. var pointCap = Array();
  61761. for (var i = 0; i < nbPoints; i++) {
  61762. pointCap.push(path[pathIndex]);
  61763. }
  61764. return pointCap;
  61765. };
  61766. switch (cap) {
  61767. case BABYLON.Mesh.NO_CAP:
  61768. break;
  61769. case BABYLON.Mesh.CAP_START:
  61770. circlePaths[0] = capPath(tessellation, 0);
  61771. circlePaths[1] = circlePaths[2].slice(0);
  61772. break;
  61773. case BABYLON.Mesh.CAP_END:
  61774. circlePaths[index] = circlePaths[index - 1].slice(0);
  61775. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61776. break;
  61777. case BABYLON.Mesh.CAP_ALL:
  61778. circlePaths[0] = capPath(tessellation, 0);
  61779. circlePaths[1] = circlePaths[2].slice(0);
  61780. circlePaths[index] = circlePaths[index - 1].slice(0);
  61781. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61782. break;
  61783. default:
  61784. break;
  61785. }
  61786. return circlePaths;
  61787. };
  61788. var path3D;
  61789. var pathArray;
  61790. if (instance) { // tube update
  61791. var arc = options.arc || instance.arc;
  61792. path3D = (instance.path3D).update(path);
  61793. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61794. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61795. instance.path3D = path3D;
  61796. instance.pathArray = pathArray;
  61797. instance.arc = arc;
  61798. instance.radius = radius;
  61799. return instance;
  61800. }
  61801. // tube creation
  61802. path3D = new BABYLON.Path3D(path);
  61803. var newPathArray = new Array();
  61804. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61805. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61806. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61807. tube.pathArray = pathArray;
  61808. tube.path3D = path3D;
  61809. tube.tessellation = tessellation;
  61810. tube.cap = cap;
  61811. tube.arc = options.arc;
  61812. tube.radius = radius;
  61813. return tube;
  61814. };
  61815. /**
  61816. * Creates a polyhedron mesh
  61817. * * 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
  61818. * * The parameter `size` (positive float, default 1) sets the polygon size
  61819. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61820. * * 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`
  61821. * * 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
  61822. * * 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)`)
  61823. * * 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
  61824. * * 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
  61825. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61826. * * 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
  61827. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61828. * @param name defines the name of the mesh
  61829. * @param options defines the options used to create the mesh
  61830. * @param scene defines the hosting scene
  61831. * @returns the polyhedron mesh
  61832. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61833. */
  61834. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61835. var polyhedron = new BABYLON.Mesh(name, scene);
  61836. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61837. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61838. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61839. vertexData.applyToMesh(polyhedron, options.updatable);
  61840. return polyhedron;
  61841. };
  61842. /**
  61843. * Creates a decal mesh.
  61844. * 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
  61845. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61846. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61847. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61848. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61849. * @param name defines the name of the mesh
  61850. * @param sourceMesh defines the mesh where the decal must be applied
  61851. * @param options defines the options used to create the mesh
  61852. * @param scene defines the hosting scene
  61853. * @returns the decal mesh
  61854. * @see http://doc.babylonjs.com/how_to/decals
  61855. */
  61856. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61857. var indices = sourceMesh.getIndices();
  61858. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61859. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61860. var position = options.position || BABYLON.Vector3.Zero();
  61861. var normal = options.normal || BABYLON.Vector3.Up();
  61862. var size = options.size || BABYLON.Vector3.One();
  61863. var angle = options.angle || 0;
  61864. // Getting correct rotation
  61865. if (!normal) {
  61866. var target = new BABYLON.Vector3(0, 0, 1);
  61867. var camera = sourceMesh.getScene().activeCamera;
  61868. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61869. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61870. }
  61871. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61872. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61873. var pitch = Math.atan2(normal.y, len);
  61874. // Matrix
  61875. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61876. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61877. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61878. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61879. var vertexData = new BABYLON.VertexData();
  61880. vertexData.indices = [];
  61881. vertexData.positions = [];
  61882. vertexData.normals = [];
  61883. vertexData.uvs = [];
  61884. var currentVertexDataIndex = 0;
  61885. var extractDecalVector3 = function (indexId) {
  61886. var result = new BABYLON.PositionNormalVertex();
  61887. if (!indices || !positions || !normals) {
  61888. return result;
  61889. }
  61890. var vertexId = indices[indexId];
  61891. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61892. // Send vector to decal local world
  61893. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61894. // Get normal
  61895. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61896. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61897. return result;
  61898. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61899. var clip = function (vertices, axis) {
  61900. if (vertices.length === 0) {
  61901. return vertices;
  61902. }
  61903. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61904. var clipVertices = function (v0, v1) {
  61905. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61906. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61907. };
  61908. var result = new Array();
  61909. for (var index = 0; index < vertices.length; index += 3) {
  61910. var v1Out;
  61911. var v2Out;
  61912. var v3Out;
  61913. var total = 0;
  61914. var nV1 = null;
  61915. var nV2 = null;
  61916. var nV3 = null;
  61917. var nV4 = null;
  61918. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61919. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61920. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61921. v1Out = d1 > 0;
  61922. v2Out = d2 > 0;
  61923. v3Out = d3 > 0;
  61924. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61925. switch (total) {
  61926. case 0:
  61927. result.push(vertices[index]);
  61928. result.push(vertices[index + 1]);
  61929. result.push(vertices[index + 2]);
  61930. break;
  61931. case 1:
  61932. if (v1Out) {
  61933. nV1 = vertices[index + 1];
  61934. nV2 = vertices[index + 2];
  61935. nV3 = clipVertices(vertices[index], nV1);
  61936. nV4 = clipVertices(vertices[index], nV2);
  61937. }
  61938. if (v2Out) {
  61939. nV1 = vertices[index];
  61940. nV2 = vertices[index + 2];
  61941. nV3 = clipVertices(vertices[index + 1], nV1);
  61942. nV4 = clipVertices(vertices[index + 1], nV2);
  61943. result.push(nV3);
  61944. result.push(nV2.clone());
  61945. result.push(nV1.clone());
  61946. result.push(nV2.clone());
  61947. result.push(nV3.clone());
  61948. result.push(nV4);
  61949. break;
  61950. }
  61951. if (v3Out) {
  61952. nV1 = vertices[index];
  61953. nV2 = vertices[index + 1];
  61954. nV3 = clipVertices(vertices[index + 2], nV1);
  61955. nV4 = clipVertices(vertices[index + 2], nV2);
  61956. }
  61957. if (nV1 && nV2 && nV3 && nV4) {
  61958. result.push(nV1.clone());
  61959. result.push(nV2.clone());
  61960. result.push(nV3);
  61961. result.push(nV4);
  61962. result.push(nV3.clone());
  61963. result.push(nV2.clone());
  61964. }
  61965. break;
  61966. case 2:
  61967. if (!v1Out) {
  61968. nV1 = vertices[index].clone();
  61969. nV2 = clipVertices(nV1, vertices[index + 1]);
  61970. nV3 = clipVertices(nV1, vertices[index + 2]);
  61971. result.push(nV1);
  61972. result.push(nV2);
  61973. result.push(nV3);
  61974. }
  61975. if (!v2Out) {
  61976. nV1 = vertices[index + 1].clone();
  61977. nV2 = clipVertices(nV1, vertices[index + 2]);
  61978. nV3 = clipVertices(nV1, vertices[index]);
  61979. result.push(nV1);
  61980. result.push(nV2);
  61981. result.push(nV3);
  61982. }
  61983. if (!v3Out) {
  61984. nV1 = vertices[index + 2].clone();
  61985. nV2 = clipVertices(nV1, vertices[index]);
  61986. nV3 = clipVertices(nV1, vertices[index + 1]);
  61987. result.push(nV1);
  61988. result.push(nV2);
  61989. result.push(nV3);
  61990. }
  61991. break;
  61992. case 3:
  61993. break;
  61994. }
  61995. }
  61996. return result;
  61997. };
  61998. for (var index = 0; index < indices.length; index += 3) {
  61999. var faceVertices = new Array();
  62000. faceVertices.push(extractDecalVector3(index));
  62001. faceVertices.push(extractDecalVector3(index + 1));
  62002. faceVertices.push(extractDecalVector3(index + 2));
  62003. // Clip
  62004. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62005. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62006. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62007. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62008. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62009. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62010. if (faceVertices.length === 0) {
  62011. continue;
  62012. }
  62013. // Add UVs and get back to world
  62014. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62015. var vertex = faceVertices[vIndex];
  62016. //TODO check for Int32Array | Uint32Array | Uint16Array
  62017. vertexData.indices.push(currentVertexDataIndex);
  62018. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62019. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62020. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62021. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62022. currentVertexDataIndex++;
  62023. }
  62024. }
  62025. // Return mesh
  62026. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62027. vertexData.applyToMesh(decal);
  62028. decal.position = position.clone();
  62029. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62030. return decal;
  62031. };
  62032. // Privates
  62033. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62034. // extrusion geometry
  62035. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62036. var tangents = path3D.getTangents();
  62037. var normals = path3D.getNormals();
  62038. var binormals = path3D.getBinormals();
  62039. var distances = path3D.getDistances();
  62040. var angle = 0;
  62041. var returnScale = function () { return scale !== null ? scale : 1; };
  62042. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62043. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62044. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62045. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62046. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62047. for (var i = 0; i < curve.length; i++) {
  62048. var shapePath = new Array();
  62049. var angleStep = rotate(i, distances[i]);
  62050. var scaleRatio = scl(i, distances[i]);
  62051. for (var p = 0; p < shape.length; p++) {
  62052. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62053. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62054. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62055. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62056. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62057. shapePath[p] = rotated;
  62058. }
  62059. shapePaths[index] = shapePath;
  62060. angle += angleStep;
  62061. index++;
  62062. }
  62063. // cap
  62064. var capPath = function (shapePath) {
  62065. var pointCap = Array();
  62066. var barycenter = BABYLON.Vector3.Zero();
  62067. var i;
  62068. for (i = 0; i < shapePath.length; i++) {
  62069. barycenter.addInPlace(shapePath[i]);
  62070. }
  62071. barycenter.scaleInPlace(1.0 / shapePath.length);
  62072. for (i = 0; i < shapePath.length; i++) {
  62073. pointCap.push(barycenter);
  62074. }
  62075. return pointCap;
  62076. };
  62077. switch (cap) {
  62078. case BABYLON.Mesh.NO_CAP:
  62079. break;
  62080. case BABYLON.Mesh.CAP_START:
  62081. shapePaths[0] = capPath(shapePaths[2]);
  62082. shapePaths[1] = shapePaths[2];
  62083. break;
  62084. case BABYLON.Mesh.CAP_END:
  62085. shapePaths[index] = shapePaths[index - 1];
  62086. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62087. break;
  62088. case BABYLON.Mesh.CAP_ALL:
  62089. shapePaths[0] = capPath(shapePaths[2]);
  62090. shapePaths[1] = shapePaths[2];
  62091. shapePaths[index] = shapePaths[index - 1];
  62092. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62093. break;
  62094. default:
  62095. break;
  62096. }
  62097. return shapePaths;
  62098. };
  62099. var path3D;
  62100. var pathArray;
  62101. if (instance) { // instance update
  62102. path3D = (instance.path3D).update(curve);
  62103. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62104. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62105. return instance;
  62106. }
  62107. // extruded shape creation
  62108. path3D = new BABYLON.Path3D(curve);
  62109. var newShapePaths = new Array();
  62110. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62111. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62112. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62113. extrudedGeneric.pathArray = pathArray;
  62114. extrudedGeneric.path3D = path3D;
  62115. extrudedGeneric.cap = cap;
  62116. return extrudedGeneric;
  62117. };
  62118. return MeshBuilder;
  62119. }());
  62120. BABYLON.MeshBuilder = MeshBuilder;
  62121. })(BABYLON || (BABYLON = {}));
  62122. //# sourceMappingURL=babylon.meshBuilder.js.map
  62123. var BABYLON;
  62124. (function (BABYLON) {
  62125. /**
  62126. * Draco compression (https://google.github.io/draco/)
  62127. *
  62128. * This class wraps the Draco module.
  62129. *
  62130. * **Encoder**
  62131. *
  62132. * The encoder is not currently implemented.
  62133. *
  62134. * **Decoder**
  62135. *
  62136. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62137. *
  62138. * To update the configuration, use the following code:
  62139. * ```javascript
  62140. * BABYLON.DracoCompression.Configuration = {
  62141. * decoder: {
  62142. * wasmUrl: "<url to the WebAssembly library>",
  62143. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62144. * fallbackUrl: "<url to the fallback JavaScript library>",
  62145. * }
  62146. * };
  62147. * ```
  62148. *
  62149. * 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.
  62150. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62151. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62152. *
  62153. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62154. * ```javascript
  62155. * var dracoCompression = new BABYLON.DracoCompression();
  62156. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62157. * [BABYLON.VertexBuffer.PositionKind]: 0
  62158. * });
  62159. * ```
  62160. *
  62161. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62162. */
  62163. var DracoCompression = /** @class */ (function () {
  62164. /**
  62165. * Constructor
  62166. */
  62167. function DracoCompression() {
  62168. }
  62169. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62170. /**
  62171. * Returns true if the decoder is available.
  62172. */
  62173. get: function () {
  62174. if (typeof DracoDecoderModule !== "undefined") {
  62175. return true;
  62176. }
  62177. var decoder = DracoCompression.Configuration.decoder;
  62178. if (decoder) {
  62179. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62180. return true;
  62181. }
  62182. if (decoder.fallbackUrl) {
  62183. return true;
  62184. }
  62185. }
  62186. return false;
  62187. },
  62188. enumerable: true,
  62189. configurable: true
  62190. });
  62191. /**
  62192. * Stop all async operations and release resources.
  62193. */
  62194. DracoCompression.prototype.dispose = function () {
  62195. };
  62196. /**
  62197. * Decode Draco compressed mesh data to vertex data.
  62198. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62199. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62200. * @returns A promise that resolves with the decoded vertex data
  62201. */
  62202. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62203. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62204. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62205. var module = wrappedModule.module;
  62206. var vertexData = new BABYLON.VertexData();
  62207. var buffer = new module.DecoderBuffer();
  62208. buffer.Init(dataView, dataView.byteLength);
  62209. var decoder = new module.Decoder();
  62210. var geometry;
  62211. var status;
  62212. try {
  62213. var type = decoder.GetEncodedGeometryType(buffer);
  62214. switch (type) {
  62215. case module.TRIANGULAR_MESH:
  62216. geometry = new module.Mesh();
  62217. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62218. break;
  62219. case module.POINT_CLOUD:
  62220. geometry = new module.PointCloud();
  62221. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62222. break;
  62223. default:
  62224. throw new Error("Invalid geometry type " + type);
  62225. }
  62226. if (!status.ok() || !geometry.ptr) {
  62227. throw new Error(status.error_msg());
  62228. }
  62229. var numPoints = geometry.num_points();
  62230. if (type === module.TRIANGULAR_MESH) {
  62231. var numFaces = geometry.num_faces();
  62232. var faceIndices = new module.DracoInt32Array();
  62233. try {
  62234. var indices = new Uint32Array(numFaces * 3);
  62235. for (var i = 0; i < numFaces; i++) {
  62236. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62237. var offset = i * 3;
  62238. indices[offset + 0] = faceIndices.GetValue(0);
  62239. indices[offset + 1] = faceIndices.GetValue(1);
  62240. indices[offset + 2] = faceIndices.GetValue(2);
  62241. }
  62242. vertexData.indices = indices;
  62243. }
  62244. finally {
  62245. module.destroy(faceIndices);
  62246. }
  62247. }
  62248. for (var kind in attributes) {
  62249. var uniqueId = attributes[kind];
  62250. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62251. var dracoData = new module.DracoFloat32Array();
  62252. try {
  62253. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62254. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62255. for (var i = 0; i < babylonData.length; i++) {
  62256. babylonData[i] = dracoData.GetValue(i);
  62257. }
  62258. vertexData.set(babylonData, kind);
  62259. }
  62260. finally {
  62261. module.destroy(dracoData);
  62262. }
  62263. }
  62264. }
  62265. finally {
  62266. if (geometry) {
  62267. module.destroy(geometry);
  62268. }
  62269. module.destroy(decoder);
  62270. module.destroy(buffer);
  62271. }
  62272. return vertexData;
  62273. });
  62274. };
  62275. DracoCompression._GetDecoderModule = function () {
  62276. if (!DracoCompression._DecoderModulePromise) {
  62277. var promise = null;
  62278. var config_1 = {};
  62279. if (typeof DracoDecoderModule !== "undefined") {
  62280. promise = Promise.resolve();
  62281. }
  62282. else {
  62283. var decoder = DracoCompression.Configuration.decoder;
  62284. if (decoder) {
  62285. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62286. promise = Promise.all([
  62287. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62288. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62289. config_1.wasmBinary = data;
  62290. })
  62291. ]);
  62292. }
  62293. else if (decoder.fallbackUrl) {
  62294. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62295. }
  62296. }
  62297. }
  62298. if (!promise) {
  62299. throw new Error("Draco decoder module is not available");
  62300. }
  62301. DracoCompression._DecoderModulePromise = promise.then(function () {
  62302. return new Promise(function (resolve) {
  62303. config_1.onModuleLoaded = function (decoderModule) {
  62304. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62305. resolve({ module: decoderModule });
  62306. };
  62307. DracoDecoderModule(config_1);
  62308. });
  62309. });
  62310. }
  62311. return DracoCompression._DecoderModulePromise;
  62312. };
  62313. DracoCompression._LoadScriptAsync = function (url) {
  62314. return new Promise(function (resolve, reject) {
  62315. BABYLON.Tools.LoadScript(url, function () {
  62316. resolve();
  62317. }, function (message) {
  62318. reject(new Error(message));
  62319. });
  62320. });
  62321. };
  62322. DracoCompression._LoadFileAsync = function (url) {
  62323. return new Promise(function (resolve, reject) {
  62324. BABYLON.Tools.LoadFile(url, function (data) {
  62325. resolve(data);
  62326. }, undefined, undefined, true, function (request, exception) {
  62327. reject(exception);
  62328. });
  62329. });
  62330. };
  62331. /**
  62332. * The configuration. Defaults to the following urls:
  62333. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62334. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62335. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62336. */
  62337. DracoCompression.Configuration = {
  62338. decoder: {
  62339. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62340. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62341. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62342. }
  62343. };
  62344. return DracoCompression;
  62345. }());
  62346. BABYLON.DracoCompression = DracoCompression;
  62347. })(BABYLON || (BABYLON = {}));
  62348. //# sourceMappingURL=babylon.dracoCompression.js.map
  62349. var BABYLON;
  62350. (function (BABYLON) {
  62351. var AudioEngine = /** @class */ (function () {
  62352. function AudioEngine() {
  62353. this._audioContext = null;
  62354. this._audioContextInitialized = false;
  62355. this.canUseWebAudio = false;
  62356. this.WarnedWebAudioUnsupported = false;
  62357. this.unlocked = false;
  62358. this.isMP3supported = false;
  62359. this.isOGGsupported = false;
  62360. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62361. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62362. this.canUseWebAudio = true;
  62363. }
  62364. var audioElem = document.createElement('audio');
  62365. try {
  62366. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62367. this.isMP3supported = true;
  62368. }
  62369. }
  62370. catch (e) {
  62371. // protect error during capability check.
  62372. }
  62373. try {
  62374. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62375. this.isOGGsupported = true;
  62376. }
  62377. }
  62378. catch (e) {
  62379. // protect error during capability check.
  62380. }
  62381. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62382. this._unlockiOSaudio();
  62383. }
  62384. else {
  62385. this.unlocked = true;
  62386. }
  62387. }
  62388. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62389. get: function () {
  62390. if (!this._audioContextInitialized) {
  62391. this._initializeAudioContext();
  62392. }
  62393. return this._audioContext;
  62394. },
  62395. enumerable: true,
  62396. configurable: true
  62397. });
  62398. AudioEngine.prototype._unlockiOSaudio = function () {
  62399. var _this = this;
  62400. var unlockaudio = function () {
  62401. if (!_this.audioContext) {
  62402. return;
  62403. }
  62404. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62405. var source = _this.audioContext.createBufferSource();
  62406. source.buffer = buffer;
  62407. source.connect(_this.audioContext.destination);
  62408. source.start(0);
  62409. setTimeout(function () {
  62410. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62411. _this.unlocked = true;
  62412. window.removeEventListener('touchend', unlockaudio, false);
  62413. if (_this.onAudioUnlocked) {
  62414. _this.onAudioUnlocked();
  62415. }
  62416. }
  62417. }, 0);
  62418. };
  62419. window.addEventListener('touchend', unlockaudio, false);
  62420. };
  62421. AudioEngine.prototype._initializeAudioContext = function () {
  62422. try {
  62423. if (this.canUseWebAudio) {
  62424. this._audioContext = new AudioContext();
  62425. // create a global volume gain node
  62426. this.masterGain = this._audioContext.createGain();
  62427. this.masterGain.gain.value = 1;
  62428. this.masterGain.connect(this._audioContext.destination);
  62429. this._audioContextInitialized = true;
  62430. }
  62431. }
  62432. catch (e) {
  62433. this.canUseWebAudio = false;
  62434. BABYLON.Tools.Error("Web Audio: " + e.message);
  62435. }
  62436. };
  62437. AudioEngine.prototype.dispose = function () {
  62438. if (this.canUseWebAudio && this._audioContextInitialized) {
  62439. if (this._connectedAnalyser && this._audioContext) {
  62440. this._connectedAnalyser.stopDebugCanvas();
  62441. this._connectedAnalyser.dispose();
  62442. this.masterGain.disconnect();
  62443. this.masterGain.connect(this._audioContext.destination);
  62444. this._connectedAnalyser = null;
  62445. }
  62446. this.masterGain.gain.value = 1;
  62447. }
  62448. this.WarnedWebAudioUnsupported = false;
  62449. };
  62450. AudioEngine.prototype.getGlobalVolume = function () {
  62451. if (this.canUseWebAudio && this._audioContextInitialized) {
  62452. return this.masterGain.gain.value;
  62453. }
  62454. else {
  62455. return -1;
  62456. }
  62457. };
  62458. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62459. if (this.canUseWebAudio && this._audioContextInitialized) {
  62460. this.masterGain.gain.value = newVolume;
  62461. }
  62462. };
  62463. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62464. if (this._connectedAnalyser) {
  62465. this._connectedAnalyser.stopDebugCanvas();
  62466. }
  62467. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62468. this._connectedAnalyser = analyser;
  62469. this.masterGain.disconnect();
  62470. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62471. }
  62472. };
  62473. return AudioEngine;
  62474. }());
  62475. BABYLON.AudioEngine = AudioEngine;
  62476. })(BABYLON || (BABYLON = {}));
  62477. //# sourceMappingURL=babylon.audioEngine.js.map
  62478. var BABYLON;
  62479. (function (BABYLON) {
  62480. var Sound = /** @class */ (function () {
  62481. /**
  62482. * Create a sound and attach it to a scene
  62483. * @param name Name of your sound
  62484. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62485. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62486. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62487. */
  62488. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62489. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62490. var _this = this;
  62491. this.autoplay = false;
  62492. this.loop = false;
  62493. this.useCustomAttenuation = false;
  62494. this.spatialSound = false;
  62495. this.refDistance = 1;
  62496. this.rolloffFactor = 1;
  62497. this.maxDistance = 100;
  62498. this.distanceModel = "linear";
  62499. this._panningModel = "equalpower";
  62500. this._playbackRate = 1;
  62501. this._streaming = false;
  62502. this._startTime = 0;
  62503. this._startOffset = 0;
  62504. this._position = BABYLON.Vector3.Zero();
  62505. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62506. this._volume = 1;
  62507. this._isReadyToPlay = false;
  62508. this.isPlaying = false;
  62509. this.isPaused = false;
  62510. this._isDirectional = false;
  62511. // Used if you'd like to create a directional sound.
  62512. // If not set, the sound will be omnidirectional
  62513. this._coneInnerAngle = 360;
  62514. this._coneOuterAngle = 360;
  62515. this._coneOuterGain = 0;
  62516. this._isOutputConnected = false;
  62517. this._urlType = "Unknown";
  62518. this.name = name;
  62519. this._scene = scene;
  62520. this._readyToPlayCallback = readyToPlayCallback;
  62521. // Default custom attenuation function is a linear attenuation
  62522. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62523. if (currentDistance < maxDistance) {
  62524. return currentVolume * (1 - currentDistance / maxDistance);
  62525. }
  62526. else {
  62527. return 0;
  62528. }
  62529. };
  62530. if (options) {
  62531. this.autoplay = options.autoplay || false;
  62532. this.loop = options.loop || false;
  62533. // if volume === 0, we need another way to check this option
  62534. if (options.volume !== undefined) {
  62535. this._volume = options.volume;
  62536. }
  62537. this.spatialSound = options.spatialSound || false;
  62538. this.maxDistance = options.maxDistance || 100;
  62539. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62540. this.rolloffFactor = options.rolloffFactor || 1;
  62541. this.refDistance = options.refDistance || 1;
  62542. this.distanceModel = options.distanceModel || "linear";
  62543. this._playbackRate = options.playbackRate || 1;
  62544. this._streaming = options.streaming || false;
  62545. }
  62546. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62547. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62548. this._soundGain.gain.value = this._volume;
  62549. this._inputAudioNode = this._soundGain;
  62550. this._ouputAudioNode = this._soundGain;
  62551. if (this.spatialSound) {
  62552. this._createSpatialParameters();
  62553. }
  62554. this._scene.mainSoundTrack.AddSound(this);
  62555. var validParameter = true;
  62556. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62557. if (urlOrArrayBuffer) {
  62558. try {
  62559. if (typeof (urlOrArrayBuffer) === "string") {
  62560. this._urlType = "String";
  62561. }
  62562. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62563. this._urlType = "ArrayBuffer";
  62564. }
  62565. else if (urlOrArrayBuffer instanceof MediaStream) {
  62566. this._urlType = "MediaStream";
  62567. }
  62568. else if (Array.isArray(urlOrArrayBuffer)) {
  62569. this._urlType = "Array";
  62570. }
  62571. var urls = [];
  62572. var codecSupportedFound = false;
  62573. switch (this._urlType) {
  62574. case "MediaStream":
  62575. this._streaming = true;
  62576. this._isReadyToPlay = true;
  62577. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62578. if (this.autoplay) {
  62579. this.play();
  62580. }
  62581. if (this._readyToPlayCallback) {
  62582. this._readyToPlayCallback();
  62583. }
  62584. break;
  62585. case "ArrayBuffer":
  62586. if (urlOrArrayBuffer.byteLength > 0) {
  62587. codecSupportedFound = true;
  62588. this._soundLoaded(urlOrArrayBuffer);
  62589. }
  62590. break;
  62591. case "String":
  62592. urls.push(urlOrArrayBuffer);
  62593. case "Array":
  62594. if (urls.length === 0)
  62595. urls = urlOrArrayBuffer;
  62596. // If we found a supported format, we load it immediately and stop the loop
  62597. for (var i = 0; i < urls.length; i++) {
  62598. var url = urls[i];
  62599. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62600. codecSupportedFound = true;
  62601. }
  62602. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62603. codecSupportedFound = true;
  62604. }
  62605. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62606. codecSupportedFound = true;
  62607. }
  62608. if (url.indexOf("blob:") !== -1) {
  62609. codecSupportedFound = true;
  62610. }
  62611. if (codecSupportedFound) {
  62612. // Loading sound using XHR2
  62613. if (!this._streaming) {
  62614. this._scene._loadFile(url, function (data) {
  62615. _this._soundLoaded(data);
  62616. }, undefined, true, true, function (exception) {
  62617. if (exception) {
  62618. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62619. }
  62620. BABYLON.Tools.Error("Sound creation aborted.");
  62621. _this._scene.mainSoundTrack.RemoveSound(_this);
  62622. });
  62623. }
  62624. // Streaming sound using HTML5 Audio tag
  62625. else {
  62626. this._htmlAudioElement = new Audio(url);
  62627. this._htmlAudioElement.controls = false;
  62628. this._htmlAudioElement.loop = this.loop;
  62629. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62630. this._htmlAudioElement.preload = "auto";
  62631. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62632. _this._isReadyToPlay = true;
  62633. if (_this.autoplay) {
  62634. _this.play();
  62635. }
  62636. if (_this._readyToPlayCallback) {
  62637. _this._readyToPlayCallback();
  62638. }
  62639. });
  62640. document.body.appendChild(this._htmlAudioElement);
  62641. }
  62642. break;
  62643. }
  62644. }
  62645. break;
  62646. default:
  62647. validParameter = false;
  62648. break;
  62649. }
  62650. if (!validParameter) {
  62651. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62652. }
  62653. else {
  62654. if (!codecSupportedFound) {
  62655. this._isReadyToPlay = true;
  62656. // Simulating a ready to play event to avoid breaking code path
  62657. if (this._readyToPlayCallback) {
  62658. window.setTimeout(function () {
  62659. if (_this._readyToPlayCallback) {
  62660. _this._readyToPlayCallback();
  62661. }
  62662. }, 1000);
  62663. }
  62664. }
  62665. }
  62666. }
  62667. catch (ex) {
  62668. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62669. this._scene.mainSoundTrack.RemoveSound(this);
  62670. }
  62671. }
  62672. }
  62673. else {
  62674. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62675. this._scene.mainSoundTrack.AddSound(this);
  62676. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62677. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62678. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62679. }
  62680. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62681. if (this._readyToPlayCallback) {
  62682. window.setTimeout(function () {
  62683. if (_this._readyToPlayCallback) {
  62684. _this._readyToPlayCallback();
  62685. }
  62686. }, 1000);
  62687. }
  62688. }
  62689. }
  62690. Sound.prototype.dispose = function () {
  62691. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62692. if (this.isPlaying) {
  62693. this.stop();
  62694. }
  62695. this._isReadyToPlay = false;
  62696. if (this.soundTrackId === -1) {
  62697. this._scene.mainSoundTrack.RemoveSound(this);
  62698. }
  62699. else {
  62700. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62701. }
  62702. if (this._soundGain) {
  62703. this._soundGain.disconnect();
  62704. this._soundGain = null;
  62705. }
  62706. if (this._soundPanner) {
  62707. this._soundPanner.disconnect();
  62708. this._soundPanner = null;
  62709. }
  62710. if (this._soundSource) {
  62711. this._soundSource.disconnect();
  62712. this._soundSource = null;
  62713. }
  62714. this._audioBuffer = null;
  62715. if (this._htmlAudioElement) {
  62716. this._htmlAudioElement.pause();
  62717. this._htmlAudioElement.src = "";
  62718. document.body.removeChild(this._htmlAudioElement);
  62719. }
  62720. if (this._streamingSource) {
  62721. this._streamingSource.disconnect();
  62722. }
  62723. if (this._connectedMesh && this._registerFunc) {
  62724. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62725. this._connectedMesh = null;
  62726. }
  62727. }
  62728. };
  62729. Sound.prototype.isReady = function () {
  62730. return this._isReadyToPlay;
  62731. };
  62732. Sound.prototype._soundLoaded = function (audioData) {
  62733. var _this = this;
  62734. if (!BABYLON.Engine.audioEngine.audioContext) {
  62735. return;
  62736. }
  62737. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62738. _this._audioBuffer = buffer;
  62739. _this._isReadyToPlay = true;
  62740. if (_this.autoplay) {
  62741. _this.play();
  62742. }
  62743. if (_this._readyToPlayCallback) {
  62744. _this._readyToPlayCallback();
  62745. }
  62746. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62747. };
  62748. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62749. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62750. this._audioBuffer = audioBuffer;
  62751. this._isReadyToPlay = true;
  62752. }
  62753. };
  62754. Sound.prototype.updateOptions = function (options) {
  62755. if (options) {
  62756. this.loop = options.loop || this.loop;
  62757. this.maxDistance = options.maxDistance || this.maxDistance;
  62758. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62759. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62760. this.refDistance = options.refDistance || this.refDistance;
  62761. this.distanceModel = options.distanceModel || this.distanceModel;
  62762. this._playbackRate = options.playbackRate || this._playbackRate;
  62763. this._updateSpatialParameters();
  62764. if (this.isPlaying) {
  62765. if (this._streaming && this._htmlAudioElement) {
  62766. this._htmlAudioElement.playbackRate = this._playbackRate;
  62767. }
  62768. else {
  62769. if (this._soundSource) {
  62770. this._soundSource.playbackRate.value = this._playbackRate;
  62771. }
  62772. }
  62773. }
  62774. }
  62775. };
  62776. Sound.prototype._createSpatialParameters = function () {
  62777. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62778. if (this._scene.headphone) {
  62779. this._panningModel = "HRTF";
  62780. }
  62781. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62782. this._updateSpatialParameters();
  62783. this._soundPanner.connect(this._ouputAudioNode);
  62784. this._inputAudioNode = this._soundPanner;
  62785. }
  62786. };
  62787. Sound.prototype._updateSpatialParameters = function () {
  62788. if (this.spatialSound && this._soundPanner) {
  62789. if (this.useCustomAttenuation) {
  62790. // Tricks to disable in a way embedded Web Audio attenuation
  62791. this._soundPanner.distanceModel = "linear";
  62792. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62793. this._soundPanner.refDistance = 1;
  62794. this._soundPanner.rolloffFactor = 1;
  62795. this._soundPanner.panningModel = this._panningModel;
  62796. }
  62797. else {
  62798. this._soundPanner.distanceModel = this.distanceModel;
  62799. this._soundPanner.maxDistance = this.maxDistance;
  62800. this._soundPanner.refDistance = this.refDistance;
  62801. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62802. this._soundPanner.panningModel = this._panningModel;
  62803. }
  62804. }
  62805. };
  62806. Sound.prototype.switchPanningModelToHRTF = function () {
  62807. this._panningModel = "HRTF";
  62808. this._switchPanningModel();
  62809. };
  62810. Sound.prototype.switchPanningModelToEqualPower = function () {
  62811. this._panningModel = "equalpower";
  62812. this._switchPanningModel();
  62813. };
  62814. Sound.prototype._switchPanningModel = function () {
  62815. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62816. this._soundPanner.panningModel = this._panningModel;
  62817. }
  62818. };
  62819. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62820. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62821. if (this._isOutputConnected) {
  62822. this._ouputAudioNode.disconnect();
  62823. }
  62824. this._ouputAudioNode.connect(soundTrackAudioNode);
  62825. this._isOutputConnected = true;
  62826. }
  62827. };
  62828. /**
  62829. * Transform this sound into a directional source
  62830. * @param coneInnerAngle Size of the inner cone in degree
  62831. * @param coneOuterAngle Size of the outer cone in degree
  62832. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62833. */
  62834. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62835. if (coneOuterAngle < coneInnerAngle) {
  62836. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62837. return;
  62838. }
  62839. this._coneInnerAngle = coneInnerAngle;
  62840. this._coneOuterAngle = coneOuterAngle;
  62841. this._coneOuterGain = coneOuterGain;
  62842. this._isDirectional = true;
  62843. if (this.isPlaying && this.loop) {
  62844. this.stop();
  62845. this.play();
  62846. }
  62847. };
  62848. Sound.prototype.setPosition = function (newPosition) {
  62849. this._position = newPosition;
  62850. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62851. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62852. }
  62853. };
  62854. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62855. this._localDirection = newLocalDirection;
  62856. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62857. this._updateDirection();
  62858. }
  62859. };
  62860. Sound.prototype._updateDirection = function () {
  62861. if (!this._connectedMesh || !this._soundPanner) {
  62862. return;
  62863. }
  62864. var mat = this._connectedMesh.getWorldMatrix();
  62865. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62866. direction.normalize();
  62867. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62868. };
  62869. Sound.prototype.updateDistanceFromListener = function () {
  62870. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62871. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62872. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62873. }
  62874. };
  62875. Sound.prototype.setAttenuationFunction = function (callback) {
  62876. this._customAttenuationFunction = callback;
  62877. };
  62878. /**
  62879. * Play the sound
  62880. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62881. * @param offset (optional) Start the sound setting it at a specific time
  62882. */
  62883. Sound.prototype.play = function (time, offset) {
  62884. var _this = this;
  62885. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62886. try {
  62887. if (this._startOffset < 0) {
  62888. time = -this._startOffset;
  62889. this._startOffset = 0;
  62890. }
  62891. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62892. if (!this._soundSource || !this._streamingSource) {
  62893. if (this.spatialSound && this._soundPanner) {
  62894. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62895. if (this._isDirectional) {
  62896. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62897. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62898. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62899. if (this._connectedMesh) {
  62900. this._updateDirection();
  62901. }
  62902. else {
  62903. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62904. }
  62905. }
  62906. }
  62907. }
  62908. if (this._streaming) {
  62909. if (!this._streamingSource) {
  62910. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62911. this._htmlAudioElement.onended = function () { _this._onended(); };
  62912. this._htmlAudioElement.playbackRate = this._playbackRate;
  62913. }
  62914. this._streamingSource.disconnect();
  62915. this._streamingSource.connect(this._inputAudioNode);
  62916. if (this._htmlAudioElement) {
  62917. this._htmlAudioElement.play();
  62918. }
  62919. }
  62920. else {
  62921. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62922. this._soundSource.buffer = this._audioBuffer;
  62923. this._soundSource.connect(this._inputAudioNode);
  62924. this._soundSource.loop = this.loop;
  62925. this._soundSource.playbackRate.value = this._playbackRate;
  62926. this._soundSource.onended = function () { _this._onended(); };
  62927. if (this._soundSource.buffer) {
  62928. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62929. }
  62930. }
  62931. this._startTime = startTime;
  62932. this.isPlaying = true;
  62933. this.isPaused = false;
  62934. }
  62935. catch (ex) {
  62936. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62937. }
  62938. }
  62939. };
  62940. Sound.prototype._onended = function () {
  62941. this.isPlaying = false;
  62942. if (this.onended) {
  62943. this.onended();
  62944. }
  62945. };
  62946. /**
  62947. * Stop the sound
  62948. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62949. */
  62950. Sound.prototype.stop = function (time) {
  62951. if (this.isPlaying) {
  62952. if (this._streaming) {
  62953. if (this._htmlAudioElement) {
  62954. this._htmlAudioElement.pause();
  62955. // Test needed for Firefox or it will generate an Invalid State Error
  62956. if (this._htmlAudioElement.currentTime > 0) {
  62957. this._htmlAudioElement.currentTime = 0;
  62958. }
  62959. }
  62960. else {
  62961. this._streamingSource.disconnect();
  62962. }
  62963. }
  62964. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62965. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62966. this._soundSource.stop(stopTime);
  62967. this._soundSource.onended = function () { };
  62968. if (!this.isPaused) {
  62969. this._startOffset = 0;
  62970. }
  62971. }
  62972. this.isPlaying = false;
  62973. }
  62974. };
  62975. Sound.prototype.pause = function () {
  62976. if (this.isPlaying) {
  62977. this.isPaused = true;
  62978. if (this._streaming) {
  62979. if (this._htmlAudioElement) {
  62980. this._htmlAudioElement.pause();
  62981. }
  62982. else {
  62983. this._streamingSource.disconnect();
  62984. }
  62985. }
  62986. else if (BABYLON.Engine.audioEngine.audioContext) {
  62987. this.stop(0);
  62988. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62989. }
  62990. }
  62991. };
  62992. Sound.prototype.setVolume = function (newVolume, time) {
  62993. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62994. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62995. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62996. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62997. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62998. }
  62999. else {
  63000. this._soundGain.gain.value = newVolume;
  63001. }
  63002. }
  63003. this._volume = newVolume;
  63004. };
  63005. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63006. this._playbackRate = newPlaybackRate;
  63007. if (this.isPlaying) {
  63008. if (this._streaming && this._htmlAudioElement) {
  63009. this._htmlAudioElement.playbackRate = this._playbackRate;
  63010. }
  63011. else if (this._soundSource) {
  63012. this._soundSource.playbackRate.value = this._playbackRate;
  63013. }
  63014. }
  63015. };
  63016. Sound.prototype.getVolume = function () {
  63017. return this._volume;
  63018. };
  63019. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63020. var _this = this;
  63021. if (this._connectedMesh && this._registerFunc) {
  63022. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63023. this._registerFunc = null;
  63024. }
  63025. this._connectedMesh = meshToConnectTo;
  63026. if (!this.spatialSound) {
  63027. this.spatialSound = true;
  63028. this._createSpatialParameters();
  63029. if (this.isPlaying && this.loop) {
  63030. this.stop();
  63031. this.play();
  63032. }
  63033. }
  63034. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63035. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63036. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63037. };
  63038. Sound.prototype.detachFromMesh = function () {
  63039. if (this._connectedMesh && this._registerFunc) {
  63040. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63041. this._registerFunc = null;
  63042. this._connectedMesh = null;
  63043. }
  63044. };
  63045. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63046. if (!node.getBoundingInfo) {
  63047. return;
  63048. }
  63049. var mesh = node;
  63050. var boundingInfo = mesh.getBoundingInfo();
  63051. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63052. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63053. this._updateDirection();
  63054. }
  63055. };
  63056. Sound.prototype.clone = function () {
  63057. var _this = this;
  63058. if (!this._streaming) {
  63059. var setBufferAndRun = function () {
  63060. if (_this._isReadyToPlay) {
  63061. clonedSound._audioBuffer = _this.getAudioBuffer();
  63062. clonedSound._isReadyToPlay = true;
  63063. if (clonedSound.autoplay) {
  63064. clonedSound.play();
  63065. }
  63066. }
  63067. else {
  63068. window.setTimeout(setBufferAndRun, 300);
  63069. }
  63070. };
  63071. var currentOptions = {
  63072. autoplay: this.autoplay, loop: this.loop,
  63073. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63074. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63075. refDistance: this.refDistance, distanceModel: this.distanceModel
  63076. };
  63077. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63078. if (this.useCustomAttenuation) {
  63079. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63080. }
  63081. clonedSound.setPosition(this._position);
  63082. clonedSound.setPlaybackRate(this._playbackRate);
  63083. setBufferAndRun();
  63084. return clonedSound;
  63085. }
  63086. // Can't clone a streaming sound
  63087. else {
  63088. return null;
  63089. }
  63090. };
  63091. Sound.prototype.getAudioBuffer = function () {
  63092. return this._audioBuffer;
  63093. };
  63094. Sound.prototype.serialize = function () {
  63095. var serializationObject = {
  63096. name: this.name,
  63097. url: this.name,
  63098. autoplay: this.autoplay,
  63099. loop: this.loop,
  63100. volume: this._volume,
  63101. spatialSound: this.spatialSound,
  63102. maxDistance: this.maxDistance,
  63103. rolloffFactor: this.rolloffFactor,
  63104. refDistance: this.refDistance,
  63105. distanceModel: this.distanceModel,
  63106. playbackRate: this._playbackRate,
  63107. panningModel: this._panningModel,
  63108. soundTrackId: this.soundTrackId
  63109. };
  63110. if (this.spatialSound) {
  63111. if (this._connectedMesh)
  63112. serializationObject.connectedMeshId = this._connectedMesh.id;
  63113. serializationObject.position = this._position.asArray();
  63114. serializationObject.refDistance = this.refDistance;
  63115. serializationObject.distanceModel = this.distanceModel;
  63116. serializationObject.isDirectional = this._isDirectional;
  63117. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63118. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63119. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63120. serializationObject.coneOuterGain = this._coneOuterGain;
  63121. }
  63122. return serializationObject;
  63123. };
  63124. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63125. var soundName = parsedSound.name;
  63126. var soundUrl;
  63127. if (parsedSound.url) {
  63128. soundUrl = rootUrl + parsedSound.url;
  63129. }
  63130. else {
  63131. soundUrl = rootUrl + soundName;
  63132. }
  63133. var options = {
  63134. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63135. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63136. rolloffFactor: parsedSound.rolloffFactor,
  63137. refDistance: parsedSound.refDistance,
  63138. distanceModel: parsedSound.distanceModel,
  63139. playbackRate: parsedSound.playbackRate
  63140. };
  63141. var newSound;
  63142. if (!sourceSound) {
  63143. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63144. scene._addPendingData(newSound);
  63145. }
  63146. else {
  63147. var setBufferAndRun = function () {
  63148. if (sourceSound._isReadyToPlay) {
  63149. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63150. newSound._isReadyToPlay = true;
  63151. if (newSound.autoplay) {
  63152. newSound.play();
  63153. }
  63154. }
  63155. else {
  63156. window.setTimeout(setBufferAndRun, 300);
  63157. }
  63158. };
  63159. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63160. setBufferAndRun();
  63161. }
  63162. if (parsedSound.position) {
  63163. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63164. newSound.setPosition(soundPosition);
  63165. }
  63166. if (parsedSound.isDirectional) {
  63167. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63168. if (parsedSound.localDirectionToMesh) {
  63169. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63170. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63171. }
  63172. }
  63173. if (parsedSound.connectedMeshId) {
  63174. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63175. if (connectedMesh) {
  63176. newSound.attachToMesh(connectedMesh);
  63177. }
  63178. }
  63179. return newSound;
  63180. };
  63181. return Sound;
  63182. }());
  63183. BABYLON.Sound = Sound;
  63184. })(BABYLON || (BABYLON = {}));
  63185. //# sourceMappingURL=babylon.sound.js.map
  63186. var BABYLON;
  63187. (function (BABYLON) {
  63188. var SoundTrack = /** @class */ (function () {
  63189. function SoundTrack(scene, options) {
  63190. this.id = -1;
  63191. this._isMainTrack = false;
  63192. this._isInitialized = false;
  63193. this._scene = scene;
  63194. this.soundCollection = new Array();
  63195. this._options = options;
  63196. if (!this._isMainTrack) {
  63197. this._scene.soundTracks.push(this);
  63198. this.id = this._scene.soundTracks.length - 1;
  63199. }
  63200. }
  63201. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63202. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63203. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63204. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63205. if (this._options) {
  63206. if (this._options.volume) {
  63207. this._outputAudioNode.gain.value = this._options.volume;
  63208. }
  63209. if (this._options.mainTrack) {
  63210. this._isMainTrack = this._options.mainTrack;
  63211. }
  63212. }
  63213. this._isInitialized = true;
  63214. }
  63215. };
  63216. SoundTrack.prototype.dispose = function () {
  63217. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63218. if (this._connectedAnalyser) {
  63219. this._connectedAnalyser.stopDebugCanvas();
  63220. }
  63221. while (this.soundCollection.length) {
  63222. this.soundCollection[0].dispose();
  63223. }
  63224. if (this._outputAudioNode) {
  63225. this._outputAudioNode.disconnect();
  63226. }
  63227. this._outputAudioNode = null;
  63228. }
  63229. };
  63230. SoundTrack.prototype.AddSound = function (sound) {
  63231. if (!this._isInitialized) {
  63232. this._initializeSoundTrackAudioGraph();
  63233. }
  63234. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63235. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63236. }
  63237. if (sound.soundTrackId) {
  63238. if (sound.soundTrackId === -1) {
  63239. this._scene.mainSoundTrack.RemoveSound(sound);
  63240. }
  63241. else {
  63242. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63243. }
  63244. }
  63245. this.soundCollection.push(sound);
  63246. sound.soundTrackId = this.id;
  63247. };
  63248. SoundTrack.prototype.RemoveSound = function (sound) {
  63249. var index = this.soundCollection.indexOf(sound);
  63250. if (index !== -1) {
  63251. this.soundCollection.splice(index, 1);
  63252. }
  63253. };
  63254. SoundTrack.prototype.setVolume = function (newVolume) {
  63255. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63256. this._outputAudioNode.gain.value = newVolume;
  63257. }
  63258. };
  63259. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63260. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63261. for (var i = 0; i < this.soundCollection.length; i++) {
  63262. this.soundCollection[i].switchPanningModelToHRTF();
  63263. }
  63264. }
  63265. };
  63266. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63267. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63268. for (var i = 0; i < this.soundCollection.length; i++) {
  63269. this.soundCollection[i].switchPanningModelToEqualPower();
  63270. }
  63271. }
  63272. };
  63273. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63274. if (this._connectedAnalyser) {
  63275. this._connectedAnalyser.stopDebugCanvas();
  63276. }
  63277. this._connectedAnalyser = analyser;
  63278. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63279. this._outputAudioNode.disconnect();
  63280. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63281. }
  63282. };
  63283. return SoundTrack;
  63284. }());
  63285. BABYLON.SoundTrack = SoundTrack;
  63286. })(BABYLON || (BABYLON = {}));
  63287. //# sourceMappingURL=babylon.soundtrack.js.map
  63288. var BABYLON;
  63289. (function (BABYLON) {
  63290. /**
  63291. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63292. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63293. */
  63294. var Analyser = /** @class */ (function () {
  63295. /**
  63296. * Creates a new analyser
  63297. * @param scene defines hosting scene
  63298. */
  63299. function Analyser(scene) {
  63300. /**
  63301. * Gets or sets the smoothing
  63302. * @ignorenaming
  63303. */
  63304. this.SMOOTHING = 0.75;
  63305. /**
  63306. * Gets or sets the FFT table size
  63307. * @ignorenaming
  63308. */
  63309. this.FFT_SIZE = 512;
  63310. /**
  63311. * Gets or sets the bar graph amplitude
  63312. * @ignorenaming
  63313. */
  63314. this.BARGRAPHAMPLITUDE = 256;
  63315. /**
  63316. * Gets or sets the position of the debug canvas
  63317. * @ignorenaming
  63318. */
  63319. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63320. /**
  63321. * Gets or sets the debug canvas size
  63322. * @ignorenaming
  63323. */
  63324. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63325. this._scene = scene;
  63326. this._audioEngine = BABYLON.Engine.audioEngine;
  63327. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63328. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63329. this._webAudioAnalyser.minDecibels = -140;
  63330. this._webAudioAnalyser.maxDecibels = 0;
  63331. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63332. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63333. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63334. }
  63335. }
  63336. /**
  63337. * Get the number of data values you will have to play with for the visualization
  63338. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63339. * @returns a number
  63340. */
  63341. Analyser.prototype.getFrequencyBinCount = function () {
  63342. if (this._audioEngine.canUseWebAudio) {
  63343. return this._webAudioAnalyser.frequencyBinCount;
  63344. }
  63345. else {
  63346. return 0;
  63347. }
  63348. };
  63349. /**
  63350. * Gets the current frequency data as a byte array
  63351. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63352. * @returns a Uint8Array
  63353. */
  63354. Analyser.prototype.getByteFrequencyData = function () {
  63355. if (this._audioEngine.canUseWebAudio) {
  63356. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63357. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63358. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63359. }
  63360. return this._byteFreqs;
  63361. };
  63362. /**
  63363. * Gets the current waveform as a byte array
  63364. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63365. * @returns a Uint8Array
  63366. */
  63367. Analyser.prototype.getByteTimeDomainData = function () {
  63368. if (this._audioEngine.canUseWebAudio) {
  63369. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63370. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63371. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63372. }
  63373. return this._byteTime;
  63374. };
  63375. /**
  63376. * Gets the current frequency data as a float array
  63377. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63378. * @returns a Float32Array
  63379. */
  63380. Analyser.prototype.getFloatFrequencyData = function () {
  63381. if (this._audioEngine.canUseWebAudio) {
  63382. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63383. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63384. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63385. }
  63386. return this._floatFreqs;
  63387. };
  63388. /**
  63389. * Renders the debug canvas
  63390. */
  63391. Analyser.prototype.drawDebugCanvas = function () {
  63392. var _this = this;
  63393. if (this._audioEngine.canUseWebAudio) {
  63394. if (!this._debugCanvas) {
  63395. this._debugCanvas = document.createElement("canvas");
  63396. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63397. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63398. this._debugCanvas.style.position = "absolute";
  63399. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63400. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63401. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63402. document.body.appendChild(this._debugCanvas);
  63403. this._registerFunc = function () {
  63404. _this.drawDebugCanvas();
  63405. };
  63406. this._scene.registerBeforeRender(this._registerFunc);
  63407. }
  63408. if (this._registerFunc && this._debugCanvasContext) {
  63409. var workingArray = this.getByteFrequencyData();
  63410. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63411. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63412. // Draw the frequency domain chart.
  63413. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63414. var value = workingArray[i];
  63415. var percent = value / this.BARGRAPHAMPLITUDE;
  63416. var height = this.DEBUGCANVASSIZE.height * percent;
  63417. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63418. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63419. var hue = i / this.getFrequencyBinCount() * 360;
  63420. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63421. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63422. }
  63423. }
  63424. }
  63425. };
  63426. /**
  63427. * Stops rendering the debug canvas and removes it
  63428. */
  63429. Analyser.prototype.stopDebugCanvas = function () {
  63430. if (this._debugCanvas) {
  63431. if (this._registerFunc) {
  63432. this._scene.unregisterBeforeRender(this._registerFunc);
  63433. this._registerFunc = null;
  63434. }
  63435. document.body.removeChild(this._debugCanvas);
  63436. this._debugCanvas = null;
  63437. this._debugCanvasContext = null;
  63438. }
  63439. };
  63440. /**
  63441. * Connects two audio nodes
  63442. * @param inputAudioNode defines first node to connect
  63443. * @param outputAudioNode defines second node to connect
  63444. */
  63445. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63446. if (this._audioEngine.canUseWebAudio) {
  63447. inputAudioNode.connect(this._webAudioAnalyser);
  63448. this._webAudioAnalyser.connect(outputAudioNode);
  63449. }
  63450. };
  63451. /**
  63452. * Releases all associated resources
  63453. */
  63454. Analyser.prototype.dispose = function () {
  63455. if (this._audioEngine.canUseWebAudio) {
  63456. this._webAudioAnalyser.disconnect();
  63457. }
  63458. };
  63459. return Analyser;
  63460. }());
  63461. BABYLON.Analyser = Analyser;
  63462. })(BABYLON || (BABYLON = {}));
  63463. //# sourceMappingURL=babylon.analyser.js.map
  63464. var BABYLON;
  63465. (function (BABYLON) {
  63466. var CubeTexture = /** @class */ (function (_super) {
  63467. __extends(CubeTexture, _super);
  63468. /**
  63469. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63470. * as prefiltered data.
  63471. * @param rootUrl defines the url of the texture or the root name of the six images
  63472. * @param scene defines the scene the texture is attached to
  63473. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63474. * @param noMipmap defines if mipmaps should be created or not
  63475. * @param files defines the six files to load for the different faces
  63476. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63477. * @param onError defines a callback triggered in case of error during load
  63478. * @param format defines the internal format to use for the texture once loaded
  63479. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63480. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63481. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63482. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63483. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63484. * @return the cube texture
  63485. */
  63486. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63487. if (extensions === void 0) { extensions = null; }
  63488. if (noMipmap === void 0) { noMipmap = false; }
  63489. if (files === void 0) { files = null; }
  63490. if (onLoad === void 0) { onLoad = null; }
  63491. if (onError === void 0) { onError = null; }
  63492. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63493. if (prefiltered === void 0) { prefiltered = false; }
  63494. if (forcedExtension === void 0) { forcedExtension = null; }
  63495. if (createPolynomials === void 0) { createPolynomials = false; }
  63496. if (lodScale === void 0) { lodScale = 0.8; }
  63497. if (lodOffset === void 0) { lodOffset = 0; }
  63498. var _this = _super.call(this, scene) || this;
  63499. /**
  63500. * Gets or sets the center of the bounding box associated with the cube texture
  63501. * It must define where the camera used to render the texture was set
  63502. */
  63503. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63504. _this._rotationY = 0;
  63505. /** @hidden */
  63506. _this._prefiltered = false;
  63507. _this.name = rootUrl;
  63508. _this.url = rootUrl;
  63509. _this._noMipmap = noMipmap;
  63510. _this.hasAlpha = false;
  63511. _this._format = format;
  63512. _this.isCube = true;
  63513. _this._textureMatrix = BABYLON.Matrix.Identity();
  63514. _this._createPolynomials = createPolynomials;
  63515. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63516. if (!rootUrl && !files) {
  63517. return _this;
  63518. }
  63519. var lastDot = rootUrl.lastIndexOf(".");
  63520. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63521. var isDDS = (extension === ".dds");
  63522. var isEnv = (extension === ".env");
  63523. if (isEnv) {
  63524. _this.gammaSpace = false;
  63525. _this._prefiltered = false;
  63526. }
  63527. else {
  63528. _this._prefiltered = prefiltered;
  63529. if (prefiltered) {
  63530. _this.gammaSpace = false;
  63531. }
  63532. }
  63533. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63534. if (!files) {
  63535. if (!isEnv && !isDDS && !extensions) {
  63536. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63537. }
  63538. files = [];
  63539. if (extensions) {
  63540. for (var index = 0; index < extensions.length; index++) {
  63541. files.push(rootUrl + extensions[index]);
  63542. }
  63543. }
  63544. }
  63545. _this._files = files;
  63546. if (!_this._texture) {
  63547. if (!scene.useDelayedTextureLoading) {
  63548. if (prefiltered) {
  63549. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63550. }
  63551. else {
  63552. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63553. }
  63554. }
  63555. else {
  63556. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63557. }
  63558. }
  63559. else if (onLoad) {
  63560. if (_this._texture.isReady) {
  63561. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63562. }
  63563. else {
  63564. _this._texture.onLoadedObservable.add(onLoad);
  63565. }
  63566. }
  63567. return _this;
  63568. }
  63569. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63570. get: function () {
  63571. return this._boundingBoxSize;
  63572. },
  63573. /**
  63574. * Gets or sets the size of the bounding box associated with the cube texture
  63575. * When defined, the cubemap will switch to local mode
  63576. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63577. * @example https://www.babylonjs-playground.com/#RNASML
  63578. */
  63579. set: function (value) {
  63580. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63581. return;
  63582. }
  63583. this._boundingBoxSize = value;
  63584. var scene = this.getScene();
  63585. if (scene) {
  63586. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63587. }
  63588. },
  63589. enumerable: true,
  63590. configurable: true
  63591. });
  63592. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63593. /**
  63594. * Gets texture matrix rotation angle around Y axis radians.
  63595. */
  63596. get: function () {
  63597. return this._rotationY;
  63598. },
  63599. /**
  63600. * Sets texture matrix rotation angle around Y axis in radians.
  63601. */
  63602. set: function (value) {
  63603. this._rotationY = value;
  63604. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63605. },
  63606. enumerable: true,
  63607. configurable: true
  63608. });
  63609. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63610. var rootUrlKey = "";
  63611. files.forEach(function (url) { return rootUrlKey += url; });
  63612. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63613. };
  63614. /**
  63615. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63616. * @param url defines the url of the prefiltered texture
  63617. * @param scene defines the scene the texture is attached to
  63618. * @param forcedExtension defines the extension of the file if different from the url
  63619. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63620. * @return the prefiltered texture
  63621. */
  63622. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63623. if (forcedExtension === void 0) { forcedExtension = null; }
  63624. if (createPolynomials === void 0) { createPolynomials = true; }
  63625. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63626. };
  63627. // Methods
  63628. CubeTexture.prototype.delayLoad = function () {
  63629. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63630. return;
  63631. }
  63632. var scene = this.getScene();
  63633. if (!scene) {
  63634. return;
  63635. }
  63636. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63637. this._texture = this._getFromCache(this.url, this._noMipmap);
  63638. if (!this._texture) {
  63639. if (this._prefiltered) {
  63640. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63641. }
  63642. else {
  63643. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63644. }
  63645. }
  63646. };
  63647. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63648. return this._textureMatrix;
  63649. };
  63650. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63651. this._textureMatrix = value;
  63652. };
  63653. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63654. var texture = BABYLON.SerializationHelper.Parse(function () {
  63655. var prefiltered = false;
  63656. if (parsedTexture.prefiltered) {
  63657. prefiltered = parsedTexture.prefiltered;
  63658. }
  63659. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63660. }, parsedTexture, scene);
  63661. // Local Cubemaps
  63662. if (parsedTexture.boundingBoxPosition) {
  63663. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63664. }
  63665. if (parsedTexture.boundingBoxSize) {
  63666. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63667. }
  63668. // Animations
  63669. if (parsedTexture.animations) {
  63670. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63671. var parsedAnimation = parsedTexture.animations[animationIndex];
  63672. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63673. }
  63674. }
  63675. return texture;
  63676. };
  63677. CubeTexture.prototype.clone = function () {
  63678. var _this = this;
  63679. return BABYLON.SerializationHelper.Clone(function () {
  63680. var scene = _this.getScene();
  63681. if (!scene) {
  63682. return _this;
  63683. }
  63684. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63685. }, this);
  63686. };
  63687. __decorate([
  63688. BABYLON.serialize("rotationY")
  63689. ], CubeTexture.prototype, "_rotationY", void 0);
  63690. return CubeTexture;
  63691. }(BABYLON.BaseTexture));
  63692. BABYLON.CubeTexture = CubeTexture;
  63693. })(BABYLON || (BABYLON = {}));
  63694. //# sourceMappingURL=babylon.cubeTexture.js.map
  63695. var BABYLON;
  63696. (function (BABYLON) {
  63697. /**
  63698. * Raw cube texture where the raw buffers are passed in
  63699. */
  63700. var RawCubeTexture = /** @class */ (function (_super) {
  63701. __extends(RawCubeTexture, _super);
  63702. /**
  63703. * Creates a cube texture where the raw buffers are passed in.
  63704. * @param scene defines the scene the texture is attached to
  63705. * @param data defines the array of data to use to create each face
  63706. * @param size defines the size of the textures
  63707. * @param format defines the format of the data
  63708. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  63709. * @param generateMipMaps defines if the engine should generate the mip levels
  63710. * @param invertY defines if data must be stored with Y axis inverted
  63711. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  63712. * @param compression defines the compression used (null by default)
  63713. */
  63714. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  63715. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63716. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63717. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63718. if (invertY === void 0) { invertY = false; }
  63719. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63720. if (compression === void 0) { compression = null; }
  63721. var _this = _super.call(this, "", scene) || this;
  63722. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  63723. return _this;
  63724. }
  63725. /**
  63726. * Updates the raw cube texture.
  63727. * @param data defines the data to store
  63728. * @param format defines the data format
  63729. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  63730. * @param invertY defines if data must be stored with Y axis inverted
  63731. * @param compression defines the compression used (null by default)
  63732. * @param level defines which level of the texture to update
  63733. */
  63734. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  63735. if (compression === void 0) { compression = null; }
  63736. if (level === void 0) { level = 0; }
  63737. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  63738. };
  63739. /**
  63740. * Updates a raw cube texture with RGBD encoded data.
  63741. * @param data defines the array of data [mipmap][face] to use to create each face
  63742. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  63743. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63744. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63745. * @returns a promsie that resolves when the operation is complete
  63746. */
  63747. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  63748. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  63749. if (lodScale === void 0) { lodScale = 0.8; }
  63750. if (lodOffset === void 0) { lodOffset = 0; }
  63751. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  63752. };
  63753. /**
  63754. * Clones the raw cube texture.
  63755. * @return a new cube texture
  63756. */
  63757. RawCubeTexture.prototype.clone = function () {
  63758. var _this = this;
  63759. return BABYLON.SerializationHelper.Clone(function () {
  63760. var scene = _this.getScene();
  63761. var internalTexture = _this._texture;
  63762. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  63763. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  63764. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  63765. }
  63766. return texture;
  63767. }, this);
  63768. };
  63769. /** @hidden */
  63770. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  63771. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  63772. internalTexture._bufferViewArrayArray = data;
  63773. internalTexture._lodGenerationScale = lodScale;
  63774. internalTexture._lodGenerationOffset = lodOffset;
  63775. internalTexture._sphericalPolynomial = sphericalPolynomial;
  63776. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  63777. internalTexture.isReady = true;
  63778. });
  63779. };
  63780. return RawCubeTexture;
  63781. }(BABYLON.CubeTexture));
  63782. BABYLON.RawCubeTexture = RawCubeTexture;
  63783. })(BABYLON || (BABYLON = {}));
  63784. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  63785. var BABYLON;
  63786. (function (BABYLON) {
  63787. var RenderTargetTexture = /** @class */ (function (_super) {
  63788. __extends(RenderTargetTexture, _super);
  63789. /**
  63790. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63791. * or used a shadow, depth texture...
  63792. * @param name The friendly name of the texture
  63793. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  63794. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63795. * @param generateMipMaps True if mip maps need to be generated after render.
  63796. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63797. * @param type The type of the buffer in the RTT (int, half float, float...)
  63798. * @param isCube True if a cube texture needs to be created
  63799. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63800. * @param generateDepthBuffer True to generate a depth buffer
  63801. * @param generateStencilBuffer True to generate a stencil buffer
  63802. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63803. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63804. */
  63805. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63806. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63807. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63808. if (isCube === void 0) { isCube = false; }
  63809. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63810. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63811. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63812. if (isMulti === void 0) { isMulti = false; }
  63813. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63814. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63815. _this.isCube = isCube;
  63816. /**
  63817. * Use this list to define the list of mesh you want to render.
  63818. */
  63819. _this.renderList = new Array();
  63820. _this.renderParticles = true;
  63821. _this.renderSprites = false;
  63822. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63823. _this.ignoreCameraViewport = false;
  63824. // Events
  63825. /**
  63826. * An event triggered when the texture is unbind.
  63827. */
  63828. _this.onBeforeBindObservable = new BABYLON.Observable();
  63829. /**
  63830. * An event triggered when the texture is unbind.
  63831. */
  63832. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63833. /**
  63834. * An event triggered before rendering the texture
  63835. */
  63836. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63837. /**
  63838. * An event triggered after rendering the texture
  63839. */
  63840. _this.onAfterRenderObservable = new BABYLON.Observable();
  63841. /**
  63842. * An event triggered after the texture clear
  63843. */
  63844. _this.onClearObservable = new BABYLON.Observable();
  63845. _this._currentRefreshId = -1;
  63846. _this._refreshRate = 1;
  63847. _this._samples = 1;
  63848. /**
  63849. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63850. * It must define where the camera used to render the texture is set
  63851. */
  63852. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63853. scene = _this.getScene();
  63854. if (!scene) {
  63855. return _this;
  63856. }
  63857. _this._engine = scene.getEngine();
  63858. _this.name = name;
  63859. _this.isRenderTarget = true;
  63860. _this._initialSizeParameter = size;
  63861. _this._processSizeParameter(size);
  63862. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63863. });
  63864. _this._generateMipMaps = generateMipMaps ? true : false;
  63865. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63866. // Rendering groups
  63867. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63868. if (isMulti) {
  63869. return _this;
  63870. }
  63871. _this._renderTargetOptions = {
  63872. generateMipMaps: generateMipMaps,
  63873. type: type,
  63874. format: format,
  63875. samplingMode: samplingMode,
  63876. generateDepthBuffer: generateDepthBuffer,
  63877. generateStencilBuffer: generateStencilBuffer
  63878. };
  63879. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63880. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63881. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63882. }
  63883. if (isCube) {
  63884. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63885. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63886. _this._textureMatrix = BABYLON.Matrix.Identity();
  63887. }
  63888. else {
  63889. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63890. }
  63891. return _this;
  63892. }
  63893. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63894. get: function () {
  63895. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63896. },
  63897. enumerable: true,
  63898. configurable: true
  63899. });
  63900. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63901. get: function () {
  63902. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63903. },
  63904. enumerable: true,
  63905. configurable: true
  63906. });
  63907. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63908. get: function () {
  63909. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63910. },
  63911. enumerable: true,
  63912. configurable: true
  63913. });
  63914. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63915. set: function (callback) {
  63916. if (this._onAfterUnbindObserver) {
  63917. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63918. }
  63919. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63920. },
  63921. enumerable: true,
  63922. configurable: true
  63923. });
  63924. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63925. set: function (callback) {
  63926. if (this._onBeforeRenderObserver) {
  63927. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63928. }
  63929. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63930. },
  63931. enumerable: true,
  63932. configurable: true
  63933. });
  63934. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63935. set: function (callback) {
  63936. if (this._onAfterRenderObserver) {
  63937. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63938. }
  63939. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63940. },
  63941. enumerable: true,
  63942. configurable: true
  63943. });
  63944. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63945. set: function (callback) {
  63946. if (this._onClearObserver) {
  63947. this.onClearObservable.remove(this._onClearObserver);
  63948. }
  63949. this._onClearObserver = this.onClearObservable.add(callback);
  63950. },
  63951. enumerable: true,
  63952. configurable: true
  63953. });
  63954. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63955. get: function () {
  63956. return this._renderTargetOptions;
  63957. },
  63958. enumerable: true,
  63959. configurable: true
  63960. });
  63961. RenderTargetTexture.prototype._onRatioRescale = function () {
  63962. if (this._sizeRatio) {
  63963. this.resize(this._initialSizeParameter);
  63964. }
  63965. };
  63966. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63967. get: function () {
  63968. return this._boundingBoxSize;
  63969. },
  63970. /**
  63971. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63972. * When defined, the cubemap will switch to local mode
  63973. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63974. * @example https://www.babylonjs-playground.com/#RNASML
  63975. */
  63976. set: function (value) {
  63977. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63978. return;
  63979. }
  63980. this._boundingBoxSize = value;
  63981. var scene = this.getScene();
  63982. if (scene) {
  63983. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63984. }
  63985. },
  63986. enumerable: true,
  63987. configurable: true
  63988. });
  63989. /**
  63990. * Creates a depth stencil texture.
  63991. * This is only available in WebGL 2 or with the depth texture extension available.
  63992. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63993. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63994. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63995. */
  63996. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63997. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63998. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63999. if (generateStencil === void 0) { generateStencil = false; }
  64000. if (!this.getScene()) {
  64001. return;
  64002. }
  64003. var engine = this.getScene().getEngine();
  64004. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64005. bilinearFiltering: bilinearFiltering,
  64006. comparisonFunction: comparisonFunction,
  64007. generateStencil: generateStencil,
  64008. isCube: this.isCube
  64009. });
  64010. engine.setFrameBufferDepthStencilTexture(this);
  64011. };
  64012. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64013. if (size.ratio) {
  64014. this._sizeRatio = size.ratio;
  64015. this._size = {
  64016. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64017. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64018. };
  64019. }
  64020. else {
  64021. this._size = size;
  64022. }
  64023. };
  64024. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64025. get: function () {
  64026. return this._samples;
  64027. },
  64028. set: function (value) {
  64029. if (this._samples === value) {
  64030. return;
  64031. }
  64032. var scene = this.getScene();
  64033. if (!scene) {
  64034. return;
  64035. }
  64036. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64037. },
  64038. enumerable: true,
  64039. configurable: true
  64040. });
  64041. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64042. this._currentRefreshId = -1;
  64043. };
  64044. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64045. get: function () {
  64046. return this._refreshRate;
  64047. },
  64048. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64049. set: function (value) {
  64050. this._refreshRate = value;
  64051. this.resetRefreshCounter();
  64052. },
  64053. enumerable: true,
  64054. configurable: true
  64055. });
  64056. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64057. if (!this._postProcessManager) {
  64058. var scene = this.getScene();
  64059. if (!scene) {
  64060. return;
  64061. }
  64062. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64063. this._postProcesses = new Array();
  64064. }
  64065. this._postProcesses.push(postProcess);
  64066. this._postProcesses[0].autoClear = false;
  64067. };
  64068. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64069. if (!this._postProcesses) {
  64070. return;
  64071. }
  64072. if (dispose) {
  64073. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64074. var postProcess = _a[_i];
  64075. postProcess.dispose();
  64076. }
  64077. }
  64078. this._postProcesses = [];
  64079. };
  64080. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64081. if (!this._postProcesses) {
  64082. return;
  64083. }
  64084. var index = this._postProcesses.indexOf(postProcess);
  64085. if (index === -1) {
  64086. return;
  64087. }
  64088. this._postProcesses.splice(index, 1);
  64089. if (this._postProcesses.length > 0) {
  64090. this._postProcesses[0].autoClear = false;
  64091. }
  64092. };
  64093. RenderTargetTexture.prototype._shouldRender = function () {
  64094. if (this._currentRefreshId === -1) { // At least render once
  64095. this._currentRefreshId = 1;
  64096. return true;
  64097. }
  64098. if (this.refreshRate === this._currentRefreshId) {
  64099. this._currentRefreshId = 1;
  64100. return true;
  64101. }
  64102. this._currentRefreshId++;
  64103. return false;
  64104. };
  64105. RenderTargetTexture.prototype.getRenderSize = function () {
  64106. if (this._size.width) {
  64107. return this._size.width;
  64108. }
  64109. return this._size;
  64110. };
  64111. RenderTargetTexture.prototype.getRenderWidth = function () {
  64112. if (this._size.width) {
  64113. return this._size.width;
  64114. }
  64115. return this._size;
  64116. };
  64117. RenderTargetTexture.prototype.getRenderHeight = function () {
  64118. if (this._size.width) {
  64119. return this._size.height;
  64120. }
  64121. return this._size;
  64122. };
  64123. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64124. get: function () {
  64125. return true;
  64126. },
  64127. enumerable: true,
  64128. configurable: true
  64129. });
  64130. RenderTargetTexture.prototype.scale = function (ratio) {
  64131. var newSize = this.getRenderSize() * ratio;
  64132. this.resize(newSize);
  64133. };
  64134. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64135. if (this.isCube) {
  64136. return this._textureMatrix;
  64137. }
  64138. return _super.prototype.getReflectionTextureMatrix.call(this);
  64139. };
  64140. RenderTargetTexture.prototype.resize = function (size) {
  64141. this.releaseInternalTexture();
  64142. var scene = this.getScene();
  64143. if (!scene) {
  64144. return;
  64145. }
  64146. this._processSizeParameter(size);
  64147. if (this.isCube) {
  64148. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64149. }
  64150. else {
  64151. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64152. }
  64153. };
  64154. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64155. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64156. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64157. var scene = this.getScene();
  64158. if (!scene) {
  64159. return;
  64160. }
  64161. var engine = scene.getEngine();
  64162. if (this.useCameraPostProcesses !== undefined) {
  64163. useCameraPostProcess = this.useCameraPostProcesses;
  64164. }
  64165. if (this._waitingRenderList) {
  64166. this.renderList = [];
  64167. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64168. var id = this._waitingRenderList[index];
  64169. var mesh_1 = scene.getMeshByID(id);
  64170. if (mesh_1) {
  64171. this.renderList.push(mesh_1);
  64172. }
  64173. }
  64174. delete this._waitingRenderList;
  64175. }
  64176. // Is predicate defined?
  64177. if (this.renderListPredicate) {
  64178. if (this.renderList) {
  64179. this.renderList.splice(0); // Clear previous renderList
  64180. }
  64181. else {
  64182. this.renderList = [];
  64183. }
  64184. var scene = this.getScene();
  64185. if (!scene) {
  64186. return;
  64187. }
  64188. var sceneMeshes = scene.meshes;
  64189. for (var index = 0; index < sceneMeshes.length; index++) {
  64190. var mesh = sceneMeshes[index];
  64191. if (this.renderListPredicate(mesh)) {
  64192. this.renderList.push(mesh);
  64193. }
  64194. }
  64195. }
  64196. this.onBeforeBindObservable.notifyObservers(this);
  64197. // Set custom projection.
  64198. // Needs to be before binding to prevent changing the aspect ratio.
  64199. var camera;
  64200. if (this.activeCamera) {
  64201. camera = this.activeCamera;
  64202. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64203. if (this.activeCamera !== scene.activeCamera) {
  64204. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64205. }
  64206. }
  64207. else {
  64208. camera = scene.activeCamera;
  64209. if (camera) {
  64210. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64211. }
  64212. }
  64213. // Prepare renderingManager
  64214. this._renderingManager.reset();
  64215. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64216. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64217. var sceneRenderId = scene.getRenderId();
  64218. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64219. var mesh = currentRenderList[meshIndex];
  64220. if (mesh) {
  64221. if (!mesh.isReady(this.refreshRate === 0)) {
  64222. this.resetRefreshCounter();
  64223. continue;
  64224. }
  64225. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64226. var isMasked = void 0;
  64227. if (!this.renderList && camera) {
  64228. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64229. }
  64230. else {
  64231. isMasked = false;
  64232. }
  64233. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64234. mesh._activate(sceneRenderId);
  64235. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64236. var subMesh = mesh.subMeshes[subIndex];
  64237. scene._activeIndices.addCount(subMesh.indexCount, false);
  64238. this._renderingManager.dispatch(subMesh, mesh);
  64239. }
  64240. }
  64241. }
  64242. }
  64243. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64244. var particleSystem = scene.particleSystems[particleIndex];
  64245. var emitter = particleSystem.emitter;
  64246. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64247. continue;
  64248. }
  64249. if (currentRenderList.indexOf(emitter) >= 0) {
  64250. this._renderingManager.dispatchParticles(particleSystem);
  64251. }
  64252. }
  64253. if (this.isCube) {
  64254. for (var face = 0; face < 6; face++) {
  64255. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64256. scene.incrementRenderId();
  64257. scene.resetCachedMaterial();
  64258. }
  64259. }
  64260. else {
  64261. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64262. }
  64263. this.onAfterUnbindObservable.notifyObservers(this);
  64264. if (scene.activeCamera) {
  64265. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64266. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64267. }
  64268. engine.setViewport(scene.activeCamera.viewport);
  64269. }
  64270. scene.resetCachedMaterial();
  64271. };
  64272. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64273. var minimum = 128;
  64274. var x = renderDimension * scale;
  64275. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64276. // Ensure we don't exceed the render dimension (while staying POT)
  64277. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64278. };
  64279. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64280. var _this = this;
  64281. if (!this._texture) {
  64282. return;
  64283. }
  64284. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64285. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64286. });
  64287. };
  64288. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64289. var scene = this.getScene();
  64290. if (!scene) {
  64291. return;
  64292. }
  64293. var engine = scene.getEngine();
  64294. if (!this._texture) {
  64295. return;
  64296. }
  64297. // Bind
  64298. if (this._postProcessManager) {
  64299. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64300. }
  64301. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64302. if (this._texture) {
  64303. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64304. }
  64305. }
  64306. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64307. // Clear
  64308. if (this.onClearObservable.hasObservers()) {
  64309. this.onClearObservable.notifyObservers(engine);
  64310. }
  64311. else {
  64312. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64313. }
  64314. if (!this._doNotChangeAspectRatio) {
  64315. scene.updateTransformMatrix(true);
  64316. }
  64317. // Render
  64318. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64319. if (this._postProcessManager) {
  64320. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64321. }
  64322. else if (useCameraPostProcess) {
  64323. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64324. }
  64325. if (!this._doNotChangeAspectRatio) {
  64326. scene.updateTransformMatrix(true);
  64327. }
  64328. // Dump ?
  64329. if (dumpForDebug) {
  64330. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64331. }
  64332. // Unbind
  64333. if (!this.isCube || faceIndex === 5) {
  64334. if (this.isCube) {
  64335. if (faceIndex === 5) {
  64336. engine.generateMipMapsForCubemap(this._texture);
  64337. }
  64338. }
  64339. this.unbindFrameBuffer(engine, faceIndex);
  64340. }
  64341. else {
  64342. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64343. }
  64344. };
  64345. /**
  64346. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64347. * This allowed control for front to back rendering or reversly depending of the special needs.
  64348. *
  64349. * @param renderingGroupId The rendering group id corresponding to its index
  64350. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64351. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64352. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64353. */
  64354. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64355. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64356. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64357. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64358. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64359. };
  64360. /**
  64361. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64362. *
  64363. * @param renderingGroupId The rendering group id corresponding to its index
  64364. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64365. */
  64366. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64367. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64368. };
  64369. RenderTargetTexture.prototype.clone = function () {
  64370. var textureSize = this.getSize();
  64371. 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);
  64372. // Base texture
  64373. newTexture.hasAlpha = this.hasAlpha;
  64374. newTexture.level = this.level;
  64375. // RenderTarget Texture
  64376. newTexture.coordinatesMode = this.coordinatesMode;
  64377. if (this.renderList) {
  64378. newTexture.renderList = this.renderList.slice(0);
  64379. }
  64380. return newTexture;
  64381. };
  64382. RenderTargetTexture.prototype.serialize = function () {
  64383. if (!this.name) {
  64384. return null;
  64385. }
  64386. var serializationObject = _super.prototype.serialize.call(this);
  64387. serializationObject.renderTargetSize = this.getRenderSize();
  64388. serializationObject.renderList = [];
  64389. if (this.renderList) {
  64390. for (var index = 0; index < this.renderList.length; index++) {
  64391. serializationObject.renderList.push(this.renderList[index].id);
  64392. }
  64393. }
  64394. return serializationObject;
  64395. };
  64396. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64397. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64398. var objBuffer = this.getInternalTexture();
  64399. var scene = this.getScene();
  64400. if (objBuffer && scene) {
  64401. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64402. }
  64403. };
  64404. RenderTargetTexture.prototype.dispose = function () {
  64405. if (this._postProcessManager) {
  64406. this._postProcessManager.dispose();
  64407. this._postProcessManager = null;
  64408. }
  64409. this.clearPostProcesses(true);
  64410. if (this._resizeObserver) {
  64411. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64412. this._resizeObserver = null;
  64413. }
  64414. this.renderList = null;
  64415. // Remove from custom render targets
  64416. var scene = this.getScene();
  64417. if (!scene) {
  64418. return;
  64419. }
  64420. var index = scene.customRenderTargets.indexOf(this);
  64421. if (index >= 0) {
  64422. scene.customRenderTargets.splice(index, 1);
  64423. }
  64424. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64425. var camera = _a[_i];
  64426. index = camera.customRenderTargets.indexOf(this);
  64427. if (index >= 0) {
  64428. camera.customRenderTargets.splice(index, 1);
  64429. }
  64430. }
  64431. _super.prototype.dispose.call(this);
  64432. };
  64433. RenderTargetTexture.prototype._rebuild = function () {
  64434. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64435. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64436. }
  64437. if (this._postProcessManager) {
  64438. this._postProcessManager._rebuild();
  64439. }
  64440. };
  64441. /**
  64442. * Clear the info related to rendering groups preventing retention point in material dispose.
  64443. */
  64444. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64445. if (this._renderingManager) {
  64446. this._renderingManager.freeRenderingGroups();
  64447. }
  64448. };
  64449. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64450. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64451. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64452. return RenderTargetTexture;
  64453. }(BABYLON.Texture));
  64454. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64455. })(BABYLON || (BABYLON = {}));
  64456. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64457. var BABYLON;
  64458. (function (BABYLON) {
  64459. ;
  64460. var MultiRenderTarget = /** @class */ (function (_super) {
  64461. __extends(MultiRenderTarget, _super);
  64462. function MultiRenderTarget(name, size, count, scene, options) {
  64463. var _this = this;
  64464. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64465. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64466. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64467. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64468. _this._engine = scene.getEngine();
  64469. if (!_this.isSupported) {
  64470. _this.dispose();
  64471. return;
  64472. }
  64473. var types = [];
  64474. var samplingModes = [];
  64475. for (var i = 0; i < count; i++) {
  64476. if (options && options.types && options.types[i] !== undefined) {
  64477. types.push(options.types[i]);
  64478. }
  64479. else {
  64480. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64481. }
  64482. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64483. samplingModes.push(options.samplingModes[i]);
  64484. }
  64485. else {
  64486. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64487. }
  64488. }
  64489. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64490. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64491. _this._size = size;
  64492. _this._multiRenderTargetOptions = {
  64493. samplingModes: samplingModes,
  64494. generateMipMaps: generateMipMaps,
  64495. generateDepthBuffer: generateDepthBuffer,
  64496. generateStencilBuffer: generateStencilBuffer,
  64497. generateDepthTexture: generateDepthTexture,
  64498. types: types,
  64499. textureCount: count
  64500. };
  64501. _this._createInternalTextures();
  64502. _this._createTextures();
  64503. return _this;
  64504. }
  64505. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64506. get: function () {
  64507. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64508. },
  64509. enumerable: true,
  64510. configurable: true
  64511. });
  64512. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64513. get: function () {
  64514. return this._textures;
  64515. },
  64516. enumerable: true,
  64517. configurable: true
  64518. });
  64519. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64520. get: function () {
  64521. return this._textures[this._textures.length - 1];
  64522. },
  64523. enumerable: true,
  64524. configurable: true
  64525. });
  64526. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64527. set: function (wrap) {
  64528. if (this._textures) {
  64529. for (var i = 0; i < this._textures.length; i++) {
  64530. this._textures[i].wrapU = wrap;
  64531. }
  64532. }
  64533. },
  64534. enumerable: true,
  64535. configurable: true
  64536. });
  64537. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64538. set: function (wrap) {
  64539. if (this._textures) {
  64540. for (var i = 0; i < this._textures.length; i++) {
  64541. this._textures[i].wrapV = wrap;
  64542. }
  64543. }
  64544. },
  64545. enumerable: true,
  64546. configurable: true
  64547. });
  64548. MultiRenderTarget.prototype._rebuild = function () {
  64549. this.releaseInternalTextures();
  64550. this._createInternalTextures();
  64551. for (var i = 0; i < this._internalTextures.length; i++) {
  64552. var texture = this._textures[i];
  64553. texture._texture = this._internalTextures[i];
  64554. }
  64555. // Keeps references to frame buffer and stencil/depth buffer
  64556. this._texture = this._internalTextures[0];
  64557. };
  64558. MultiRenderTarget.prototype._createInternalTextures = function () {
  64559. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64560. };
  64561. MultiRenderTarget.prototype._createTextures = function () {
  64562. this._textures = [];
  64563. for (var i = 0; i < this._internalTextures.length; i++) {
  64564. var texture = new BABYLON.Texture(null, this.getScene());
  64565. texture._texture = this._internalTextures[i];
  64566. this._textures.push(texture);
  64567. }
  64568. // Keeps references to frame buffer and stencil/depth buffer
  64569. this._texture = this._internalTextures[0];
  64570. };
  64571. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64572. get: function () {
  64573. return this._samples;
  64574. },
  64575. set: function (value) {
  64576. if (this._samples === value) {
  64577. return;
  64578. }
  64579. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64580. },
  64581. enumerable: true,
  64582. configurable: true
  64583. });
  64584. MultiRenderTarget.prototype.resize = function (size) {
  64585. this.releaseInternalTextures();
  64586. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64587. this._createInternalTextures();
  64588. };
  64589. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64590. var _this = this;
  64591. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64592. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64593. });
  64594. };
  64595. MultiRenderTarget.prototype.dispose = function () {
  64596. this.releaseInternalTextures();
  64597. _super.prototype.dispose.call(this);
  64598. };
  64599. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64600. if (!this._internalTextures) {
  64601. return;
  64602. }
  64603. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64604. if (this._internalTextures[i] !== undefined) {
  64605. this._internalTextures[i].dispose();
  64606. this._internalTextures.splice(i, 1);
  64607. }
  64608. }
  64609. };
  64610. return MultiRenderTarget;
  64611. }(BABYLON.RenderTargetTexture));
  64612. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64613. })(BABYLON || (BABYLON = {}));
  64614. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64615. var BABYLON;
  64616. (function (BABYLON) {
  64617. var MirrorTexture = /** @class */ (function (_super) {
  64618. __extends(MirrorTexture, _super);
  64619. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64620. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64621. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64622. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64623. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64624. _this.scene = scene;
  64625. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64626. _this._transformMatrix = BABYLON.Matrix.Zero();
  64627. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64628. _this._adaptiveBlurKernel = 0;
  64629. _this._blurKernelX = 0;
  64630. _this._blurKernelY = 0;
  64631. _this._blurRatio = 1.0;
  64632. _this.ignoreCameraViewport = true;
  64633. _this._updateGammaSpace();
  64634. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64635. _this._updateGammaSpace;
  64636. });
  64637. _this.onBeforeRenderObservable.add(function () {
  64638. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64639. _this._savedViewMatrix = scene.getViewMatrix();
  64640. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64641. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64642. scene.clipPlane = _this.mirrorPlane;
  64643. scene.getEngine().cullBackFaces = false;
  64644. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64645. });
  64646. _this.onAfterRenderObservable.add(function () {
  64647. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64648. scene.getEngine().cullBackFaces = true;
  64649. scene._mirroredCameraPosition = null;
  64650. delete scene.clipPlane;
  64651. });
  64652. return _this;
  64653. }
  64654. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64655. get: function () {
  64656. return this._blurRatio;
  64657. },
  64658. set: function (value) {
  64659. if (this._blurRatio === value) {
  64660. return;
  64661. }
  64662. this._blurRatio = value;
  64663. this._preparePostProcesses();
  64664. },
  64665. enumerable: true,
  64666. configurable: true
  64667. });
  64668. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64669. set: function (value) {
  64670. this._adaptiveBlurKernel = value;
  64671. this._autoComputeBlurKernel();
  64672. },
  64673. enumerable: true,
  64674. configurable: true
  64675. });
  64676. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64677. set: function (value) {
  64678. this.blurKernelX = value;
  64679. this.blurKernelY = value;
  64680. },
  64681. enumerable: true,
  64682. configurable: true
  64683. });
  64684. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64685. get: function () {
  64686. return this._blurKernelX;
  64687. },
  64688. set: function (value) {
  64689. if (this._blurKernelX === value) {
  64690. return;
  64691. }
  64692. this._blurKernelX = value;
  64693. this._preparePostProcesses();
  64694. },
  64695. enumerable: true,
  64696. configurable: true
  64697. });
  64698. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64699. get: function () {
  64700. return this._blurKernelY;
  64701. },
  64702. set: function (value) {
  64703. if (this._blurKernelY === value) {
  64704. return;
  64705. }
  64706. this._blurKernelY = value;
  64707. this._preparePostProcesses();
  64708. },
  64709. enumerable: true,
  64710. configurable: true
  64711. });
  64712. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64713. var engine = this.getScene().getEngine();
  64714. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64715. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64716. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64717. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64718. };
  64719. MirrorTexture.prototype._onRatioRescale = function () {
  64720. if (this._sizeRatio) {
  64721. this.resize(this._initialSizeParameter);
  64722. if (!this._adaptiveBlurKernel) {
  64723. this._preparePostProcesses();
  64724. }
  64725. }
  64726. if (this._adaptiveBlurKernel) {
  64727. this._autoComputeBlurKernel();
  64728. }
  64729. };
  64730. MirrorTexture.prototype._updateGammaSpace = function () {
  64731. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64732. };
  64733. MirrorTexture.prototype._preparePostProcesses = function () {
  64734. this.clearPostProcesses(true);
  64735. if (this._blurKernelX && this._blurKernelY) {
  64736. var engine = this.getScene().getEngine();
  64737. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64738. 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);
  64739. this._blurX.autoClear = false;
  64740. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64741. this._blurX.inputTexture = this._texture;
  64742. }
  64743. else {
  64744. this._blurX.alwaysForcePOT = true;
  64745. }
  64746. 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);
  64747. this._blurY.autoClear = false;
  64748. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64749. this.addPostProcess(this._blurX);
  64750. this.addPostProcess(this._blurY);
  64751. }
  64752. else {
  64753. if (this._blurY) {
  64754. this.removePostProcess(this._blurY);
  64755. this._blurY.dispose();
  64756. this._blurY = null;
  64757. }
  64758. if (this._blurX) {
  64759. this.removePostProcess(this._blurX);
  64760. this._blurX.dispose();
  64761. this._blurX = null;
  64762. }
  64763. }
  64764. };
  64765. MirrorTexture.prototype.clone = function () {
  64766. var scene = this.getScene();
  64767. if (!scene) {
  64768. return this;
  64769. }
  64770. var textureSize = this.getSize();
  64771. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64772. // Base texture
  64773. newTexture.hasAlpha = this.hasAlpha;
  64774. newTexture.level = this.level;
  64775. // Mirror Texture
  64776. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64777. if (this.renderList) {
  64778. newTexture.renderList = this.renderList.slice(0);
  64779. }
  64780. return newTexture;
  64781. };
  64782. MirrorTexture.prototype.serialize = function () {
  64783. if (!this.name) {
  64784. return null;
  64785. }
  64786. var serializationObject = _super.prototype.serialize.call(this);
  64787. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64788. return serializationObject;
  64789. };
  64790. MirrorTexture.prototype.dispose = function () {
  64791. _super.prototype.dispose.call(this);
  64792. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64793. };
  64794. return MirrorTexture;
  64795. }(BABYLON.RenderTargetTexture));
  64796. BABYLON.MirrorTexture = MirrorTexture;
  64797. })(BABYLON || (BABYLON = {}));
  64798. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64799. var BABYLON;
  64800. (function (BABYLON) {
  64801. /**
  64802. * Creates a refraction texture used by refraction channel of the standard material.
  64803. * @param name the texture name
  64804. * @param size size of the underlying texture
  64805. * @param scene root scene
  64806. */
  64807. var RefractionTexture = /** @class */ (function (_super) {
  64808. __extends(RefractionTexture, _super);
  64809. function RefractionTexture(name, size, scene, generateMipMaps) {
  64810. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64811. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64812. _this.depth = 2.0;
  64813. _this.onBeforeRenderObservable.add(function () {
  64814. scene.clipPlane = _this.refractionPlane;
  64815. });
  64816. _this.onAfterRenderObservable.add(function () {
  64817. delete scene.clipPlane;
  64818. });
  64819. return _this;
  64820. }
  64821. RefractionTexture.prototype.clone = function () {
  64822. var scene = this.getScene();
  64823. if (!scene) {
  64824. return this;
  64825. }
  64826. var textureSize = this.getSize();
  64827. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64828. // Base texture
  64829. newTexture.hasAlpha = this.hasAlpha;
  64830. newTexture.level = this.level;
  64831. // Refraction Texture
  64832. newTexture.refractionPlane = this.refractionPlane.clone();
  64833. if (this.renderList) {
  64834. newTexture.renderList = this.renderList.slice(0);
  64835. }
  64836. newTexture.depth = this.depth;
  64837. return newTexture;
  64838. };
  64839. RefractionTexture.prototype.serialize = function () {
  64840. if (!this.name) {
  64841. return null;
  64842. }
  64843. var serializationObject = _super.prototype.serialize.call(this);
  64844. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64845. serializationObject.depth = this.depth;
  64846. return serializationObject;
  64847. };
  64848. return RefractionTexture;
  64849. }(BABYLON.RenderTargetTexture));
  64850. BABYLON.RefractionTexture = RefractionTexture;
  64851. })(BABYLON || (BABYLON = {}));
  64852. //# sourceMappingURL=babylon.refractionTexture.js.map
  64853. var BABYLON;
  64854. (function (BABYLON) {
  64855. /**
  64856. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64857. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64858. */
  64859. var DynamicTexture = /** @class */ (function (_super) {
  64860. __extends(DynamicTexture, _super);
  64861. /**
  64862. * Creates a {BABYLON.DynamicTexture}
  64863. * @param name defines the name of the texture
  64864. * @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
  64865. * @param scene defines the scene where you want the texture
  64866. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64867. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64868. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64869. */
  64870. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64871. if (scene === void 0) { scene = null; }
  64872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64873. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64874. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64875. _this.name = name;
  64876. _this._engine = _this.getScene().getEngine();
  64877. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64878. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64879. _this._generateMipMaps = generateMipMaps;
  64880. if (options.getContext) {
  64881. _this._canvas = options;
  64882. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64883. }
  64884. else {
  64885. _this._canvas = document.createElement("canvas");
  64886. if (options.width || options.width === 0) {
  64887. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64888. }
  64889. else {
  64890. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64891. }
  64892. }
  64893. var textureSize = _this.getSize();
  64894. _this._canvas.width = textureSize.width;
  64895. _this._canvas.height = textureSize.height;
  64896. _this._context = _this._canvas.getContext("2d");
  64897. return _this;
  64898. }
  64899. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64900. /**
  64901. * Gets the current state of canRescale
  64902. */
  64903. get: function () {
  64904. return true;
  64905. },
  64906. enumerable: true,
  64907. configurable: true
  64908. });
  64909. DynamicTexture.prototype._recreate = function (textureSize) {
  64910. this._canvas.width = textureSize.width;
  64911. this._canvas.height = textureSize.height;
  64912. this.releaseInternalTexture();
  64913. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64914. };
  64915. /**
  64916. * Scales the texture
  64917. * @param ratio the scale factor to apply to both width and height
  64918. */
  64919. DynamicTexture.prototype.scale = function (ratio) {
  64920. var textureSize = this.getSize();
  64921. textureSize.width *= ratio;
  64922. textureSize.height *= ratio;
  64923. this._recreate(textureSize);
  64924. };
  64925. /**
  64926. * Resizes the texture
  64927. * @param width the new width
  64928. * @param height the new height
  64929. */
  64930. DynamicTexture.prototype.scaleTo = function (width, height) {
  64931. var textureSize = this.getSize();
  64932. textureSize.width = width;
  64933. textureSize.height = height;
  64934. this._recreate(textureSize);
  64935. };
  64936. /**
  64937. * Gets the context of the canvas used by the texture
  64938. * @returns the canvas context of the dynamic texture
  64939. */
  64940. DynamicTexture.prototype.getContext = function () {
  64941. return this._context;
  64942. };
  64943. /**
  64944. * Clears the texture
  64945. */
  64946. DynamicTexture.prototype.clear = function () {
  64947. var size = this.getSize();
  64948. this._context.fillRect(0, 0, size.width, size.height);
  64949. };
  64950. /**
  64951. * Updates the texture
  64952. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64953. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64954. */
  64955. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64956. if (premulAlpha === void 0) { premulAlpha = false; }
  64957. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64958. };
  64959. /**
  64960. * Draws text onto the texture
  64961. * @param text defines the text to be drawn
  64962. * @param x defines the placement of the text from the left
  64963. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64964. * @param font defines the font to be used with font-style, font-size, font-name
  64965. * @param color defines the color used for the text
  64966. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64967. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64968. * @param update defines whether texture is immediately update (default is true)
  64969. */
  64970. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64971. if (update === void 0) { update = true; }
  64972. var size = this.getSize();
  64973. if (clearColor) {
  64974. this._context.fillStyle = clearColor;
  64975. this._context.fillRect(0, 0, size.width, size.height);
  64976. }
  64977. this._context.font = font;
  64978. if (x === null || x === undefined) {
  64979. var textSize = this._context.measureText(text);
  64980. x = (size.width - textSize.width) / 2;
  64981. }
  64982. if (y === null || y === undefined) {
  64983. var fontSize = parseInt((font.replace(/\D/g, '')));
  64984. y = (size.height / 2) + (fontSize / 3.65);
  64985. }
  64986. this._context.fillStyle = color;
  64987. this._context.fillText(text, x, y);
  64988. if (update) {
  64989. this.update(invertY);
  64990. }
  64991. };
  64992. /**
  64993. * Clones the texture
  64994. * @returns the clone of the texture.
  64995. */
  64996. DynamicTexture.prototype.clone = function () {
  64997. var scene = this.getScene();
  64998. if (!scene) {
  64999. return this;
  65000. }
  65001. var textureSize = this.getSize();
  65002. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65003. // Base texture
  65004. newTexture.hasAlpha = this.hasAlpha;
  65005. newTexture.level = this.level;
  65006. // Dynamic Texture
  65007. newTexture.wrapU = this.wrapU;
  65008. newTexture.wrapV = this.wrapV;
  65009. return newTexture;
  65010. };
  65011. /** @hidden */
  65012. DynamicTexture.prototype._rebuild = function () {
  65013. this.update();
  65014. };
  65015. return DynamicTexture;
  65016. }(BABYLON.Texture));
  65017. BABYLON.DynamicTexture = DynamicTexture;
  65018. })(BABYLON || (BABYLON = {}));
  65019. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65020. var BABYLON;
  65021. (function (BABYLON) {
  65022. var VideoTexture = /** @class */ (function (_super) {
  65023. __extends(VideoTexture, _super);
  65024. /**
  65025. * Creates a video texture.
  65026. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65027. * @param {string | null} name optional name, will detect from video source, if not defined
  65028. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65029. * @param {BABYLON.Scene} scene is obviously the current scene.
  65030. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65031. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65032. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65033. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65034. */
  65035. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65036. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65037. if (invertY === void 0) { invertY = false; }
  65038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65039. if (settings === void 0) { settings = {
  65040. autoPlay: true,
  65041. loop: true,
  65042. autoUpdateTexture: true,
  65043. }; }
  65044. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65045. _this._onUserActionRequestedObservable = null;
  65046. _this._stillImageCaptured = false;
  65047. _this._createInternalTexture = function () {
  65048. if (_this._texture != null) {
  65049. return;
  65050. }
  65051. if (!_this._engine.needPOTTextures ||
  65052. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65053. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65054. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65055. }
  65056. else {
  65057. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65058. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65059. _this._generateMipMaps = false;
  65060. }
  65061. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65062. if (!_this.video.autoplay) {
  65063. var oldHandler_1 = _this.video.onplaying;
  65064. var error_1 = false;
  65065. _this.video.onplaying = function () {
  65066. _this.video.onplaying = oldHandler_1;
  65067. _this._texture.isReady = true;
  65068. _this._updateInternalTexture();
  65069. if (!error_1) {
  65070. _this.video.pause();
  65071. }
  65072. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65073. _this.onLoadObservable.notifyObservers(_this);
  65074. }
  65075. };
  65076. var playing = _this.video.play();
  65077. if (playing) {
  65078. playing.then(function () {
  65079. // Everything is good.
  65080. })
  65081. .catch(function () {
  65082. error_1 = true;
  65083. // On Chrome for instance, new policies might prevent playing without user interaction.
  65084. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  65085. _this._onUserActionRequestedObservable.notifyObservers(_this);
  65086. }
  65087. });
  65088. }
  65089. else {
  65090. _this.video.onplaying = oldHandler_1;
  65091. _this._texture.isReady = true;
  65092. _this._updateInternalTexture();
  65093. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65094. _this.onLoadObservable.notifyObservers(_this);
  65095. }
  65096. }
  65097. }
  65098. else {
  65099. _this._texture.isReady = true;
  65100. _this._updateInternalTexture();
  65101. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65102. _this.onLoadObservable.notifyObservers(_this);
  65103. }
  65104. }
  65105. };
  65106. _this.reset = function () {
  65107. if (_this._texture == null) {
  65108. return;
  65109. }
  65110. _this._texture.dispose();
  65111. _this._texture = null;
  65112. };
  65113. _this._updateInternalTexture = function (e) {
  65114. if (_this._texture == null || !_this._texture.isReady) {
  65115. return;
  65116. }
  65117. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65118. return;
  65119. }
  65120. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65121. };
  65122. _this._engine = _this.getScene().getEngine();
  65123. _this._generateMipMaps = generateMipMaps;
  65124. _this._samplingMode = samplingMode;
  65125. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65126. _this.name = name || _this._getName(src);
  65127. _this.video = _this._getVideo(src);
  65128. if (settings.poster) {
  65129. _this.video.poster = settings.poster;
  65130. }
  65131. if (settings.autoPlay !== undefined) {
  65132. _this.video.autoplay = settings.autoPlay;
  65133. }
  65134. if (settings.loop !== undefined) {
  65135. _this.video.loop = settings.loop;
  65136. }
  65137. _this.video.setAttribute("playsinline", "");
  65138. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65139. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65140. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65141. _this.video.addEventListener("emptied", _this.reset);
  65142. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65143. _this._createInternalTexture();
  65144. }
  65145. return _this;
  65146. }
  65147. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  65148. get: function () {
  65149. if (!this._onUserActionRequestedObservable) {
  65150. this._onUserActionRequestedObservable = new BABYLON.Observable();
  65151. }
  65152. return this._onUserActionRequestedObservable;
  65153. },
  65154. enumerable: true,
  65155. configurable: true
  65156. });
  65157. VideoTexture.prototype._getName = function (src) {
  65158. if (src instanceof HTMLVideoElement) {
  65159. return src.currentSrc;
  65160. }
  65161. if (typeof src === "object") {
  65162. return src.toString();
  65163. }
  65164. return src;
  65165. };
  65166. ;
  65167. VideoTexture.prototype._getVideo = function (src) {
  65168. if (src instanceof HTMLVideoElement) {
  65169. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65170. return src;
  65171. }
  65172. var video = document.createElement("video");
  65173. if (typeof src === "string") {
  65174. BABYLON.Tools.SetCorsBehavior(src, video);
  65175. video.src = src;
  65176. }
  65177. else {
  65178. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65179. src.forEach(function (url) {
  65180. var source = document.createElement("source");
  65181. source.src = url;
  65182. video.appendChild(source);
  65183. });
  65184. }
  65185. return video;
  65186. };
  65187. ;
  65188. /**
  65189. * Internal method to initiate `update`.
  65190. */
  65191. VideoTexture.prototype._rebuild = function () {
  65192. this.update();
  65193. };
  65194. /**
  65195. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65196. */
  65197. VideoTexture.prototype.update = function () {
  65198. if (!this.autoUpdateTexture) {
  65199. // Expecting user to call `updateTexture` manually
  65200. return;
  65201. }
  65202. this.updateTexture(true);
  65203. };
  65204. /**
  65205. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65206. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65207. */
  65208. VideoTexture.prototype.updateTexture = function (isVisible) {
  65209. if (!isVisible) {
  65210. return;
  65211. }
  65212. if (this.video.paused && this._stillImageCaptured) {
  65213. return;
  65214. }
  65215. this._stillImageCaptured = true;
  65216. this._updateInternalTexture();
  65217. };
  65218. /**
  65219. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65220. * @param url New url.
  65221. */
  65222. VideoTexture.prototype.updateURL = function (url) {
  65223. this.video.src = url;
  65224. };
  65225. VideoTexture.prototype.dispose = function () {
  65226. _super.prototype.dispose.call(this);
  65227. if (this._onUserActionRequestedObservable) {
  65228. this._onUserActionRequestedObservable.clear();
  65229. this._onUserActionRequestedObservable = null;
  65230. }
  65231. this.video.removeEventListener("canplay", this._createInternalTexture);
  65232. this.video.removeEventListener("paused", this._updateInternalTexture);
  65233. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65234. this.video.removeEventListener("emptied", this.reset);
  65235. this.video.pause();
  65236. };
  65237. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65238. var video = document.createElement("video");
  65239. video.setAttribute('autoplay', '');
  65240. video.setAttribute('muted', '');
  65241. video.setAttribute('playsinline', '');
  65242. var constraintsDeviceId;
  65243. if (constraints && constraints.deviceId) {
  65244. constraintsDeviceId = {
  65245. exact: constraints.deviceId,
  65246. };
  65247. }
  65248. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65249. if (navigator.mediaDevices) {
  65250. navigator.mediaDevices.getUserMedia({ video: constraints })
  65251. .then(function (stream) {
  65252. if (video.mozSrcObject !== undefined) {
  65253. // hack for Firefox < 19
  65254. video.mozSrcObject = stream;
  65255. }
  65256. else {
  65257. video.srcObject = stream;
  65258. }
  65259. var onPlaying = function () {
  65260. if (onReady) {
  65261. onReady(new VideoTexture("video", video, scene, true, true));
  65262. }
  65263. video.removeEventListener("playing", onPlaying);
  65264. };
  65265. video.addEventListener("playing", onPlaying);
  65266. video.play();
  65267. })
  65268. .catch(function (err) {
  65269. BABYLON.Tools.Error(err.name);
  65270. });
  65271. }
  65272. else {
  65273. navigator.getUserMedia =
  65274. navigator.getUserMedia ||
  65275. navigator.webkitGetUserMedia ||
  65276. navigator.mozGetUserMedia ||
  65277. navigator.msGetUserMedia;
  65278. if (navigator.getUserMedia) {
  65279. navigator.getUserMedia({
  65280. video: {
  65281. deviceId: constraintsDeviceId,
  65282. width: {
  65283. min: (constraints && constraints.minWidth) || 256,
  65284. max: (constraints && constraints.maxWidth) || 640,
  65285. },
  65286. height: {
  65287. min: (constraints && constraints.minHeight) || 256,
  65288. max: (constraints && constraints.maxHeight) || 480,
  65289. },
  65290. },
  65291. }, function (stream) {
  65292. if (video.mozSrcObject !== undefined) {
  65293. // hack for Firefox < 19
  65294. video.mozSrcObject = stream;
  65295. }
  65296. else {
  65297. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65298. }
  65299. video.play();
  65300. if (onReady) {
  65301. onReady(new VideoTexture("video", video, scene, true, true));
  65302. }
  65303. }, function (e) {
  65304. BABYLON.Tools.Error(e.name);
  65305. });
  65306. }
  65307. }
  65308. };
  65309. return VideoTexture;
  65310. }(BABYLON.Texture));
  65311. BABYLON.VideoTexture = VideoTexture;
  65312. })(BABYLON || (BABYLON = {}));
  65313. //# sourceMappingURL=babylon.videoTexture.js.map
  65314. var BABYLON;
  65315. (function (BABYLON) {
  65316. var RawTexture = /** @class */ (function (_super) {
  65317. __extends(RawTexture, _super);
  65318. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65319. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65320. if (invertY === void 0) { invertY = false; }
  65321. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65322. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65323. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65324. _this.format = format;
  65325. _this._engine = scene.getEngine();
  65326. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65327. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65328. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65329. return _this;
  65330. }
  65331. RawTexture.prototype.update = function (data) {
  65332. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65333. };
  65334. // Statics
  65335. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65336. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65337. if (invertY === void 0) { invertY = false; }
  65338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65339. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65340. };
  65341. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65342. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65343. if (invertY === void 0) { invertY = false; }
  65344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65345. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65346. };
  65347. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65348. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65349. if (invertY === void 0) { invertY = false; }
  65350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65351. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65352. };
  65353. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65354. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65355. if (invertY === void 0) { invertY = false; }
  65356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65357. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65358. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65359. };
  65360. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65361. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65362. if (invertY === void 0) { invertY = false; }
  65363. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65364. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65365. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65366. };
  65367. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65368. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65369. if (invertY === void 0) { invertY = false; }
  65370. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65371. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65372. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65373. };
  65374. return RawTexture;
  65375. }(BABYLON.Texture));
  65376. BABYLON.RawTexture = RawTexture;
  65377. })(BABYLON || (BABYLON = {}));
  65378. //# sourceMappingURL=babylon.rawTexture.js.map
  65379. var BABYLON;
  65380. (function (BABYLON) {
  65381. /**
  65382. * Class used to store 3D textures containing user data
  65383. */
  65384. var RawTexture3D = /** @class */ (function (_super) {
  65385. __extends(RawTexture3D, _super);
  65386. /**
  65387. * Create a new RawTexture3D
  65388. * @param data defines the data of the texture
  65389. * @param width defines the width of the texture
  65390. * @param height defines the height of the texture
  65391. * @param depth defines the depth of the texture
  65392. * @param format defines the texture format to use
  65393. * @param scene defines the hosting scene
  65394. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65395. * @param invertY defines if texture must be stored with Y axis inverted
  65396. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65397. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65398. */
  65399. function RawTexture3D(data, width, height, depth,
  65400. /** Gets or sets the texture format to use */
  65401. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65402. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65403. if (invertY === void 0) { invertY = false; }
  65404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65405. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65406. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65407. _this.format = format;
  65408. _this._engine = scene.getEngine();
  65409. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65410. _this.is3D = true;
  65411. return _this;
  65412. }
  65413. /**
  65414. * Update the texture with new data
  65415. * @param data defines the data to store in the texture
  65416. */
  65417. RawTexture3D.prototype.update = function (data) {
  65418. if (!this._texture) {
  65419. return;
  65420. }
  65421. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65422. };
  65423. return RawTexture3D;
  65424. }(BABYLON.Texture));
  65425. BABYLON.RawTexture3D = RawTexture3D;
  65426. })(BABYLON || (BABYLON = {}));
  65427. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65428. var BABYLON;
  65429. (function (BABYLON) {
  65430. /**
  65431. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65432. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65433. */
  65434. var PostProcessManager = /** @class */ (function () {
  65435. /**
  65436. * Creates a new instance PostProcess
  65437. * @param scene The scene that the post process is associated with.
  65438. */
  65439. function PostProcessManager(scene) {
  65440. this._vertexBuffers = {};
  65441. this._scene = scene;
  65442. }
  65443. PostProcessManager.prototype._prepareBuffers = function () {
  65444. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65445. return;
  65446. }
  65447. // VBO
  65448. var vertices = [];
  65449. vertices.push(1, 1);
  65450. vertices.push(-1, 1);
  65451. vertices.push(-1, -1);
  65452. vertices.push(1, -1);
  65453. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65454. this._buildIndexBuffer();
  65455. };
  65456. PostProcessManager.prototype._buildIndexBuffer = function () {
  65457. // Indices
  65458. var indices = [];
  65459. indices.push(0);
  65460. indices.push(1);
  65461. indices.push(2);
  65462. indices.push(0);
  65463. indices.push(2);
  65464. indices.push(3);
  65465. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65466. };
  65467. /**
  65468. * Rebuilds the vertex buffers of the manager.
  65469. */
  65470. PostProcessManager.prototype._rebuild = function () {
  65471. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65472. if (!vb) {
  65473. return;
  65474. }
  65475. vb._rebuild();
  65476. this._buildIndexBuffer();
  65477. };
  65478. // Methods
  65479. /**
  65480. * Prepares a frame to be run through a post process.
  65481. * @param sourceTexture The input texture to the post procesess. (default: null)
  65482. * @param postProcesses An array of post processes to be run. (default: null)
  65483. * @returns True if the post processes were able to be run.
  65484. */
  65485. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65486. if (sourceTexture === void 0) { sourceTexture = null; }
  65487. if (postProcesses === void 0) { postProcesses = null; }
  65488. var camera = this._scene.activeCamera;
  65489. if (!camera) {
  65490. return false;
  65491. }
  65492. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65493. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65494. return false;
  65495. }
  65496. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65497. return true;
  65498. };
  65499. /**
  65500. * Manually render a set of post processes to a texture.
  65501. * @param postProcesses An array of post processes to be run.
  65502. * @param targetTexture The target texture to render to.
  65503. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65504. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65505. * @param lodLevel defines which lod of the texture to render to
  65506. */
  65507. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65508. if (targetTexture === void 0) { targetTexture = null; }
  65509. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65510. if (faceIndex === void 0) { faceIndex = 0; }
  65511. if (lodLevel === void 0) { lodLevel = 0; }
  65512. var engine = this._scene.getEngine();
  65513. for (var index = 0; index < postProcesses.length; index++) {
  65514. if (index < postProcesses.length - 1) {
  65515. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65516. }
  65517. else {
  65518. if (targetTexture) {
  65519. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65520. }
  65521. else {
  65522. engine.restoreDefaultFramebuffer();
  65523. }
  65524. }
  65525. var pp = postProcesses[index];
  65526. var effect = pp.apply();
  65527. if (effect) {
  65528. pp.onBeforeRenderObservable.notifyObservers(effect);
  65529. // VBOs
  65530. this._prepareBuffers();
  65531. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65532. // Draw order
  65533. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65534. pp.onAfterRenderObservable.notifyObservers(effect);
  65535. }
  65536. }
  65537. // Restore depth buffer
  65538. engine.setDepthBuffer(true);
  65539. engine.setDepthWrite(true);
  65540. };
  65541. /**
  65542. * Finalize the result of the output of the postprocesses.
  65543. * @param doNotPresent If true the result will not be displayed to the screen.
  65544. * @param targetTexture The target texture to render to.
  65545. * @param faceIndex The index of the face to bind the target texture to.
  65546. * @param postProcesses The array of post processes to render.
  65547. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65548. */
  65549. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65550. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65551. var camera = this._scene.activeCamera;
  65552. if (!camera) {
  65553. return;
  65554. }
  65555. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65556. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65557. return;
  65558. }
  65559. var engine = this._scene.getEngine();
  65560. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65561. var pp = postProcesses[index];
  65562. if (index < len - 1) {
  65563. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65564. }
  65565. else {
  65566. if (targetTexture) {
  65567. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65568. pp._outputTexture = targetTexture;
  65569. }
  65570. else {
  65571. engine.restoreDefaultFramebuffer();
  65572. pp._outputTexture = null;
  65573. }
  65574. }
  65575. if (doNotPresent) {
  65576. break;
  65577. }
  65578. var effect = pp.apply();
  65579. if (effect) {
  65580. pp.onBeforeRenderObservable.notifyObservers(effect);
  65581. // VBOs
  65582. this._prepareBuffers();
  65583. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65584. // Draw order
  65585. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65586. pp.onAfterRenderObservable.notifyObservers(effect);
  65587. }
  65588. }
  65589. // Restore states
  65590. engine.setDepthBuffer(true);
  65591. engine.setDepthWrite(true);
  65592. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65593. };
  65594. /**
  65595. * Disposes of the post process manager.
  65596. */
  65597. PostProcessManager.prototype.dispose = function () {
  65598. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65599. if (buffer) {
  65600. buffer.dispose();
  65601. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65602. }
  65603. if (this._indexBuffer) {
  65604. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65605. this._indexBuffer = null;
  65606. }
  65607. };
  65608. return PostProcessManager;
  65609. }());
  65610. BABYLON.PostProcessManager = PostProcessManager;
  65611. })(BABYLON || (BABYLON = {}));
  65612. //# sourceMappingURL=babylon.postProcessManager.js.map
  65613. var BABYLON;
  65614. (function (BABYLON) {
  65615. /**
  65616. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65617. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65618. */
  65619. var PostProcess = /** @class */ (function () {
  65620. /**
  65621. * Creates a new instance PostProcess
  65622. * @param name The name of the PostProcess.
  65623. * @param fragmentUrl The url of the fragment shader to be used.
  65624. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65625. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65626. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65627. * @param camera The camera to apply the render pass to.
  65628. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65629. * @param engine The engine which the post process will be applied. (default: current engine)
  65630. * @param reusable If the post process can be reused on the same frame. (default: false)
  65631. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65632. * @param textureType Type of textures used when performing the post process. (default: 0)
  65633. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65634. * @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
  65635. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65636. */
  65637. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65639. if (defines === void 0) { defines = null; }
  65640. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65641. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65642. if (blockCompilation === void 0) { blockCompilation = false; }
  65643. this.name = name;
  65644. /**
  65645. * Width of the texture to apply the post process on
  65646. */
  65647. this.width = -1;
  65648. /**
  65649. * Height of the texture to apply the post process on
  65650. */
  65651. this.height = -1;
  65652. /**
  65653. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65654. */
  65655. this._outputTexture = null;
  65656. /**
  65657. * If the buffer needs to be cleared before applying the post process. (default: true)
  65658. * Should be set to false if shader will overwrite all previous pixels.
  65659. */
  65660. this.autoClear = true;
  65661. /**
  65662. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65663. */
  65664. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65665. /**
  65666. * Animations to be used for the post processing
  65667. */
  65668. this.animations = new Array();
  65669. /**
  65670. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65671. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65672. */
  65673. this.enablePixelPerfectMode = false;
  65674. /**
  65675. * Force the postprocess to be applied without taking in account viewport
  65676. */
  65677. this.forceFullscreenViewport = true;
  65678. /**
  65679. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65680. *
  65681. * | Value | Type | Description |
  65682. * | ----- | ----------------------------------- | ----------- |
  65683. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65684. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65685. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65686. *
  65687. */
  65688. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65689. /**
  65690. * Force textures to be a power of two (default: false)
  65691. */
  65692. this.alwaysForcePOT = false;
  65693. /**
  65694. * Number of sample textures (default: 1)
  65695. */
  65696. this.samples = 1;
  65697. /**
  65698. * Modify the scale of the post process to be the same as the viewport (default: false)
  65699. */
  65700. this.adaptScaleToCurrentViewport = false;
  65701. this._reusable = false;
  65702. /**
  65703. * Smart array of input and output textures for the post process.
  65704. */
  65705. this._textures = new BABYLON.SmartArray(2);
  65706. /**
  65707. * The index in _textures that corresponds to the output texture.
  65708. */
  65709. this._currentRenderTextureInd = 0;
  65710. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65711. this._texelSize = BABYLON.Vector2.Zero();
  65712. // Events
  65713. /**
  65714. * An event triggered when the postprocess is activated.
  65715. */
  65716. this.onActivateObservable = new BABYLON.Observable();
  65717. /**
  65718. * An event triggered when the postprocess changes its size.
  65719. */
  65720. this.onSizeChangedObservable = new BABYLON.Observable();
  65721. /**
  65722. * An event triggered when the postprocess applies its effect.
  65723. */
  65724. this.onApplyObservable = new BABYLON.Observable();
  65725. /**
  65726. * An event triggered before rendering the postprocess
  65727. */
  65728. this.onBeforeRenderObservable = new BABYLON.Observable();
  65729. /**
  65730. * An event triggered after rendering the postprocess
  65731. */
  65732. this.onAfterRenderObservable = new BABYLON.Observable();
  65733. if (camera != null) {
  65734. this._camera = camera;
  65735. this._scene = camera.getScene();
  65736. camera.attachPostProcess(this);
  65737. this._engine = this._scene.getEngine();
  65738. this._scene.postProcesses.push(this);
  65739. }
  65740. else if (engine) {
  65741. this._engine = engine;
  65742. this._engine.postProcesses.push(this);
  65743. }
  65744. this._options = options;
  65745. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65746. this._reusable = reusable || false;
  65747. this._textureType = textureType;
  65748. this._samplers = samplers || [];
  65749. this._samplers.push("textureSampler");
  65750. this._fragmentUrl = fragmentUrl;
  65751. this._vertexUrl = vertexUrl;
  65752. this._parameters = parameters || [];
  65753. this._parameters.push("scale");
  65754. this._indexParameters = indexParameters;
  65755. if (!blockCompilation) {
  65756. this.updateEffect(defines);
  65757. }
  65758. }
  65759. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65760. /**
  65761. * A function that is added to the onActivateObservable
  65762. */
  65763. set: function (callback) {
  65764. if (this._onActivateObserver) {
  65765. this.onActivateObservable.remove(this._onActivateObserver);
  65766. }
  65767. if (callback) {
  65768. this._onActivateObserver = this.onActivateObservable.add(callback);
  65769. }
  65770. },
  65771. enumerable: true,
  65772. configurable: true
  65773. });
  65774. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65775. /**
  65776. * A function that is added to the onSizeChangedObservable
  65777. */
  65778. set: function (callback) {
  65779. if (this._onSizeChangedObserver) {
  65780. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65781. }
  65782. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65783. },
  65784. enumerable: true,
  65785. configurable: true
  65786. });
  65787. Object.defineProperty(PostProcess.prototype, "onApply", {
  65788. /**
  65789. * A function that is added to the onApplyObservable
  65790. */
  65791. set: function (callback) {
  65792. if (this._onApplyObserver) {
  65793. this.onApplyObservable.remove(this._onApplyObserver);
  65794. }
  65795. this._onApplyObserver = this.onApplyObservable.add(callback);
  65796. },
  65797. enumerable: true,
  65798. configurable: true
  65799. });
  65800. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65801. /**
  65802. * A function that is added to the onBeforeRenderObservable
  65803. */
  65804. set: function (callback) {
  65805. if (this._onBeforeRenderObserver) {
  65806. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65807. }
  65808. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65809. },
  65810. enumerable: true,
  65811. configurable: true
  65812. });
  65813. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65814. /**
  65815. * A function that is added to the onAfterRenderObservable
  65816. */
  65817. set: function (callback) {
  65818. if (this._onAfterRenderObserver) {
  65819. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65820. }
  65821. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65822. },
  65823. enumerable: true,
  65824. configurable: true
  65825. });
  65826. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65827. /**
  65828. * 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
  65829. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65830. */
  65831. get: function () {
  65832. return this._textures.data[this._currentRenderTextureInd];
  65833. },
  65834. set: function (value) {
  65835. this._forcedOutputTexture = value;
  65836. },
  65837. enumerable: true,
  65838. configurable: true
  65839. });
  65840. /**
  65841. * Gets the camera which post process is applied to.
  65842. * @returns The camera the post process is applied to.
  65843. */
  65844. PostProcess.prototype.getCamera = function () {
  65845. return this._camera;
  65846. };
  65847. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65848. /**
  65849. * Gets the texel size of the postprocess.
  65850. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65851. */
  65852. get: function () {
  65853. if (this._shareOutputWithPostProcess) {
  65854. return this._shareOutputWithPostProcess.texelSize;
  65855. }
  65856. if (this._forcedOutputTexture) {
  65857. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65858. }
  65859. return this._texelSize;
  65860. },
  65861. enumerable: true,
  65862. configurable: true
  65863. });
  65864. /**
  65865. * Gets the engine which this post process belongs to.
  65866. * @returns The engine the post process was enabled with.
  65867. */
  65868. PostProcess.prototype.getEngine = function () {
  65869. return this._engine;
  65870. };
  65871. /**
  65872. * The effect that is created when initializing the post process.
  65873. * @returns The created effect corrisponding the the postprocess.
  65874. */
  65875. PostProcess.prototype.getEffect = function () {
  65876. return this._effect;
  65877. };
  65878. /**
  65879. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65880. * @param postProcess The post process to share the output with.
  65881. * @returns This post process.
  65882. */
  65883. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65884. this._disposeTextures();
  65885. this._shareOutputWithPostProcess = postProcess;
  65886. return this;
  65887. };
  65888. /**
  65889. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65890. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65891. */
  65892. PostProcess.prototype.useOwnOutput = function () {
  65893. if (this._textures.length == 0) {
  65894. this._textures = new BABYLON.SmartArray(2);
  65895. }
  65896. this._shareOutputWithPostProcess = null;
  65897. };
  65898. /**
  65899. * Updates the effect with the current post process compile time values and recompiles the shader.
  65900. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65901. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65902. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65903. * @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
  65904. * @param onCompiled Called when the shader has been compiled.
  65905. * @param onError Called if there is an error when compiling a shader.
  65906. */
  65907. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65908. if (defines === void 0) { defines = null; }
  65909. if (uniforms === void 0) { uniforms = null; }
  65910. if (samplers === void 0) { samplers = null; }
  65911. 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);
  65912. };
  65913. /**
  65914. * The post process is reusable if it can be used multiple times within one frame.
  65915. * @returns If the post process is reusable
  65916. */
  65917. PostProcess.prototype.isReusable = function () {
  65918. return this._reusable;
  65919. };
  65920. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65921. PostProcess.prototype.markTextureDirty = function () {
  65922. this.width = -1;
  65923. };
  65924. /**
  65925. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65926. * 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.
  65927. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65928. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65929. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65930. * @returns The target texture that was bound to be written to.
  65931. */
  65932. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65933. var _this = this;
  65934. if (sourceTexture === void 0) { sourceTexture = null; }
  65935. camera = camera || this._camera;
  65936. var scene = camera.getScene();
  65937. var engine = scene.getEngine();
  65938. var maxSize = engine.getCaps().maxTextureSize;
  65939. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65940. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65941. // 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
  65942. var webVRCamera = camera.parent;
  65943. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65944. requiredWidth /= 2;
  65945. }
  65946. var desiredWidth = (this._options.width || requiredWidth);
  65947. var desiredHeight = this._options.height || requiredHeight;
  65948. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65949. if (this.adaptScaleToCurrentViewport) {
  65950. var currentViewport = engine.currentViewport;
  65951. if (currentViewport) {
  65952. desiredWidth *= currentViewport.width;
  65953. desiredHeight *= currentViewport.height;
  65954. }
  65955. }
  65956. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65957. if (!this._options.width) {
  65958. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65959. }
  65960. if (!this._options.height) {
  65961. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65962. }
  65963. }
  65964. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65965. if (this._textures.length > 0) {
  65966. for (var i = 0; i < this._textures.length; i++) {
  65967. this._engine._releaseTexture(this._textures.data[i]);
  65968. }
  65969. this._textures.reset();
  65970. }
  65971. this.width = desiredWidth;
  65972. this.height = desiredHeight;
  65973. var textureSize = { width: this.width, height: this.height };
  65974. var textureOptions = {
  65975. generateMipMaps: false,
  65976. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65977. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65978. samplingMode: this.renderTargetSamplingMode,
  65979. type: this._textureType
  65980. };
  65981. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65982. if (this._reusable) {
  65983. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65984. }
  65985. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65986. this.onSizeChangedObservable.notifyObservers(this);
  65987. }
  65988. this._textures.forEach(function (texture) {
  65989. if (texture.samples !== _this.samples) {
  65990. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65991. }
  65992. });
  65993. }
  65994. var target;
  65995. if (this._shareOutputWithPostProcess) {
  65996. target = this._shareOutputWithPostProcess.inputTexture;
  65997. }
  65998. else if (this._forcedOutputTexture) {
  65999. target = this._forcedOutputTexture;
  66000. this.width = this._forcedOutputTexture.width;
  66001. this.height = this._forcedOutputTexture.height;
  66002. }
  66003. else {
  66004. target = this.inputTexture;
  66005. }
  66006. // Bind the input of this post process to be used as the output of the previous post process.
  66007. if (this.enablePixelPerfectMode) {
  66008. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  66009. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  66010. }
  66011. else {
  66012. this._scaleRatio.copyFromFloats(1, 1);
  66013. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  66014. }
  66015. this.onActivateObservable.notifyObservers(camera);
  66016. // Clear
  66017. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  66018. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  66019. }
  66020. if (this._reusable) {
  66021. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  66022. }
  66023. return target;
  66024. };
  66025. Object.defineProperty(PostProcess.prototype, "isSupported", {
  66026. /**
  66027. * If the post process is supported.
  66028. */
  66029. get: function () {
  66030. return this._effect.isSupported;
  66031. },
  66032. enumerable: true,
  66033. configurable: true
  66034. });
  66035. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  66036. /**
  66037. * The aspect ratio of the output texture.
  66038. */
  66039. get: function () {
  66040. if (this._shareOutputWithPostProcess) {
  66041. return this._shareOutputWithPostProcess.aspectRatio;
  66042. }
  66043. if (this._forcedOutputTexture) {
  66044. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  66045. }
  66046. return this.width / this.height;
  66047. },
  66048. enumerable: true,
  66049. configurable: true
  66050. });
  66051. /**
  66052. * Get a value indicating if the post-process is ready to be used
  66053. * @returns true if the post-process is ready (shader is compiled)
  66054. */
  66055. PostProcess.prototype.isReady = function () {
  66056. return this._effect && this._effect.isReady();
  66057. };
  66058. /**
  66059. * Binds all textures and uniforms to the shader, this will be run on every pass.
  66060. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  66061. */
  66062. PostProcess.prototype.apply = function () {
  66063. // Check
  66064. if (!this._effect || !this._effect.isReady())
  66065. return null;
  66066. // States
  66067. this._engine.enableEffect(this._effect);
  66068. this._engine.setState(false);
  66069. this._engine.setDepthBuffer(false);
  66070. this._engine.setDepthWrite(false);
  66071. // Alpha
  66072. this._engine.setAlphaMode(this.alphaMode);
  66073. if (this.alphaConstants) {
  66074. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  66075. }
  66076. // Bind the output texture of the preivous post process as the input to this post process.
  66077. var source;
  66078. if (this._shareOutputWithPostProcess) {
  66079. source = this._shareOutputWithPostProcess.inputTexture;
  66080. }
  66081. else if (this._forcedOutputTexture) {
  66082. source = this._forcedOutputTexture;
  66083. }
  66084. else {
  66085. source = this.inputTexture;
  66086. }
  66087. this._effect._bindTexture("textureSampler", source);
  66088. // Parameters
  66089. this._effect.setVector2("scale", this._scaleRatio);
  66090. this.onApplyObservable.notifyObservers(this._effect);
  66091. return this._effect;
  66092. };
  66093. PostProcess.prototype._disposeTextures = function () {
  66094. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  66095. return;
  66096. }
  66097. if (this._textures.length > 0) {
  66098. for (var i = 0; i < this._textures.length; i++) {
  66099. this._engine._releaseTexture(this._textures.data[i]);
  66100. }
  66101. }
  66102. this._textures.dispose();
  66103. };
  66104. /**
  66105. * Disposes the post process.
  66106. * @param camera The camera to dispose the post process on.
  66107. */
  66108. PostProcess.prototype.dispose = function (camera) {
  66109. camera = camera || this._camera;
  66110. this._disposeTextures();
  66111. if (this._scene) {
  66112. var index_1 = this._scene.postProcesses.indexOf(this);
  66113. if (index_1 !== -1) {
  66114. this._scene.postProcesses.splice(index_1, 1);
  66115. }
  66116. }
  66117. else {
  66118. var index_2 = this._engine.postProcesses.indexOf(this);
  66119. if (index_2 !== -1) {
  66120. this._engine.postProcesses.splice(index_2, 1);
  66121. }
  66122. }
  66123. if (!camera) {
  66124. return;
  66125. }
  66126. camera.detachPostProcess(this);
  66127. var index = camera._postProcesses.indexOf(this);
  66128. if (index === 0 && camera._postProcesses.length > 0) {
  66129. var firstPostProcess = this._camera._getFirstPostProcess();
  66130. if (firstPostProcess) {
  66131. firstPostProcess.markTextureDirty();
  66132. }
  66133. }
  66134. this.onActivateObservable.clear();
  66135. this.onAfterRenderObservable.clear();
  66136. this.onApplyObservable.clear();
  66137. this.onBeforeRenderObservable.clear();
  66138. this.onSizeChangedObservable.clear();
  66139. };
  66140. return PostProcess;
  66141. }());
  66142. BABYLON.PostProcess = PostProcess;
  66143. })(BABYLON || (BABYLON = {}));
  66144. //# sourceMappingURL=babylon.postProcess.js.map
  66145. var BABYLON;
  66146. (function (BABYLON) {
  66147. var PassPostProcess = /** @class */ (function (_super) {
  66148. __extends(PassPostProcess, _super);
  66149. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66150. if (camera === void 0) { camera = null; }
  66151. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66152. if (blockCompilation === void 0) { blockCompilation = false; }
  66153. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66154. }
  66155. return PassPostProcess;
  66156. }(BABYLON.PostProcess));
  66157. BABYLON.PassPostProcess = PassPostProcess;
  66158. })(BABYLON || (BABYLON = {}));
  66159. //# sourceMappingURL=babylon.passPostProcess.js.map
  66160. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66161. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66162. s = arguments[i];
  66163. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66164. t[p] = s[p];
  66165. }
  66166. return t;
  66167. };
  66168. var BABYLON;
  66169. (function (BABYLON) {
  66170. /**
  66171. * Default implementation IShadowGenerator.
  66172. * This is the main object responsible of generating shadows in the framework.
  66173. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66174. */
  66175. var ShadowGenerator = /** @class */ (function () {
  66176. /**
  66177. * Creates a ShadowGenerator object.
  66178. * A ShadowGenerator is the required tool to use the shadows.
  66179. * Each light casting shadows needs to use its own ShadowGenerator.
  66180. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66181. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66182. * @param light The light object generating the shadows.
  66183. * @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.
  66184. */
  66185. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66186. this._bias = 0.00005;
  66187. this._normalBias = 0;
  66188. this._blurBoxOffset = 1;
  66189. this._blurScale = 2;
  66190. this._blurKernel = 1;
  66191. this._useKernelBlur = false;
  66192. this._filter = ShadowGenerator.FILTER_NONE;
  66193. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66194. this._contactHardeningLightSizeUVRatio = 0.1;
  66195. this._darkness = 0;
  66196. this._transparencyShadow = false;
  66197. /**
  66198. * Controls the extent to which the shadows fade out at the edge of the frustum
  66199. * Used only by directionals and spots
  66200. */
  66201. this.frustumEdgeFalloff = 0;
  66202. /**
  66203. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66204. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66205. * It might on the other hand introduce peter panning.
  66206. */
  66207. this.forceBackFacesOnly = false;
  66208. this._lightDirection = BABYLON.Vector3.Zero();
  66209. this._viewMatrix = BABYLON.Matrix.Zero();
  66210. this._projectionMatrix = BABYLON.Matrix.Zero();
  66211. this._transformMatrix = BABYLON.Matrix.Zero();
  66212. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66213. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66214. this._currentFaceIndex = 0;
  66215. this._currentFaceIndexCache = 0;
  66216. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66217. this._mapSize = mapSize;
  66218. this._light = light;
  66219. this._scene = light.getScene();
  66220. light._shadowGenerator = this;
  66221. // Texture type fallback from float to int if not supported.
  66222. var caps = this._scene.getEngine().getCaps();
  66223. if (!useFullFloatFirst) {
  66224. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66225. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66226. }
  66227. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66228. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66229. }
  66230. else {
  66231. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66232. }
  66233. }
  66234. else {
  66235. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66236. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66237. }
  66238. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66239. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66240. }
  66241. else {
  66242. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66243. }
  66244. }
  66245. this._initializeGenerator();
  66246. this._applyFilterValues();
  66247. }
  66248. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66249. /**
  66250. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66251. */
  66252. get: function () {
  66253. return this._bias;
  66254. },
  66255. /**
  66256. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66257. */
  66258. set: function (bias) {
  66259. this._bias = bias;
  66260. },
  66261. enumerable: true,
  66262. configurable: true
  66263. });
  66264. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66265. /**
  66266. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66267. */
  66268. get: function () {
  66269. return this._normalBias;
  66270. },
  66271. /**
  66272. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66273. */
  66274. set: function (normalBias) {
  66275. this._normalBias = normalBias;
  66276. },
  66277. enumerable: true,
  66278. configurable: true
  66279. });
  66280. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66281. /**
  66282. * Gets the blur box offset: offset applied during the blur pass.
  66283. * Only usefull if useKernelBlur = false
  66284. */
  66285. get: function () {
  66286. return this._blurBoxOffset;
  66287. },
  66288. /**
  66289. * Sets the blur box offset: offset applied during the blur pass.
  66290. * Only usefull if useKernelBlur = false
  66291. */
  66292. set: function (value) {
  66293. if (this._blurBoxOffset === value) {
  66294. return;
  66295. }
  66296. this._blurBoxOffset = value;
  66297. this._disposeBlurPostProcesses();
  66298. },
  66299. enumerable: true,
  66300. configurable: true
  66301. });
  66302. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66303. /**
  66304. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66305. * 2 means half of the size.
  66306. */
  66307. get: function () {
  66308. return this._blurScale;
  66309. },
  66310. /**
  66311. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66312. * 2 means half of the size.
  66313. */
  66314. set: function (value) {
  66315. if (this._blurScale === value) {
  66316. return;
  66317. }
  66318. this._blurScale = value;
  66319. this._disposeBlurPostProcesses();
  66320. },
  66321. enumerable: true,
  66322. configurable: true
  66323. });
  66324. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66325. /**
  66326. * Gets the blur kernel: kernel size of the blur pass.
  66327. * Only usefull if useKernelBlur = true
  66328. */
  66329. get: function () {
  66330. return this._blurKernel;
  66331. },
  66332. /**
  66333. * Sets the blur kernel: kernel size of the blur pass.
  66334. * Only usefull if useKernelBlur = true
  66335. */
  66336. set: function (value) {
  66337. if (this._blurKernel === value) {
  66338. return;
  66339. }
  66340. this._blurKernel = value;
  66341. this._disposeBlurPostProcesses();
  66342. },
  66343. enumerable: true,
  66344. configurable: true
  66345. });
  66346. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66347. /**
  66348. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66349. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66350. */
  66351. get: function () {
  66352. return this._useKernelBlur;
  66353. },
  66354. /**
  66355. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66356. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66357. */
  66358. set: function (value) {
  66359. if (this._useKernelBlur === value) {
  66360. return;
  66361. }
  66362. this._useKernelBlur = value;
  66363. this._disposeBlurPostProcesses();
  66364. },
  66365. enumerable: true,
  66366. configurable: true
  66367. });
  66368. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66369. /**
  66370. * Gets the depth scale used in ESM mode.
  66371. */
  66372. get: function () {
  66373. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66374. },
  66375. /**
  66376. * Sets the depth scale used in ESM mode.
  66377. * This can override the scale stored on the light.
  66378. */
  66379. set: function (value) {
  66380. this._depthScale = value;
  66381. },
  66382. enumerable: true,
  66383. configurable: true
  66384. });
  66385. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66386. /**
  66387. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66388. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66389. */
  66390. get: function () {
  66391. return this._filter;
  66392. },
  66393. /**
  66394. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66395. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66396. */
  66397. set: function (value) {
  66398. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66399. if (this._light.needCube()) {
  66400. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66401. this.useExponentialShadowMap = true;
  66402. return;
  66403. }
  66404. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66405. this.useCloseExponentialShadowMap = true;
  66406. return;
  66407. }
  66408. // PCF on cubemap would also be expensive
  66409. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66410. this.usePoissonSampling = true;
  66411. return;
  66412. }
  66413. }
  66414. // Weblg1 fallback for PCF.
  66415. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66416. if (this._scene.getEngine().webGLVersion === 1) {
  66417. this.usePoissonSampling = true;
  66418. return;
  66419. }
  66420. }
  66421. if (this._filter === value) {
  66422. return;
  66423. }
  66424. this._filter = value;
  66425. this._disposeBlurPostProcesses();
  66426. this._applyFilterValues();
  66427. this._light._markMeshesAsLightDirty();
  66428. },
  66429. enumerable: true,
  66430. configurable: true
  66431. });
  66432. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66433. /**
  66434. * Gets if the current filter is set to Poisson Sampling.
  66435. */
  66436. get: function () {
  66437. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66438. },
  66439. /**
  66440. * Sets the current filter to Poisson Sampling.
  66441. */
  66442. set: function (value) {
  66443. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66444. return;
  66445. }
  66446. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66447. },
  66448. enumerable: true,
  66449. configurable: true
  66450. });
  66451. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66452. /**
  66453. * Gets if the current filter is set to VSM.
  66454. * DEPRECATED. Should use useExponentialShadowMap instead.
  66455. */
  66456. get: function () {
  66457. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66458. return this.useExponentialShadowMap;
  66459. },
  66460. /**
  66461. * Sets the current filter is to VSM.
  66462. * DEPRECATED. Should use useExponentialShadowMap instead.
  66463. */
  66464. set: function (value) {
  66465. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66466. this.useExponentialShadowMap = value;
  66467. },
  66468. enumerable: true,
  66469. configurable: true
  66470. });
  66471. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66472. /**
  66473. * Gets if the current filter is set to blurred VSM.
  66474. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66475. */
  66476. get: function () {
  66477. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66478. return this.useBlurExponentialShadowMap;
  66479. },
  66480. /**
  66481. * Sets the current filter is to blurred VSM.
  66482. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66483. */
  66484. set: function (value) {
  66485. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66486. this.useBlurExponentialShadowMap = value;
  66487. },
  66488. enumerable: true,
  66489. configurable: true
  66490. });
  66491. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66492. /**
  66493. * Gets if the current filter is set to ESM.
  66494. */
  66495. get: function () {
  66496. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66497. },
  66498. /**
  66499. * Sets the current filter is to ESM.
  66500. */
  66501. set: function (value) {
  66502. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66503. return;
  66504. }
  66505. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66506. },
  66507. enumerable: true,
  66508. configurable: true
  66509. });
  66510. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66511. /**
  66512. * Gets if the current filter is set to filtered ESM.
  66513. */
  66514. get: function () {
  66515. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66516. },
  66517. /**
  66518. * Gets if the current filter is set to filtered ESM.
  66519. */
  66520. set: function (value) {
  66521. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66522. return;
  66523. }
  66524. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66525. },
  66526. enumerable: true,
  66527. configurable: true
  66528. });
  66529. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66530. /**
  66531. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66532. * exponential to prevent steep falloff artifacts).
  66533. */
  66534. get: function () {
  66535. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66536. },
  66537. /**
  66538. * Sets the current filter to "close ESM" (using the inverse of the
  66539. * exponential to prevent steep falloff artifacts).
  66540. */
  66541. set: function (value) {
  66542. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66543. return;
  66544. }
  66545. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66546. },
  66547. enumerable: true,
  66548. configurable: true
  66549. });
  66550. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66551. /**
  66552. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66553. * exponential to prevent steep falloff artifacts).
  66554. */
  66555. get: function () {
  66556. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66557. },
  66558. /**
  66559. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66560. * exponential to prevent steep falloff artifacts).
  66561. */
  66562. set: function (value) {
  66563. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66564. return;
  66565. }
  66566. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66567. },
  66568. enumerable: true,
  66569. configurable: true
  66570. });
  66571. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66572. /**
  66573. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66574. */
  66575. get: function () {
  66576. return this.filter === ShadowGenerator.FILTER_PCF;
  66577. },
  66578. /**
  66579. * Sets the current filter to "PCF" (percentage closer filtering).
  66580. */
  66581. set: function (value) {
  66582. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66583. return;
  66584. }
  66585. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66586. },
  66587. enumerable: true,
  66588. configurable: true
  66589. });
  66590. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66591. /**
  66592. * Gets the PCF or PCSS Quality.
  66593. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66594. */
  66595. get: function () {
  66596. return this._filteringQuality;
  66597. },
  66598. /**
  66599. * Sets the PCF or PCSS Quality.
  66600. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66601. */
  66602. set: function (filteringQuality) {
  66603. this._filteringQuality = filteringQuality;
  66604. },
  66605. enumerable: true,
  66606. configurable: true
  66607. });
  66608. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66609. /**
  66610. * Gets if the current filter is set to "PCSS" (contact hardening).
  66611. */
  66612. get: function () {
  66613. return this.filter === ShadowGenerator.FILTER_PCSS;
  66614. },
  66615. /**
  66616. * Sets the current filter to "PCSS" (contact hardening).
  66617. */
  66618. set: function (value) {
  66619. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66620. return;
  66621. }
  66622. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66623. },
  66624. enumerable: true,
  66625. configurable: true
  66626. });
  66627. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66628. /**
  66629. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66630. * Using a ratio helps keeping shape stability independently of the map size.
  66631. *
  66632. * It does not account for the light projection as it was having too much
  66633. * instability during the light setup or during light position changes.
  66634. *
  66635. * Only valid if useContactHardeningShadow is true.
  66636. */
  66637. get: function () {
  66638. return this._contactHardeningLightSizeUVRatio;
  66639. },
  66640. /**
  66641. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66642. * Using a ratio helps keeping shape stability independently of the map size.
  66643. *
  66644. * It does not account for the light projection as it was having too much
  66645. * instability during the light setup or during light position changes.
  66646. *
  66647. * Only valid if useContactHardeningShadow is true.
  66648. */
  66649. set: function (contactHardeningLightSizeUVRatio) {
  66650. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66651. },
  66652. enumerable: true,
  66653. configurable: true
  66654. });
  66655. /**
  66656. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66657. * 0 means strongest and 1 would means no shadow.
  66658. * @returns the darkness.
  66659. */
  66660. ShadowGenerator.prototype.getDarkness = function () {
  66661. return this._darkness;
  66662. };
  66663. /**
  66664. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66665. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66666. * @returns the shadow generator allowing fluent coding.
  66667. */
  66668. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66669. if (darkness >= 1.0)
  66670. this._darkness = 1.0;
  66671. else if (darkness <= 0.0)
  66672. this._darkness = 0.0;
  66673. else
  66674. this._darkness = darkness;
  66675. return this;
  66676. };
  66677. /**
  66678. * Sets the ability to have transparent shadow (boolean).
  66679. * @param transparent True if transparent else False
  66680. * @returns the shadow generator allowing fluent coding
  66681. */
  66682. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66683. this._transparencyShadow = transparent;
  66684. return this;
  66685. };
  66686. /**
  66687. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66688. * @returns The render target texture if present otherwise, null
  66689. */
  66690. ShadowGenerator.prototype.getShadowMap = function () {
  66691. return this._shadowMap;
  66692. };
  66693. /**
  66694. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66695. * @returns The render target texture if the shadow map is present otherwise, null
  66696. */
  66697. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66698. if (this._shadowMap2) {
  66699. return this._shadowMap2;
  66700. }
  66701. return this._shadowMap;
  66702. };
  66703. /**
  66704. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66705. * @param mesh Mesh to add
  66706. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66707. * @returns the Shadow Generator itself
  66708. */
  66709. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66710. if (includeDescendants === void 0) { includeDescendants = true; }
  66711. if (!this._shadowMap) {
  66712. return this;
  66713. }
  66714. if (!this._shadowMap.renderList) {
  66715. this._shadowMap.renderList = [];
  66716. }
  66717. this._shadowMap.renderList.push(mesh);
  66718. if (includeDescendants) {
  66719. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66720. }
  66721. return this;
  66722. var _a;
  66723. };
  66724. /**
  66725. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66726. * @param mesh Mesh to remove
  66727. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66728. * @returns the Shadow Generator itself
  66729. */
  66730. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66731. if (includeDescendants === void 0) { includeDescendants = true; }
  66732. if (!this._shadowMap || !this._shadowMap.renderList) {
  66733. return this;
  66734. }
  66735. var index = this._shadowMap.renderList.indexOf(mesh);
  66736. if (index !== -1) {
  66737. this._shadowMap.renderList.splice(index, 1);
  66738. }
  66739. if (includeDescendants) {
  66740. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66741. var child = _a[_i];
  66742. this.removeShadowCaster(child);
  66743. }
  66744. }
  66745. return this;
  66746. };
  66747. /**
  66748. * Returns the associated light object.
  66749. * @returns the light generating the shadow
  66750. */
  66751. ShadowGenerator.prototype.getLight = function () {
  66752. return this._light;
  66753. };
  66754. ShadowGenerator.prototype._initializeGenerator = function () {
  66755. this._light._markMeshesAsLightDirty();
  66756. this._initializeShadowMap();
  66757. };
  66758. ShadowGenerator.prototype._initializeShadowMap = function () {
  66759. var _this = this;
  66760. // Render target
  66761. var engine = this._scene.getEngine();
  66762. if (engine.webGLVersion > 1) {
  66763. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66764. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66765. }
  66766. else {
  66767. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66768. }
  66769. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66770. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66771. this._shadowMap.anisotropicFilteringLevel = 1;
  66772. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66773. this._shadowMap.renderParticles = false;
  66774. this._shadowMap.ignoreCameraViewport = true;
  66775. // Record Face Index before render.
  66776. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66777. _this._currentFaceIndex = faceIndex;
  66778. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66779. engine.setColorWrite(false);
  66780. }
  66781. });
  66782. // Custom render function.
  66783. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66784. // Blur if required afer render.
  66785. this._shadowMap.onAfterUnbindObservable.add(function () {
  66786. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66787. engine.setColorWrite(true);
  66788. }
  66789. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66790. return;
  66791. }
  66792. var shadowMap = _this.getShadowMapForRendering();
  66793. if (shadowMap) {
  66794. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66795. }
  66796. });
  66797. // Clear according to the chosen filter.
  66798. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66799. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66800. this._shadowMap.onClearObservable.add(function (engine) {
  66801. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66802. engine.clear(clearOne, false, true, false);
  66803. }
  66804. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66805. engine.clear(clearZero, true, true, false);
  66806. }
  66807. else {
  66808. engine.clear(clearOne, true, true, false);
  66809. }
  66810. });
  66811. };
  66812. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66813. var _this = this;
  66814. var engine = this._scene.getEngine();
  66815. var targetSize = this._mapSize / this.blurScale;
  66816. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66817. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66818. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66819. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66820. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66821. }
  66822. if (this.useKernelBlur) {
  66823. 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);
  66824. this._kernelBlurXPostprocess.width = targetSize;
  66825. this._kernelBlurXPostprocess.height = targetSize;
  66826. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66827. effect.setTexture("textureSampler", _this._shadowMap);
  66828. });
  66829. 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);
  66830. this._kernelBlurXPostprocess.autoClear = false;
  66831. this._kernelBlurYPostprocess.autoClear = false;
  66832. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66833. this._kernelBlurXPostprocess.packedFloat = true;
  66834. this._kernelBlurYPostprocess.packedFloat = true;
  66835. }
  66836. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66837. }
  66838. else {
  66839. 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);
  66840. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66841. effect.setFloat2("screenSize", targetSize, targetSize);
  66842. effect.setTexture("textureSampler", _this._shadowMap);
  66843. });
  66844. this._boxBlurPostprocess.autoClear = false;
  66845. this._blurPostProcesses = [this._boxBlurPostprocess];
  66846. }
  66847. };
  66848. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66849. var index;
  66850. var engine = this._scene.getEngine();
  66851. if (depthOnlySubMeshes.length) {
  66852. engine.setColorWrite(false);
  66853. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66854. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66855. }
  66856. engine.setColorWrite(true);
  66857. }
  66858. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66859. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66860. }
  66861. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66862. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66863. }
  66864. if (this._transparencyShadow) {
  66865. for (index = 0; index < transparentSubMeshes.length; index++) {
  66866. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66867. }
  66868. }
  66869. };
  66870. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66871. var _this = this;
  66872. var mesh = subMesh.getRenderingMesh();
  66873. var scene = this._scene;
  66874. var engine = scene.getEngine();
  66875. var material = subMesh.getMaterial();
  66876. if (!material) {
  66877. return;
  66878. }
  66879. // Culling
  66880. engine.setState(material.backFaceCulling);
  66881. // Managing instances
  66882. var batch = mesh._getInstancesRenderList(subMesh._id);
  66883. if (batch.mustReturn) {
  66884. return;
  66885. }
  66886. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66887. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66888. engine.enableEffect(this._effect);
  66889. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66890. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66891. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66892. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66893. this._effect.setVector3("lightData", this._cachedDirection);
  66894. }
  66895. else {
  66896. this._effect.setVector3("lightData", this._cachedPosition);
  66897. }
  66898. if (scene.activeCamera) {
  66899. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66900. }
  66901. // Alpha test
  66902. if (material && material.needAlphaTesting()) {
  66903. var alphaTexture = material.getAlphaTestTexture();
  66904. if (alphaTexture) {
  66905. this._effect.setTexture("diffuseSampler", alphaTexture);
  66906. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66907. }
  66908. }
  66909. // Bones
  66910. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66911. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66912. }
  66913. // Morph targets
  66914. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66915. if (this.forceBackFacesOnly) {
  66916. engine.setState(true, 0, false, true);
  66917. }
  66918. // Draw
  66919. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66920. if (this.forceBackFacesOnly) {
  66921. engine.setState(true, 0, false, false);
  66922. }
  66923. }
  66924. else {
  66925. // Need to reset refresh rate of the shadowMap
  66926. if (this._shadowMap) {
  66927. this._shadowMap.resetRefreshCounter();
  66928. }
  66929. }
  66930. };
  66931. ShadowGenerator.prototype._applyFilterValues = function () {
  66932. if (!this._shadowMap) {
  66933. return;
  66934. }
  66935. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66936. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66937. }
  66938. else {
  66939. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66940. }
  66941. };
  66942. /**
  66943. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66944. * @param onCompiled Callback triggered at the and of the effects compilation
  66945. * @param options Sets of optional options forcing the compilation with different modes
  66946. */
  66947. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66948. var _this = this;
  66949. var localOptions = __assign({ useInstances: false }, options);
  66950. var shadowMap = this.getShadowMap();
  66951. if (!shadowMap) {
  66952. if (onCompiled) {
  66953. onCompiled(this);
  66954. }
  66955. return;
  66956. }
  66957. var renderList = shadowMap.renderList;
  66958. if (!renderList) {
  66959. if (onCompiled) {
  66960. onCompiled(this);
  66961. }
  66962. return;
  66963. }
  66964. var subMeshes = new Array();
  66965. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66966. var mesh = renderList_1[_i];
  66967. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66968. }
  66969. if (subMeshes.length === 0) {
  66970. if (onCompiled) {
  66971. onCompiled(this);
  66972. }
  66973. return;
  66974. }
  66975. var currentIndex = 0;
  66976. var checkReady = function () {
  66977. if (!_this._scene || !_this._scene.getEngine()) {
  66978. return;
  66979. }
  66980. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66981. currentIndex++;
  66982. if (currentIndex >= subMeshes.length) {
  66983. if (onCompiled) {
  66984. onCompiled(_this);
  66985. }
  66986. return;
  66987. }
  66988. }
  66989. setTimeout(checkReady, 16);
  66990. };
  66991. checkReady();
  66992. };
  66993. /**
  66994. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66995. * @param options Sets of optional options forcing the compilation with different modes
  66996. * @returns A promise that resolves when the compilation completes
  66997. */
  66998. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66999. var _this = this;
  67000. return new Promise(function (resolve) {
  67001. _this.forceCompilation(function () {
  67002. resolve();
  67003. }, options);
  67004. });
  67005. };
  67006. /**
  67007. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  67008. * @param subMesh The submesh we want to render in the shadow map
  67009. * @param useInstances Defines wether will draw in the map using instances
  67010. * @returns true if ready otherwise, false
  67011. */
  67012. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  67013. var defines = [];
  67014. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67015. defines.push("#define FLOAT");
  67016. }
  67017. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67018. defines.push("#define ESM");
  67019. }
  67020. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  67021. defines.push("#define DEPTHTEXTURE");
  67022. }
  67023. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67024. var mesh = subMesh.getMesh();
  67025. var material = subMesh.getMaterial();
  67026. // Normal bias.
  67027. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  67028. attribs.push(BABYLON.VertexBuffer.NormalKind);
  67029. defines.push("#define NORMAL");
  67030. if (mesh.nonUniformScaling) {
  67031. defines.push("#define NONUNIFORMSCALING");
  67032. }
  67033. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  67034. defines.push("#define DIRECTIONINLIGHTDATA");
  67035. }
  67036. }
  67037. // Alpha test
  67038. if (material && material.needAlphaTesting()) {
  67039. var alphaTexture = material.getAlphaTestTexture();
  67040. if (alphaTexture) {
  67041. defines.push("#define ALPHATEST");
  67042. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67043. attribs.push(BABYLON.VertexBuffer.UVKind);
  67044. defines.push("#define UV1");
  67045. }
  67046. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67047. if (alphaTexture.coordinatesIndex === 1) {
  67048. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67049. defines.push("#define UV2");
  67050. }
  67051. }
  67052. }
  67053. }
  67054. // Bones
  67055. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67056. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67057. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67058. if (mesh.numBoneInfluencers > 4) {
  67059. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67060. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67061. }
  67062. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67063. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67064. }
  67065. else {
  67066. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67067. }
  67068. // Morph targets
  67069. var manager = mesh.morphTargetManager;
  67070. var morphInfluencers = 0;
  67071. if (manager) {
  67072. if (manager.numInfluencers > 0) {
  67073. defines.push("#define MORPHTARGETS");
  67074. morphInfluencers = manager.numInfluencers;
  67075. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  67076. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  67077. }
  67078. }
  67079. // Instances
  67080. if (useInstances) {
  67081. defines.push("#define INSTANCES");
  67082. attribs.push("world0");
  67083. attribs.push("world1");
  67084. attribs.push("world2");
  67085. attribs.push("world3");
  67086. }
  67087. // Get correct effect
  67088. var join = defines.join("\n");
  67089. if (this._cachedDefines !== join) {
  67090. this._cachedDefines = join;
  67091. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  67092. }
  67093. if (!this._effect.isReady()) {
  67094. return false;
  67095. }
  67096. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67097. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  67098. this._initializeBlurRTTAndPostProcesses();
  67099. }
  67100. }
  67101. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  67102. return false;
  67103. }
  67104. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  67105. return false;
  67106. }
  67107. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  67108. return false;
  67109. }
  67110. return true;
  67111. };
  67112. /**
  67113. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67114. * @param defines Defines of the material we want to update
  67115. * @param lightIndex Index of the light in the enabled light list of the material
  67116. */
  67117. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67118. var scene = this._scene;
  67119. var light = this._light;
  67120. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67121. return;
  67122. }
  67123. defines["SHADOW" + lightIndex] = true;
  67124. if (this.useContactHardeningShadow) {
  67125. defines["SHADOWPCSS" + lightIndex] = true;
  67126. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67127. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67128. }
  67129. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67130. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67131. }
  67132. // else default to high.
  67133. }
  67134. if (this.usePercentageCloserFiltering) {
  67135. defines["SHADOWPCF" + lightIndex] = true;
  67136. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67137. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67138. }
  67139. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67140. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67141. }
  67142. // else default to high.
  67143. }
  67144. else if (this.usePoissonSampling) {
  67145. defines["SHADOWPOISSON" + lightIndex] = true;
  67146. }
  67147. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67148. defines["SHADOWESM" + lightIndex] = true;
  67149. }
  67150. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67151. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67152. }
  67153. if (light.needCube()) {
  67154. defines["SHADOWCUBE" + lightIndex] = true;
  67155. }
  67156. };
  67157. /**
  67158. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67159. * defined in the generator but impacting the effect).
  67160. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67161. * @param effect The effect we are binfing the information for
  67162. */
  67163. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67164. var light = this._light;
  67165. var scene = this._scene;
  67166. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67167. return;
  67168. }
  67169. var camera = scene.activeCamera;
  67170. if (!camera) {
  67171. return;
  67172. }
  67173. var shadowMap = this.getShadowMap();
  67174. if (!shadowMap) {
  67175. return;
  67176. }
  67177. if (!light.needCube()) {
  67178. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67179. }
  67180. // Only PCF uses depth stencil texture.
  67181. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67182. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67183. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67184. }
  67185. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67186. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67187. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67188. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67189. }
  67190. else {
  67191. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67192. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67193. }
  67194. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67195. };
  67196. /**
  67197. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67198. * (eq to shadow prjection matrix * light transform matrix)
  67199. * @returns The transform matrix used to create the shadow map
  67200. */
  67201. ShadowGenerator.prototype.getTransformMatrix = function () {
  67202. var scene = this._scene;
  67203. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67204. return this._transformMatrix;
  67205. }
  67206. this._currentRenderID = scene.getRenderId();
  67207. this._currentFaceIndexCache = this._currentFaceIndex;
  67208. var lightPosition = this._light.position;
  67209. if (this._light.computeTransformedInformation()) {
  67210. lightPosition = this._light.transformedPosition;
  67211. }
  67212. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67213. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67214. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67215. }
  67216. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67217. this._cachedPosition.copyFrom(lightPosition);
  67218. this._cachedDirection.copyFrom(this._lightDirection);
  67219. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67220. var shadowMap = this.getShadowMap();
  67221. if (shadowMap) {
  67222. var renderList = shadowMap.renderList;
  67223. if (renderList) {
  67224. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67225. }
  67226. }
  67227. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67228. }
  67229. return this._transformMatrix;
  67230. };
  67231. /**
  67232. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67233. * Cube and 2D textures for instance.
  67234. */
  67235. ShadowGenerator.prototype.recreateShadowMap = function () {
  67236. var shadowMap = this._shadowMap;
  67237. if (!shadowMap) {
  67238. return;
  67239. }
  67240. // Track render list.
  67241. var renderList = shadowMap.renderList;
  67242. // Clean up existing data.
  67243. this._disposeRTTandPostProcesses();
  67244. // Reinitializes.
  67245. this._initializeGenerator();
  67246. // Reaffect the filter to ensure a correct fallback if necessary.
  67247. this.filter = this.filter;
  67248. // Reaffect the filter.
  67249. this._applyFilterValues();
  67250. // Reaffect Render List.
  67251. this._shadowMap.renderList = renderList;
  67252. };
  67253. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67254. if (this._shadowMap2) {
  67255. this._shadowMap2.dispose();
  67256. this._shadowMap2 = null;
  67257. }
  67258. if (this._boxBlurPostprocess) {
  67259. this._boxBlurPostprocess.dispose();
  67260. this._boxBlurPostprocess = null;
  67261. }
  67262. if (this._kernelBlurXPostprocess) {
  67263. this._kernelBlurXPostprocess.dispose();
  67264. this._kernelBlurXPostprocess = null;
  67265. }
  67266. if (this._kernelBlurYPostprocess) {
  67267. this._kernelBlurYPostprocess.dispose();
  67268. this._kernelBlurYPostprocess = null;
  67269. }
  67270. this._blurPostProcesses = [];
  67271. };
  67272. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67273. if (this._shadowMap) {
  67274. this._shadowMap.dispose();
  67275. this._shadowMap = null;
  67276. }
  67277. this._disposeBlurPostProcesses();
  67278. };
  67279. /**
  67280. * Disposes the ShadowGenerator.
  67281. * Returns nothing.
  67282. */
  67283. ShadowGenerator.prototype.dispose = function () {
  67284. this._disposeRTTandPostProcesses();
  67285. if (this._light) {
  67286. this._light._shadowGenerator = null;
  67287. this._light._markMeshesAsLightDirty();
  67288. }
  67289. };
  67290. /**
  67291. * Serializes the shadow generator setup to a json object.
  67292. * @returns The serialized JSON object
  67293. */
  67294. ShadowGenerator.prototype.serialize = function () {
  67295. var serializationObject = {};
  67296. var shadowMap = this.getShadowMap();
  67297. if (!shadowMap) {
  67298. return serializationObject;
  67299. }
  67300. serializationObject.lightId = this._light.id;
  67301. serializationObject.mapSize = shadowMap.getRenderSize();
  67302. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67303. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67304. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67305. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67306. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67307. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67308. serializationObject.depthScale = this.depthScale;
  67309. serializationObject.darkness = this.getDarkness();
  67310. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67311. serializationObject.blurKernel = this.blurKernel;
  67312. serializationObject.blurScale = this.blurScale;
  67313. serializationObject.useKernelBlur = this.useKernelBlur;
  67314. serializationObject.transparencyShadow = this._transparencyShadow;
  67315. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67316. serializationObject.bias = this.bias;
  67317. serializationObject.normalBias = this.normalBias;
  67318. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67319. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67320. serializationObject.filteringQuality = this.filteringQuality;
  67321. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67322. serializationObject.renderList = [];
  67323. if (shadowMap.renderList) {
  67324. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67325. var mesh = shadowMap.renderList[meshIndex];
  67326. serializationObject.renderList.push(mesh.id);
  67327. }
  67328. }
  67329. return serializationObject;
  67330. };
  67331. /**
  67332. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67333. * @param parsedShadowGenerator The JSON object to parse
  67334. * @param scene The scene to create the shadow map for
  67335. * @returns The parsed shadow generator
  67336. */
  67337. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67338. //casting to point light, as light is missing the position attr and typescript complains.
  67339. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67340. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67341. var shadowMap = shadowGenerator.getShadowMap();
  67342. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67343. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67344. meshes.forEach(function (mesh) {
  67345. if (!shadowMap) {
  67346. return;
  67347. }
  67348. if (!shadowMap.renderList) {
  67349. shadowMap.renderList = [];
  67350. }
  67351. shadowMap.renderList.push(mesh);
  67352. });
  67353. }
  67354. if (parsedShadowGenerator.usePoissonSampling) {
  67355. shadowGenerator.usePoissonSampling = true;
  67356. }
  67357. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67358. shadowGenerator.useExponentialShadowMap = true;
  67359. }
  67360. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67361. shadowGenerator.useBlurExponentialShadowMap = true;
  67362. }
  67363. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67364. shadowGenerator.useCloseExponentialShadowMap = true;
  67365. }
  67366. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67367. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67368. }
  67369. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67370. shadowGenerator.usePercentageCloserFiltering = true;
  67371. }
  67372. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67373. shadowGenerator.useContactHardeningShadow = true;
  67374. }
  67375. if (parsedShadowGenerator.filteringQuality) {
  67376. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67377. }
  67378. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67379. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67380. }
  67381. // Backward compat
  67382. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67383. shadowGenerator.useExponentialShadowMap = true;
  67384. }
  67385. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67386. shadowGenerator.useBlurExponentialShadowMap = true;
  67387. }
  67388. if (parsedShadowGenerator.depthScale) {
  67389. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67390. }
  67391. if (parsedShadowGenerator.blurScale) {
  67392. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67393. }
  67394. if (parsedShadowGenerator.blurBoxOffset) {
  67395. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67396. }
  67397. if (parsedShadowGenerator.useKernelBlur) {
  67398. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67399. }
  67400. if (parsedShadowGenerator.blurKernel) {
  67401. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67402. }
  67403. if (parsedShadowGenerator.bias !== undefined) {
  67404. shadowGenerator.bias = parsedShadowGenerator.bias;
  67405. }
  67406. if (parsedShadowGenerator.normalBias !== undefined) {
  67407. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67408. }
  67409. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67410. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67411. }
  67412. if (parsedShadowGenerator.darkness) {
  67413. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67414. }
  67415. if (parsedShadowGenerator.transparencyShadow) {
  67416. shadowGenerator.setTransparencyShadow(true);
  67417. }
  67418. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67419. return shadowGenerator;
  67420. };
  67421. /**
  67422. * Shadow generator mode None: no filtering applied.
  67423. */
  67424. ShadowGenerator.FILTER_NONE = 0;
  67425. /**
  67426. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67427. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67428. */
  67429. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67430. /**
  67431. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67432. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67433. */
  67434. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67435. /**
  67436. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67437. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67438. */
  67439. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67440. /**
  67441. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67442. * edge artifacts on steep falloff.
  67443. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67444. */
  67445. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67446. /**
  67447. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67448. * edge artifacts on steep falloff.
  67449. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67450. */
  67451. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67452. /**
  67453. * Shadow generator mode PCF: Percentage Closer Filtering
  67454. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67455. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67456. */
  67457. ShadowGenerator.FILTER_PCF = 6;
  67458. /**
  67459. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67460. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67461. * Contact Hardening
  67462. */
  67463. ShadowGenerator.FILTER_PCSS = 7;
  67464. /**
  67465. * Reserved for PCF and PCSS
  67466. * Highest Quality.
  67467. *
  67468. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67469. *
  67470. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67471. */
  67472. ShadowGenerator.QUALITY_HIGH = 0;
  67473. /**
  67474. * Reserved for PCF and PCSS
  67475. * Good tradeoff for quality/perf cross devices
  67476. *
  67477. * Execute PCF on a 3*3 kernel.
  67478. *
  67479. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67480. */
  67481. ShadowGenerator.QUALITY_MEDIUM = 1;
  67482. /**
  67483. * Reserved for PCF and PCSS
  67484. * The lowest quality but the fastest.
  67485. *
  67486. * Execute PCF on a 1*1 kernel.
  67487. *
  67488. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67489. */
  67490. ShadowGenerator.QUALITY_LOW = 2;
  67491. return ShadowGenerator;
  67492. }());
  67493. BABYLON.ShadowGenerator = ShadowGenerator;
  67494. })(BABYLON || (BABYLON = {}));
  67495. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67496. var BABYLON;
  67497. (function (BABYLON) {
  67498. var DefaultLoadingScreen = /** @class */ (function () {
  67499. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67500. if (_loadingText === void 0) { _loadingText = ""; }
  67501. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67502. var _this = this;
  67503. this._renderingCanvas = _renderingCanvas;
  67504. this._loadingText = _loadingText;
  67505. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67506. // Resize
  67507. this._resizeLoadingUI = function () {
  67508. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67509. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67510. if (!_this._loadingDiv) {
  67511. return;
  67512. }
  67513. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67514. _this._loadingDiv.style.left = canvasRect.left + "px";
  67515. _this._loadingDiv.style.top = canvasRect.top + "px";
  67516. _this._loadingDiv.style.width = canvasRect.width + "px";
  67517. _this._loadingDiv.style.height = canvasRect.height + "px";
  67518. };
  67519. }
  67520. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67521. if (this._loadingDiv) {
  67522. // Do not add a loading screen if there is already one
  67523. return;
  67524. }
  67525. this._loadingDiv = document.createElement("div");
  67526. this._loadingDiv.id = "babylonjsLoadingDiv";
  67527. this._loadingDiv.style.opacity = "0";
  67528. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67529. this._loadingDiv.style.pointerEvents = "none";
  67530. // Loading text
  67531. this._loadingTextDiv = document.createElement("div");
  67532. this._loadingTextDiv.style.position = "absolute";
  67533. this._loadingTextDiv.style.left = "0";
  67534. this._loadingTextDiv.style.top = "50%";
  67535. this._loadingTextDiv.style.marginTop = "80px";
  67536. this._loadingTextDiv.style.width = "100%";
  67537. this._loadingTextDiv.style.height = "20px";
  67538. this._loadingTextDiv.style.fontFamily = "Arial";
  67539. this._loadingTextDiv.style.fontSize = "14px";
  67540. this._loadingTextDiv.style.color = "white";
  67541. this._loadingTextDiv.style.textAlign = "center";
  67542. this._loadingTextDiv.innerHTML = "Loading";
  67543. this._loadingDiv.appendChild(this._loadingTextDiv);
  67544. //set the predefined text
  67545. this._loadingTextDiv.innerHTML = this._loadingText;
  67546. // Generating keyframes
  67547. var style = document.createElement('style');
  67548. style.type = 'text/css';
  67549. 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 }";
  67550. style.innerHTML = keyFrames;
  67551. document.getElementsByTagName('head')[0].appendChild(style);
  67552. // Loading img
  67553. var imgBack = new Image();
  67554. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN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OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  67555. imgBack.style.position = "absolute";
  67556. imgBack.style.left = "50%";
  67557. imgBack.style.top = "50%";
  67558. imgBack.style.marginLeft = "-60px";
  67559. imgBack.style.marginTop = "-60px";
  67560. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67561. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67562. imgBack.style.transformOrigin = "50% 50%";
  67563. imgBack.style.webkitTransformOrigin = "50% 50%";
  67564. this._loadingDiv.appendChild(imgBack);
  67565. this._resizeLoadingUI();
  67566. window.addEventListener("resize", this._resizeLoadingUI);
  67567. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67568. document.body.appendChild(this._loadingDiv);
  67569. this._loadingDiv.style.opacity = "1";
  67570. };
  67571. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67572. var _this = this;
  67573. if (!this._loadingDiv) {
  67574. return;
  67575. }
  67576. var onTransitionEnd = function () {
  67577. if (!_this._loadingDiv) {
  67578. return;
  67579. }
  67580. document.body.removeChild(_this._loadingDiv);
  67581. window.removeEventListener("resize", _this._resizeLoadingUI);
  67582. _this._loadingDiv = null;
  67583. };
  67584. this._loadingDiv.style.opacity = "0";
  67585. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67586. };
  67587. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67588. set: function (text) {
  67589. this._loadingText = text;
  67590. if (this._loadingTextDiv) {
  67591. this._loadingTextDiv.innerHTML = this._loadingText;
  67592. }
  67593. },
  67594. enumerable: true,
  67595. configurable: true
  67596. });
  67597. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67598. get: function () {
  67599. return this._loadingDivBackgroundColor;
  67600. },
  67601. set: function (color) {
  67602. this._loadingDivBackgroundColor = color;
  67603. if (!this._loadingDiv) {
  67604. return;
  67605. }
  67606. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67607. },
  67608. enumerable: true,
  67609. configurable: true
  67610. });
  67611. return DefaultLoadingScreen;
  67612. }());
  67613. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67614. })(BABYLON || (BABYLON = {}));
  67615. //# sourceMappingURL=babylon.loadingScreen.js.map
  67616. var BABYLON;
  67617. (function (BABYLON) {
  67618. var SceneLoaderProgressEvent = /** @class */ (function () {
  67619. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67620. this.lengthComputable = lengthComputable;
  67621. this.loaded = loaded;
  67622. this.total = total;
  67623. }
  67624. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67625. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67626. };
  67627. return SceneLoaderProgressEvent;
  67628. }());
  67629. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67630. var SceneLoader = /** @class */ (function () {
  67631. function SceneLoader() {
  67632. }
  67633. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67634. get: function () {
  67635. return 0;
  67636. },
  67637. enumerable: true,
  67638. configurable: true
  67639. });
  67640. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67641. get: function () {
  67642. return 1;
  67643. },
  67644. enumerable: true,
  67645. configurable: true
  67646. });
  67647. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67648. get: function () {
  67649. return 2;
  67650. },
  67651. enumerable: true,
  67652. configurable: true
  67653. });
  67654. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67655. get: function () {
  67656. return 3;
  67657. },
  67658. enumerable: true,
  67659. configurable: true
  67660. });
  67661. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67662. get: function () {
  67663. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67664. },
  67665. set: function (value) {
  67666. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67667. },
  67668. enumerable: true,
  67669. configurable: true
  67670. });
  67671. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67672. get: function () {
  67673. return SceneLoader._ShowLoadingScreen;
  67674. },
  67675. set: function (value) {
  67676. SceneLoader._ShowLoadingScreen = value;
  67677. },
  67678. enumerable: true,
  67679. configurable: true
  67680. });
  67681. Object.defineProperty(SceneLoader, "loggingLevel", {
  67682. get: function () {
  67683. return SceneLoader._loggingLevel;
  67684. },
  67685. set: function (value) {
  67686. SceneLoader._loggingLevel = value;
  67687. },
  67688. enumerable: true,
  67689. configurable: true
  67690. });
  67691. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67692. get: function () {
  67693. return SceneLoader._CleanBoneMatrixWeights;
  67694. },
  67695. set: function (value) {
  67696. SceneLoader._CleanBoneMatrixWeights = value;
  67697. },
  67698. enumerable: true,
  67699. configurable: true
  67700. });
  67701. SceneLoader._getDefaultPlugin = function () {
  67702. return SceneLoader._registeredPlugins[".babylon"];
  67703. };
  67704. SceneLoader._getPluginForExtension = function (extension) {
  67705. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67706. if (registeredPlugin) {
  67707. return registeredPlugin;
  67708. }
  67709. 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");
  67710. return SceneLoader._getDefaultPlugin();
  67711. };
  67712. SceneLoader._getPluginForDirectLoad = function (data) {
  67713. for (var extension in SceneLoader._registeredPlugins) {
  67714. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67715. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67716. return SceneLoader._registeredPlugins[extension];
  67717. }
  67718. }
  67719. return SceneLoader._getDefaultPlugin();
  67720. };
  67721. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67722. if (sceneFilename.name) {
  67723. sceneFilename = sceneFilename.name;
  67724. }
  67725. var queryStringPosition = sceneFilename.indexOf("?");
  67726. if (queryStringPosition !== -1) {
  67727. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67728. }
  67729. var dotPosition = sceneFilename.lastIndexOf(".");
  67730. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67731. return SceneLoader._getPluginForExtension(extension);
  67732. };
  67733. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67734. SceneLoader._getDirectLoad = function (sceneFilename) {
  67735. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67736. return sceneFilename.substr(5);
  67737. }
  67738. return null;
  67739. };
  67740. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67741. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67742. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67743. var plugin;
  67744. if (registeredPlugin.plugin.createPlugin) {
  67745. plugin = registeredPlugin.plugin.createPlugin();
  67746. }
  67747. else {
  67748. plugin = registeredPlugin.plugin;
  67749. }
  67750. var useArrayBuffer = registeredPlugin.isBinary;
  67751. var database;
  67752. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67753. var dataCallback = function (data, responseURL) {
  67754. if (scene.isDisposed) {
  67755. onError("Scene has been disposed");
  67756. return;
  67757. }
  67758. scene.database = database;
  67759. onSuccess(plugin, data, responseURL);
  67760. };
  67761. var request = null;
  67762. var pluginDisposed = false;
  67763. var onDisposeObservable = plugin.onDisposeObservable;
  67764. if (onDisposeObservable) {
  67765. onDisposeObservable.add(function () {
  67766. pluginDisposed = true;
  67767. if (request) {
  67768. request.abort();
  67769. request = null;
  67770. }
  67771. onDispose();
  67772. });
  67773. }
  67774. var manifestChecked = function () {
  67775. if (pluginDisposed) {
  67776. return;
  67777. }
  67778. var url = rootUrl + sceneFilename;
  67779. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67780. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67781. } : undefined, database, useArrayBuffer, function (request, exception) {
  67782. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67783. });
  67784. };
  67785. if (directLoad) {
  67786. dataCallback(directLoad);
  67787. return plugin;
  67788. }
  67789. if (rootUrl.indexOf("file:") === -1) {
  67790. var engine = scene.getEngine();
  67791. var canUseOfflineSupport = engine.enableOfflineSupport;
  67792. if (canUseOfflineSupport) {
  67793. // Also check for exceptions
  67794. var exceptionFound = false;
  67795. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67796. var regex = _a[_i];
  67797. if (regex.test(rootUrl + sceneFilename)) {
  67798. exceptionFound = true;
  67799. break;
  67800. }
  67801. }
  67802. canUseOfflineSupport = !exceptionFound;
  67803. }
  67804. if (canUseOfflineSupport) {
  67805. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67806. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67807. }
  67808. else {
  67809. manifestChecked();
  67810. }
  67811. }
  67812. // Loading file from disk via input file or drag'n'drop
  67813. else {
  67814. var fileOrString = sceneFilename;
  67815. if (fileOrString.name) { // File
  67816. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67817. }
  67818. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67819. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67820. }
  67821. else {
  67822. onError("Unable to find file named " + sceneFilename);
  67823. }
  67824. }
  67825. return plugin;
  67826. };
  67827. // Public functions
  67828. SceneLoader.GetPluginForExtension = function (extension) {
  67829. return SceneLoader._getPluginForExtension(extension).plugin;
  67830. };
  67831. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67832. return !!SceneLoader._registeredPlugins[extension];
  67833. };
  67834. SceneLoader.RegisterPlugin = function (plugin) {
  67835. if (typeof plugin.extensions === "string") {
  67836. var extension = plugin.extensions;
  67837. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67838. plugin: plugin,
  67839. isBinary: false
  67840. };
  67841. }
  67842. else {
  67843. var extensions = plugin.extensions;
  67844. Object.keys(extensions).forEach(function (extension) {
  67845. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67846. plugin: plugin,
  67847. isBinary: extensions[extension].isBinary
  67848. };
  67849. });
  67850. }
  67851. };
  67852. /**
  67853. * Import meshes into a scene
  67854. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67855. * @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)
  67856. * @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)
  67857. * @param scene the instance of BABYLON.Scene to append to
  67858. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67859. * @param onProgress a callback with a progress event for each file being loaded
  67860. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67861. * @param pluginExtension the extension used to determine the plugin
  67862. * @returns The loaded plugin
  67863. */
  67864. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67865. if (sceneFilename === void 0) { sceneFilename = ""; }
  67866. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67867. if (onSuccess === void 0) { onSuccess = null; }
  67868. if (onProgress === void 0) { onProgress = null; }
  67869. if (onError === void 0) { onError = null; }
  67870. if (pluginExtension === void 0) { pluginExtension = null; }
  67871. if (!scene) {
  67872. BABYLON.Tools.Error("No scene available to import mesh to");
  67873. return null;
  67874. }
  67875. if (!sceneFilename) {
  67876. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67877. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67878. }
  67879. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67880. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67881. return null;
  67882. }
  67883. var loadingToken = {};
  67884. scene._addPendingData(loadingToken);
  67885. var disposeHandler = function () {
  67886. scene._removePendingData(loadingToken);
  67887. };
  67888. var errorHandler = function (message, exception) {
  67889. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67890. if (onError) {
  67891. onError(scene, errorMessage, exception);
  67892. }
  67893. else {
  67894. BABYLON.Tools.Error(errorMessage);
  67895. // should the exception be thrown?
  67896. }
  67897. disposeHandler();
  67898. };
  67899. var progressHandler = onProgress ? function (event) {
  67900. try {
  67901. onProgress(event);
  67902. }
  67903. catch (e) {
  67904. errorHandler("Error in onProgress callback", e);
  67905. }
  67906. } : undefined;
  67907. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67908. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67909. if (onSuccess) {
  67910. try {
  67911. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67912. }
  67913. catch (e) {
  67914. errorHandler("Error in onSuccess callback", e);
  67915. }
  67916. }
  67917. scene._removePendingData(loadingToken);
  67918. };
  67919. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67920. if (plugin.rewriteRootURL) {
  67921. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67922. }
  67923. if (sceneFilename === "") {
  67924. if (sceneFilename === "") {
  67925. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67926. }
  67927. }
  67928. if (plugin.importMesh) {
  67929. var syncedPlugin = plugin;
  67930. var meshes = new Array();
  67931. var particleSystems = new Array();
  67932. var skeletons = new Array();
  67933. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67934. return;
  67935. }
  67936. scene.loadingPluginName = plugin.name;
  67937. successHandler(meshes, particleSystems, skeletons, []);
  67938. }
  67939. else {
  67940. var asyncedPlugin = plugin;
  67941. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67942. scene.loadingPluginName = plugin.name;
  67943. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67944. }).catch(function (error) {
  67945. errorHandler(error.message, error);
  67946. });
  67947. }
  67948. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67949. };
  67950. /**
  67951. * Import meshes into a scene
  67952. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67953. * @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)
  67954. * @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)
  67955. * @param scene the instance of BABYLON.Scene to append to
  67956. * @param onProgress a callback with a progress event for each file being loaded
  67957. * @param pluginExtension the extension used to determine the plugin
  67958. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67959. */
  67960. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67961. if (sceneFilename === void 0) { sceneFilename = ""; }
  67962. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67963. if (onProgress === void 0) { onProgress = null; }
  67964. if (pluginExtension === void 0) { pluginExtension = null; }
  67965. return new Promise(function (resolve, reject) {
  67966. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67967. resolve({
  67968. meshes: meshes,
  67969. particleSystems: particleSystems,
  67970. skeletons: skeletons,
  67971. animationGroups: animationGroups
  67972. });
  67973. }, onProgress, function (scene, message, exception) {
  67974. reject(exception || new Error(message));
  67975. }, pluginExtension);
  67976. });
  67977. };
  67978. /**
  67979. * Load a scene
  67980. * @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)
  67981. * @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)
  67982. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67983. * @param onSuccess a callback with the scene when import succeeds
  67984. * @param onProgress a callback with a progress event for each file being loaded
  67985. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67986. * @param pluginExtension the extension used to determine the plugin
  67987. * @returns The loaded plugin
  67988. */
  67989. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67990. if (onSuccess === void 0) { onSuccess = null; }
  67991. if (onProgress === void 0) { onProgress = null; }
  67992. if (onError === void 0) { onError = null; }
  67993. if (pluginExtension === void 0) { pluginExtension = null; }
  67994. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67995. };
  67996. /**
  67997. * Load a scene
  67998. * @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)
  67999. * @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)
  68000. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68001. * @param onProgress a callback with a progress event for each file being loaded
  68002. * @param pluginExtension the extension used to determine the plugin
  68003. * @returns The loaded scene
  68004. */
  68005. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  68006. if (onProgress === void 0) { onProgress = null; }
  68007. if (pluginExtension === void 0) { pluginExtension = null; }
  68008. return new Promise(function (resolve, reject) {
  68009. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  68010. resolve(scene);
  68011. }, onProgress, function (scene, message, exception) {
  68012. reject(exception || new Error(message));
  68013. }, pluginExtension);
  68014. });
  68015. };
  68016. /**
  68017. * Append a scene
  68018. * @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)
  68019. * @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)
  68020. * @param scene is the instance of BABYLON.Scene to append to
  68021. * @param onSuccess a callback with the scene when import succeeds
  68022. * @param onProgress a callback with a progress event for each file being loaded
  68023. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68024. * @param pluginExtension the extension used to determine the plugin
  68025. * @returns The loaded plugin
  68026. */
  68027. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68028. if (sceneFilename === void 0) { sceneFilename = ""; }
  68029. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68030. if (onSuccess === void 0) { onSuccess = null; }
  68031. if (onProgress === void 0) { onProgress = null; }
  68032. if (onError === void 0) { onError = null; }
  68033. if (pluginExtension === void 0) { pluginExtension = null; }
  68034. if (!scene) {
  68035. BABYLON.Tools.Error("No scene available to append to");
  68036. return null;
  68037. }
  68038. if (!sceneFilename) {
  68039. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68040. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68041. }
  68042. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68043. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68044. return null;
  68045. }
  68046. if (SceneLoader.ShowLoadingScreen) {
  68047. scene.getEngine().displayLoadingUI();
  68048. }
  68049. var loadingToken = {};
  68050. scene._addPendingData(loadingToken);
  68051. var disposeHandler = function () {
  68052. scene._removePendingData(loadingToken);
  68053. scene.getEngine().hideLoadingUI();
  68054. };
  68055. var errorHandler = function (message, exception) {
  68056. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68057. if (onError) {
  68058. onError(scene, errorMessage, exception);
  68059. }
  68060. else {
  68061. BABYLON.Tools.Error(errorMessage);
  68062. // should the exception be thrown?
  68063. }
  68064. disposeHandler();
  68065. };
  68066. var progressHandler = onProgress ? function (event) {
  68067. try {
  68068. onProgress(event);
  68069. }
  68070. catch (e) {
  68071. errorHandler("Error in onProgress callback", e);
  68072. }
  68073. } : undefined;
  68074. var successHandler = function () {
  68075. if (onSuccess) {
  68076. try {
  68077. onSuccess(scene);
  68078. }
  68079. catch (e) {
  68080. errorHandler("Error in onSuccess callback", e);
  68081. }
  68082. }
  68083. scene._removePendingData(loadingToken);
  68084. };
  68085. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68086. if (sceneFilename === "") {
  68087. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68088. }
  68089. if (plugin.load) {
  68090. var syncedPlugin = plugin;
  68091. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  68092. return;
  68093. }
  68094. scene.loadingPluginName = plugin.name;
  68095. successHandler();
  68096. }
  68097. else {
  68098. var asyncedPlugin = plugin;
  68099. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  68100. scene.loadingPluginName = plugin.name;
  68101. successHandler();
  68102. }).catch(function (error) {
  68103. errorHandler(error.message, error);
  68104. });
  68105. }
  68106. if (SceneLoader.ShowLoadingScreen) {
  68107. scene.executeWhenReady(function () {
  68108. scene.getEngine().hideLoadingUI();
  68109. });
  68110. }
  68111. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68112. };
  68113. /**
  68114. * Append a scene
  68115. * @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)
  68116. * @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)
  68117. * @param scene is the instance of BABYLON.Scene to append to
  68118. * @param onProgress a callback with a progress event for each file being loaded
  68119. * @param pluginExtension the extension used to determine the plugin
  68120. * @returns The given scene
  68121. */
  68122. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68123. if (sceneFilename === void 0) { sceneFilename = ""; }
  68124. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68125. if (onProgress === void 0) { onProgress = null; }
  68126. if (pluginExtension === void 0) { pluginExtension = null; }
  68127. return new Promise(function (resolve, reject) {
  68128. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68129. resolve(scene);
  68130. }, onProgress, function (scene, message, exception) {
  68131. reject(exception || new Error(message));
  68132. }, pluginExtension);
  68133. });
  68134. };
  68135. /**
  68136. * Load a scene into an asset container
  68137. * @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)
  68138. * @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)
  68139. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68140. * @param onSuccess a callback with the scene when import succeeds
  68141. * @param onProgress a callback with a progress event for each file being loaded
  68142. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68143. * @param pluginExtension the extension used to determine the plugin
  68144. * @returns The loaded plugin
  68145. */
  68146. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68147. if (sceneFilename === void 0) { sceneFilename = ""; }
  68148. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68149. if (onSuccess === void 0) { onSuccess = null; }
  68150. if (onProgress === void 0) { onProgress = null; }
  68151. if (onError === void 0) { onError = null; }
  68152. if (pluginExtension === void 0) { pluginExtension = null; }
  68153. if (!scene) {
  68154. BABYLON.Tools.Error("No scene available to load asset container to");
  68155. return null;
  68156. }
  68157. if (!sceneFilename) {
  68158. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68159. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68160. }
  68161. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68162. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68163. return null;
  68164. }
  68165. var loadingToken = {};
  68166. scene._addPendingData(loadingToken);
  68167. var disposeHandler = function () {
  68168. scene._removePendingData(loadingToken);
  68169. };
  68170. var errorHandler = function (message, exception) {
  68171. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68172. if (onError) {
  68173. onError(scene, errorMessage, exception);
  68174. }
  68175. else {
  68176. BABYLON.Tools.Error(errorMessage);
  68177. // should the exception be thrown?
  68178. }
  68179. disposeHandler();
  68180. };
  68181. var progressHandler = onProgress ? function (event) {
  68182. try {
  68183. onProgress(event);
  68184. }
  68185. catch (e) {
  68186. errorHandler("Error in onProgress callback", e);
  68187. }
  68188. } : undefined;
  68189. var successHandler = function (assets) {
  68190. if (onSuccess) {
  68191. try {
  68192. onSuccess(assets);
  68193. }
  68194. catch (e) {
  68195. errorHandler("Error in onSuccess callback", e);
  68196. }
  68197. }
  68198. scene._removePendingData(loadingToken);
  68199. };
  68200. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68201. if (plugin.loadAssetContainer) {
  68202. var syncedPlugin = plugin;
  68203. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68204. if (!assetContainer) {
  68205. return;
  68206. }
  68207. scene.loadingPluginName = plugin.name;
  68208. successHandler(assetContainer);
  68209. }
  68210. else if (plugin.loadAssetContainerAsync) {
  68211. var asyncedPlugin = plugin;
  68212. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68213. scene.loadingPluginName = plugin.name;
  68214. successHandler(assetContainer);
  68215. }).catch(function (error) {
  68216. errorHandler(error.message, error);
  68217. });
  68218. }
  68219. else {
  68220. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68221. }
  68222. if (SceneLoader.ShowLoadingScreen) {
  68223. scene.executeWhenReady(function () {
  68224. scene.getEngine().hideLoadingUI();
  68225. });
  68226. }
  68227. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68228. };
  68229. /**
  68230. * Load a scene into an asset container
  68231. * @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)
  68232. * @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)
  68233. * @param scene is the instance of BABYLON.Scene to append to
  68234. * @param onProgress a callback with a progress event for each file being loaded
  68235. * @param pluginExtension the extension used to determine the plugin
  68236. * @returns The loaded asset container
  68237. */
  68238. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68239. if (sceneFilename === void 0) { sceneFilename = ""; }
  68240. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68241. if (onProgress === void 0) { onProgress = null; }
  68242. if (pluginExtension === void 0) { pluginExtension = null; }
  68243. return new Promise(function (resolve, reject) {
  68244. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68245. resolve(assetContainer);
  68246. }, onProgress, function (scene, message, exception) {
  68247. reject(exception || new Error(message));
  68248. }, pluginExtension);
  68249. });
  68250. };
  68251. // Flags
  68252. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68253. SceneLoader._ShowLoadingScreen = true;
  68254. SceneLoader._CleanBoneMatrixWeights = false;
  68255. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68256. // Members
  68257. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68258. SceneLoader._registeredPlugins = {};
  68259. return SceneLoader;
  68260. }());
  68261. BABYLON.SceneLoader = SceneLoader;
  68262. ;
  68263. })(BABYLON || (BABYLON = {}));
  68264. //# sourceMappingURL=babylon.sceneLoader.js.map
  68265. var BABYLON;
  68266. (function (BABYLON) {
  68267. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68268. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68269. var parsedMaterial = parsedData.materials[index];
  68270. if (parsedMaterial.id === id) {
  68271. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68272. }
  68273. }
  68274. return null;
  68275. };
  68276. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68277. for (var i in names) {
  68278. if (mesh.name === names[i]) {
  68279. hierarchyIds.push(mesh.id);
  68280. return true;
  68281. }
  68282. }
  68283. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68284. hierarchyIds.push(mesh.id);
  68285. return true;
  68286. }
  68287. return false;
  68288. };
  68289. var logOperation = function (operation, producer) {
  68290. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68291. };
  68292. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68293. if (addToScene === void 0) { addToScene = false; }
  68294. var container = new BABYLON.AssetContainer(scene);
  68295. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68296. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68297. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68298. // and avoid problems with multiple concurrent .babylon loads.
  68299. var log = "importScene has failed JSON parse";
  68300. try {
  68301. var parsedData = JSON.parse(data);
  68302. log = "";
  68303. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68304. var index;
  68305. var cache;
  68306. // Lights
  68307. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68308. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68309. var parsedLight = parsedData.lights[index];
  68310. var light = BABYLON.Light.Parse(parsedLight, scene);
  68311. if (light) {
  68312. container.lights.push(light);
  68313. log += (index === 0 ? "\n\tLights:" : "");
  68314. log += "\n\t\t" + light.toString(fullDetails);
  68315. }
  68316. }
  68317. }
  68318. // Animations
  68319. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68320. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68321. var parsedAnimation = parsedData.animations[index];
  68322. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68323. scene.animations.push(animation);
  68324. container.animations.push(animation);
  68325. log += (index === 0 ? "\n\tAnimations:" : "");
  68326. log += "\n\t\t" + animation.toString(fullDetails);
  68327. }
  68328. }
  68329. // Materials
  68330. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68331. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68332. var parsedMaterial = parsedData.materials[index];
  68333. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68334. container.materials.push(mat);
  68335. log += (index === 0 ? "\n\tMaterials:" : "");
  68336. log += "\n\t\t" + mat.toString(fullDetails);
  68337. }
  68338. }
  68339. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68340. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68341. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68342. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68343. container.multiMaterials.push(mmat);
  68344. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68345. log += "\n\t\t" + mmat.toString(fullDetails);
  68346. }
  68347. }
  68348. // Morph targets
  68349. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68350. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68351. var managerData = _a[_i];
  68352. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68353. }
  68354. }
  68355. // Skeletons
  68356. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68357. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68358. var parsedSkeleton = parsedData.skeletons[index];
  68359. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68360. container.skeletons.push(skeleton);
  68361. log += (index === 0 ? "\n\tSkeletons:" : "");
  68362. log += "\n\t\t" + skeleton.toString(fullDetails);
  68363. }
  68364. }
  68365. // Geometries
  68366. var geometries = parsedData.geometries;
  68367. if (geometries !== undefined && geometries !== null) {
  68368. var addedGeometry = new Array();
  68369. // Boxes
  68370. var boxes = geometries.boxes;
  68371. if (boxes !== undefined && boxes !== null) {
  68372. for (index = 0, cache = boxes.length; index < cache; index++) {
  68373. var parsedBox = boxes[index];
  68374. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68375. }
  68376. }
  68377. // Spheres
  68378. var spheres = geometries.spheres;
  68379. if (spheres !== undefined && spheres !== null) {
  68380. for (index = 0, cache = spheres.length; index < cache; index++) {
  68381. var parsedSphere = spheres[index];
  68382. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68383. }
  68384. }
  68385. // Cylinders
  68386. var cylinders = geometries.cylinders;
  68387. if (cylinders !== undefined && cylinders !== null) {
  68388. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68389. var parsedCylinder = cylinders[index];
  68390. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68391. }
  68392. }
  68393. // Toruses
  68394. var toruses = geometries.toruses;
  68395. if (toruses !== undefined && toruses !== null) {
  68396. for (index = 0, cache = toruses.length; index < cache; index++) {
  68397. var parsedTorus = toruses[index];
  68398. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68399. }
  68400. }
  68401. // Grounds
  68402. var grounds = geometries.grounds;
  68403. if (grounds !== undefined && grounds !== null) {
  68404. for (index = 0, cache = grounds.length; index < cache; index++) {
  68405. var parsedGround = grounds[index];
  68406. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68407. }
  68408. }
  68409. // Planes
  68410. var planes = geometries.planes;
  68411. if (planes !== undefined && planes !== null) {
  68412. for (index = 0, cache = planes.length; index < cache; index++) {
  68413. var parsedPlane = planes[index];
  68414. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68415. }
  68416. }
  68417. // TorusKnots
  68418. var torusKnots = geometries.torusKnots;
  68419. if (torusKnots !== undefined && torusKnots !== null) {
  68420. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68421. var parsedTorusKnot = torusKnots[index];
  68422. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68423. }
  68424. }
  68425. // VertexData
  68426. var vertexData = geometries.vertexData;
  68427. if (vertexData !== undefined && vertexData !== null) {
  68428. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68429. var parsedVertexData = vertexData[index];
  68430. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68431. }
  68432. }
  68433. addedGeometry.forEach(function (g) {
  68434. if (g) {
  68435. container.geometries.push(g);
  68436. }
  68437. });
  68438. }
  68439. // Transform nodes
  68440. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68441. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68442. var parsedTransformNode = parsedData.transformNodes[index];
  68443. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68444. container.transformNodes.push(node);
  68445. }
  68446. }
  68447. // Meshes
  68448. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68449. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68450. var parsedMesh = parsedData.meshes[index];
  68451. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68452. container.meshes.push(mesh);
  68453. log += (index === 0 ? "\n\tMeshes:" : "");
  68454. log += "\n\t\t" + mesh.toString(fullDetails);
  68455. }
  68456. }
  68457. // Cameras
  68458. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68459. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68460. var parsedCamera = parsedData.cameras[index];
  68461. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68462. container.cameras.push(camera);
  68463. log += (index === 0 ? "\n\tCameras:" : "");
  68464. log += "\n\t\t" + camera.toString(fullDetails);
  68465. }
  68466. }
  68467. // Browsing all the graph to connect the dots
  68468. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68469. var camera = scene.cameras[index];
  68470. if (camera._waitingParentId) {
  68471. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68472. camera._waitingParentId = null;
  68473. }
  68474. }
  68475. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68476. var light_1 = scene.lights[index];
  68477. if (light_1 && light_1._waitingParentId) {
  68478. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68479. light_1._waitingParentId = null;
  68480. }
  68481. }
  68482. // Sounds
  68483. // TODO: add sound
  68484. var loadedSounds = [];
  68485. var loadedSound;
  68486. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68487. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68488. var parsedSound = parsedData.sounds[index];
  68489. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68490. if (!parsedSound.url)
  68491. parsedSound.url = parsedSound.name;
  68492. if (!loadedSounds[parsedSound.url]) {
  68493. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68494. loadedSounds[parsedSound.url] = loadedSound;
  68495. container.sounds.push(loadedSound);
  68496. }
  68497. else {
  68498. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68499. }
  68500. }
  68501. else {
  68502. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68503. }
  68504. }
  68505. }
  68506. loadedSounds = [];
  68507. // Connect parents & children and parse actions
  68508. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68509. var transformNode = scene.transformNodes[index];
  68510. if (transformNode._waitingParentId) {
  68511. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68512. transformNode._waitingParentId = null;
  68513. }
  68514. }
  68515. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68516. var mesh = scene.meshes[index];
  68517. if (mesh._waitingParentId) {
  68518. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68519. mesh._waitingParentId = null;
  68520. }
  68521. if (mesh._waitingActions) {
  68522. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68523. mesh._waitingActions = null;
  68524. }
  68525. }
  68526. // freeze world matrix application
  68527. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68528. var currentMesh = scene.meshes[index];
  68529. if (currentMesh._waitingFreezeWorldMatrix) {
  68530. currentMesh.freezeWorldMatrix();
  68531. currentMesh._waitingFreezeWorldMatrix = null;
  68532. }
  68533. else {
  68534. currentMesh.computeWorldMatrix(true);
  68535. }
  68536. }
  68537. // Shadows
  68538. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68539. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68540. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68541. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68542. // SG would be available on their associated lights
  68543. }
  68544. }
  68545. // Lights exclusions / inclusions
  68546. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68547. var light_2 = scene.lights[index];
  68548. // Excluded check
  68549. if (light_2._excludedMeshesIds.length > 0) {
  68550. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68551. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68552. if (excludedMesh) {
  68553. light_2.excludedMeshes.push(excludedMesh);
  68554. }
  68555. }
  68556. light_2._excludedMeshesIds = [];
  68557. }
  68558. // Included check
  68559. if (light_2._includedOnlyMeshesIds.length > 0) {
  68560. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68561. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68562. if (includedOnlyMesh) {
  68563. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68564. }
  68565. }
  68566. light_2._includedOnlyMeshesIds = [];
  68567. }
  68568. }
  68569. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68570. // Actions (scene)
  68571. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68572. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68573. }
  68574. if (!addToScene) {
  68575. container.removeAllFromScene();
  68576. }
  68577. }
  68578. catch (err) {
  68579. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68580. if (onError) {
  68581. onError(msg, err);
  68582. }
  68583. else {
  68584. BABYLON.Tools.Log(msg);
  68585. throw err;
  68586. }
  68587. }
  68588. finally {
  68589. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68590. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68591. }
  68592. }
  68593. return container;
  68594. };
  68595. BABYLON.SceneLoader.RegisterPlugin({
  68596. name: "babylon.js",
  68597. extensions: ".babylon",
  68598. canDirectLoad: function (data) {
  68599. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68600. return true;
  68601. }
  68602. return false;
  68603. },
  68604. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68605. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68606. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68607. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68608. // and avoid problems with multiple concurrent .babylon loads.
  68609. var log = "importMesh has failed JSON parse";
  68610. try {
  68611. var parsedData = JSON.parse(data);
  68612. log = "";
  68613. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68614. if (!meshesNames) {
  68615. meshesNames = null;
  68616. }
  68617. else if (!Array.isArray(meshesNames)) {
  68618. meshesNames = [meshesNames];
  68619. }
  68620. var hierarchyIds = new Array();
  68621. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68622. var loadedSkeletonsIds = [];
  68623. var loadedMaterialsIds = [];
  68624. var index;
  68625. var cache;
  68626. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68627. var parsedMesh = parsedData.meshes[index];
  68628. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68629. if (meshesNames !== null) {
  68630. // Remove found mesh name from list.
  68631. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68632. }
  68633. //Geometry?
  68634. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68635. //does the file contain geometries?
  68636. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68637. //find the correct geometry and add it to the scene
  68638. var found = false;
  68639. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68640. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68641. return;
  68642. }
  68643. else {
  68644. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68645. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68646. switch (geometryType) {
  68647. case "boxes":
  68648. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68649. break;
  68650. case "spheres":
  68651. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68652. break;
  68653. case "cylinders":
  68654. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68655. break;
  68656. case "toruses":
  68657. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68658. break;
  68659. case "grounds":
  68660. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68661. break;
  68662. case "planes":
  68663. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68664. break;
  68665. case "torusKnots":
  68666. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68667. break;
  68668. case "vertexData":
  68669. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68670. break;
  68671. }
  68672. found = true;
  68673. }
  68674. });
  68675. }
  68676. });
  68677. if (found === false) {
  68678. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68679. }
  68680. }
  68681. }
  68682. // Material ?
  68683. if (parsedMesh.materialId) {
  68684. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68685. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68686. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68687. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68688. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68689. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68690. var subMatId = parsedMultiMaterial.materials[matIndex];
  68691. loadedMaterialsIds.push(subMatId);
  68692. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68693. if (mat) {
  68694. log += "\n\tMaterial " + mat.toString(fullDetails);
  68695. }
  68696. }
  68697. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68698. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68699. if (mmat) {
  68700. materialFound = true;
  68701. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68702. }
  68703. break;
  68704. }
  68705. }
  68706. }
  68707. if (materialFound === false) {
  68708. loadedMaterialsIds.push(parsedMesh.materialId);
  68709. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68710. if (!mat) {
  68711. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68712. }
  68713. else {
  68714. log += "\n\tMaterial " + mat.toString(fullDetails);
  68715. }
  68716. }
  68717. }
  68718. // Skeleton ?
  68719. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68720. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68721. if (skeletonAlreadyLoaded === false) {
  68722. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68723. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68724. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68725. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68726. skeletons.push(skeleton);
  68727. loadedSkeletonsIds.push(parsedSkeleton.id);
  68728. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68729. }
  68730. }
  68731. }
  68732. }
  68733. // Morph targets ?
  68734. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68735. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68736. var managerData = _a[_i];
  68737. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68738. }
  68739. }
  68740. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68741. meshes.push(mesh);
  68742. log += "\n\tMesh " + mesh.toString(fullDetails);
  68743. }
  68744. }
  68745. // Connecting parents
  68746. var currentMesh;
  68747. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68748. currentMesh = scene.meshes[index];
  68749. if (currentMesh._waitingParentId) {
  68750. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68751. currentMesh._waitingParentId = null;
  68752. }
  68753. }
  68754. // freeze and compute world matrix application
  68755. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68756. currentMesh = scene.meshes[index];
  68757. if (currentMesh._waitingFreezeWorldMatrix) {
  68758. currentMesh.freezeWorldMatrix();
  68759. currentMesh._waitingFreezeWorldMatrix = null;
  68760. }
  68761. else {
  68762. currentMesh.computeWorldMatrix(true);
  68763. }
  68764. }
  68765. }
  68766. // Particles
  68767. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68768. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  68769. if (parser) {
  68770. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68771. var parsedParticleSystem = parsedData.particleSystems[index];
  68772. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68773. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  68774. }
  68775. }
  68776. }
  68777. }
  68778. return true;
  68779. }
  68780. catch (err) {
  68781. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68782. if (onError) {
  68783. onError(msg, err);
  68784. }
  68785. else {
  68786. BABYLON.Tools.Log(msg);
  68787. throw err;
  68788. }
  68789. }
  68790. finally {
  68791. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68792. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68793. }
  68794. }
  68795. return false;
  68796. },
  68797. load: function (scene, data, rootUrl, onError) {
  68798. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68799. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68800. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68801. // and avoid problems with multiple concurrent .babylon loads.
  68802. var log = "importScene has failed JSON parse";
  68803. try {
  68804. var parsedData = JSON.parse(data);
  68805. log = "";
  68806. // Scene
  68807. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68808. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68809. }
  68810. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68811. scene.autoClear = parsedData.autoClear;
  68812. }
  68813. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68814. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68815. }
  68816. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68817. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68818. }
  68819. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68820. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68821. }
  68822. // Fog
  68823. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68824. scene.fogMode = parsedData.fogMode;
  68825. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68826. scene.fogStart = parsedData.fogStart;
  68827. scene.fogEnd = parsedData.fogEnd;
  68828. scene.fogDensity = parsedData.fogDensity;
  68829. log += "\tFog mode for scene: ";
  68830. switch (scene.fogMode) {
  68831. // getters not compiling, so using hardcoded
  68832. case 1:
  68833. log += "exp\n";
  68834. break;
  68835. case 2:
  68836. log += "exp2\n";
  68837. break;
  68838. case 3:
  68839. log += "linear\n";
  68840. break;
  68841. }
  68842. }
  68843. //Physics
  68844. if (parsedData.physicsEnabled) {
  68845. var physicsPlugin;
  68846. if (parsedData.physicsEngine === "cannon") {
  68847. physicsPlugin = new BABYLON.CannonJSPlugin();
  68848. }
  68849. else if (parsedData.physicsEngine === "oimo") {
  68850. physicsPlugin = new BABYLON.OimoJSPlugin();
  68851. }
  68852. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68853. //else - default engine, which is currently oimo
  68854. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68855. scene.enablePhysics(physicsGravity, physicsPlugin);
  68856. }
  68857. // Metadata
  68858. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68859. scene.metadata = parsedData.metadata;
  68860. }
  68861. //collisions, if defined. otherwise, default is true
  68862. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68863. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68864. }
  68865. scene.workerCollisions = !!parsedData.workerCollisions;
  68866. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68867. if (!container) {
  68868. return false;
  68869. }
  68870. if (parsedData.autoAnimate) {
  68871. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68872. }
  68873. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68874. scene.setActiveCameraByID(parsedData.activeCameraID);
  68875. }
  68876. // Environment texture
  68877. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68878. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68879. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68880. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68881. if (parsedData.environmentTextureRotationY) {
  68882. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68883. }
  68884. scene.environmentTexture = hdrTexture;
  68885. }
  68886. else {
  68887. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68888. if (parsedData.environmentTextureRotationY) {
  68889. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68890. }
  68891. scene.environmentTexture = cubeTexture;
  68892. }
  68893. if (parsedData.createDefaultSkybox === true) {
  68894. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68895. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68896. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68897. }
  68898. }
  68899. // Finish
  68900. return true;
  68901. }
  68902. catch (err) {
  68903. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68904. if (onError) {
  68905. onError(msg, err);
  68906. }
  68907. else {
  68908. BABYLON.Tools.Log(msg);
  68909. throw err;
  68910. }
  68911. }
  68912. finally {
  68913. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68914. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68915. }
  68916. }
  68917. return false;
  68918. },
  68919. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68920. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68921. return container;
  68922. }
  68923. });
  68924. })(BABYLON || (BABYLON = {}));
  68925. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68926. var BABYLON;
  68927. (function (BABYLON) {
  68928. var FilesInput = /** @class */ (function () {
  68929. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68930. this.onProcessFileCallback = function () { return true; };
  68931. this._engine = engine;
  68932. this._currentScene = scene;
  68933. this._sceneLoadedCallback = sceneLoadedCallback;
  68934. this._progressCallback = progressCallback;
  68935. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68936. this._textureLoadingCallback = textureLoadingCallback;
  68937. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68938. this._onReloadCallback = onReloadCallback;
  68939. this._errorCallback = errorCallback;
  68940. }
  68941. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68942. var _this = this;
  68943. if (elementToMonitor) {
  68944. this._elementToMonitor = elementToMonitor;
  68945. this._dragEnterHandler = function (e) { _this.drag(e); };
  68946. this._dragOverHandler = function (e) { _this.drag(e); };
  68947. this._dropHandler = function (e) { _this.drop(e); };
  68948. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68949. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68950. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68951. }
  68952. };
  68953. FilesInput.prototype.dispose = function () {
  68954. if (!this._elementToMonitor) {
  68955. return;
  68956. }
  68957. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68958. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68959. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68960. };
  68961. FilesInput.prototype.renderFunction = function () {
  68962. if (this._additionalRenderLoopLogicCallback) {
  68963. this._additionalRenderLoopLogicCallback();
  68964. }
  68965. if (this._currentScene) {
  68966. if (this._textureLoadingCallback) {
  68967. var remaining = this._currentScene.getWaitingItemsCount();
  68968. if (remaining > 0) {
  68969. this._textureLoadingCallback(remaining);
  68970. }
  68971. }
  68972. this._currentScene.render();
  68973. }
  68974. };
  68975. FilesInput.prototype.drag = function (e) {
  68976. e.stopPropagation();
  68977. e.preventDefault();
  68978. };
  68979. FilesInput.prototype.drop = function (eventDrop) {
  68980. eventDrop.stopPropagation();
  68981. eventDrop.preventDefault();
  68982. this.loadFiles(eventDrop);
  68983. };
  68984. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68985. var _this = this;
  68986. var reader = folder.createReader();
  68987. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68988. reader.readEntries(function (entries) {
  68989. remaining.count += entries.length;
  68990. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68991. var entry = entries_1[_i];
  68992. if (entry.isFile) {
  68993. entry.file(function (file) {
  68994. file.correctName = relativePath + file.name;
  68995. files.push(file);
  68996. if (--remaining.count === 0) {
  68997. callback();
  68998. }
  68999. });
  69000. }
  69001. else if (entry.isDirectory) {
  69002. _this._traverseFolder(entry, files, remaining, callback);
  69003. }
  69004. }
  69005. if (--remaining.count) {
  69006. callback();
  69007. }
  69008. });
  69009. };
  69010. FilesInput.prototype._processFiles = function (files) {
  69011. for (var i = 0; i < files.length; i++) {
  69012. var name = files[i].correctName.toLowerCase();
  69013. var extension = name.split('.').pop();
  69014. if (!this.onProcessFileCallback(files[i], name, extension)) {
  69015. continue;
  69016. }
  69017. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  69018. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  69019. this._sceneFileToLoad = files[i];
  69020. }
  69021. else {
  69022. FilesInput.FilesToLoad[name] = files[i];
  69023. }
  69024. }
  69025. };
  69026. FilesInput.prototype.loadFiles = function (event) {
  69027. var _this = this;
  69028. if (this._startingProcessingFilesCallback)
  69029. this._startingProcessingFilesCallback();
  69030. // Handling data transfer via drag'n'drop
  69031. if (event && event.dataTransfer && event.dataTransfer.files) {
  69032. this._filesToLoad = event.dataTransfer.files;
  69033. }
  69034. // Handling files from input files
  69035. if (event && event.target && event.target.files) {
  69036. this._filesToLoad = event.target.files;
  69037. }
  69038. if (this._filesToLoad && this._filesToLoad.length > 0) {
  69039. var files_1 = new Array();
  69040. var folders = [];
  69041. var items = event.dataTransfer ? event.dataTransfer.items : null;
  69042. for (var i = 0; i < this._filesToLoad.length; i++) {
  69043. var fileToLoad = this._filesToLoad[i];
  69044. var name_1 = fileToLoad.name.toLowerCase();
  69045. var entry = void 0;
  69046. fileToLoad.correctName = name_1;
  69047. if (items) {
  69048. var item = items[i];
  69049. if (item.getAsEntry) {
  69050. entry = item.getAsEntry();
  69051. }
  69052. else if (item.webkitGetAsEntry) {
  69053. entry = item.webkitGetAsEntry();
  69054. }
  69055. }
  69056. if (!entry) {
  69057. files_1.push(fileToLoad);
  69058. }
  69059. else {
  69060. if (entry.isDirectory) {
  69061. folders.push(entry);
  69062. }
  69063. else {
  69064. files_1.push(fileToLoad);
  69065. }
  69066. }
  69067. }
  69068. if (folders.length === 0) {
  69069. this._processFiles(files_1);
  69070. this._processReload();
  69071. }
  69072. else {
  69073. var remaining = { count: folders.length };
  69074. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  69075. var folder = folders_1[_i];
  69076. this._traverseFolder(folder, files_1, remaining, function () {
  69077. _this._processFiles(files_1);
  69078. if (remaining.count === 0) {
  69079. _this._processReload();
  69080. }
  69081. });
  69082. }
  69083. }
  69084. }
  69085. };
  69086. FilesInput.prototype._processReload = function () {
  69087. if (this._onReloadCallback) {
  69088. this._onReloadCallback(this._sceneFileToLoad);
  69089. }
  69090. else {
  69091. this.reload();
  69092. }
  69093. };
  69094. FilesInput.prototype.reload = function () {
  69095. var _this = this;
  69096. // If a scene file has been provided
  69097. if (this._sceneFileToLoad) {
  69098. if (this._currentScene) {
  69099. if (BABYLON.Tools.errorsCount > 0) {
  69100. BABYLON.Tools.ClearLogCache();
  69101. }
  69102. this._engine.stopRenderLoop();
  69103. }
  69104. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69105. if (_this._progressCallback) {
  69106. _this._progressCallback(progress);
  69107. }
  69108. }).then(function (scene) {
  69109. if (_this._currentScene) {
  69110. _this._currentScene.dispose();
  69111. }
  69112. _this._currentScene = scene;
  69113. if (_this._sceneLoadedCallback) {
  69114. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69115. }
  69116. // Wait for textures and shaders to be ready
  69117. _this._currentScene.executeWhenReady(function () {
  69118. _this._engine.runRenderLoop(function () {
  69119. _this.renderFunction();
  69120. });
  69121. });
  69122. }).catch(function (error) {
  69123. if (_this._errorCallback) {
  69124. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69125. }
  69126. });
  69127. }
  69128. else {
  69129. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69130. }
  69131. };
  69132. FilesInput.FilesToLoad = {};
  69133. return FilesInput;
  69134. }());
  69135. BABYLON.FilesInput = FilesInput;
  69136. })(BABYLON || (BABYLON = {}));
  69137. //# sourceMappingURL=babylon.filesInput.js.map
  69138. var BABYLON;
  69139. (function (BABYLON) {
  69140. /**
  69141. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69142. * The underlying implementation relies on an associative array to ensure the best performances.
  69143. * The value can be anything including 'null' but except 'undefined'
  69144. */
  69145. var StringDictionary = /** @class */ (function () {
  69146. function StringDictionary() {
  69147. this._count = 0;
  69148. this._data = {};
  69149. }
  69150. /**
  69151. * This will clear this dictionary and copy the content from the 'source' one.
  69152. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69153. * @param source the dictionary to take the content from and copy to this dictionary
  69154. */
  69155. StringDictionary.prototype.copyFrom = function (source) {
  69156. var _this = this;
  69157. this.clear();
  69158. source.forEach(function (t, v) { return _this.add(t, v); });
  69159. };
  69160. /**
  69161. * Get a value based from its key
  69162. * @param key the given key to get the matching value from
  69163. * @return the value if found, otherwise undefined is returned
  69164. */
  69165. StringDictionary.prototype.get = function (key) {
  69166. var val = this._data[key];
  69167. if (val !== undefined) {
  69168. return val;
  69169. }
  69170. return undefined;
  69171. };
  69172. /**
  69173. * Get a value from its key or add it if it doesn't exist.
  69174. * This method will ensure you that a given key/data will be present in the dictionary.
  69175. * @param key the given key to get the matching value from
  69176. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69177. * The factory will only be invoked if there's no data for the given key.
  69178. * @return the value corresponding to the key.
  69179. */
  69180. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69181. var val = this.get(key);
  69182. if (val !== undefined) {
  69183. return val;
  69184. }
  69185. val = factory(key);
  69186. if (val) {
  69187. this.add(key, val);
  69188. }
  69189. return val;
  69190. };
  69191. /**
  69192. * Get a value from its key if present in the dictionary otherwise add it
  69193. * @param key the key to get the value from
  69194. * @param val if there's no such key/value pair in the dictionary add it with this value
  69195. * @return the value corresponding to the key
  69196. */
  69197. StringDictionary.prototype.getOrAdd = function (key, val) {
  69198. var curVal = this.get(key);
  69199. if (curVal !== undefined) {
  69200. return curVal;
  69201. }
  69202. this.add(key, val);
  69203. return val;
  69204. };
  69205. /**
  69206. * Check if there's a given key in the dictionary
  69207. * @param key the key to check for
  69208. * @return true if the key is present, false otherwise
  69209. */
  69210. StringDictionary.prototype.contains = function (key) {
  69211. return this._data[key] !== undefined;
  69212. };
  69213. /**
  69214. * Add a new key and its corresponding value
  69215. * @param key the key to add
  69216. * @param value the value corresponding to the key
  69217. * @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
  69218. */
  69219. StringDictionary.prototype.add = function (key, value) {
  69220. if (this._data[key] !== undefined) {
  69221. return false;
  69222. }
  69223. this._data[key] = value;
  69224. ++this._count;
  69225. return true;
  69226. };
  69227. StringDictionary.prototype.set = function (key, value) {
  69228. if (this._data[key] === undefined) {
  69229. return false;
  69230. }
  69231. this._data[key] = value;
  69232. return true;
  69233. };
  69234. /**
  69235. * Get the element of the given key and remove it from the dictionary
  69236. * @param key
  69237. */
  69238. StringDictionary.prototype.getAndRemove = function (key) {
  69239. var val = this.get(key);
  69240. if (val !== undefined) {
  69241. delete this._data[key];
  69242. --this._count;
  69243. return val;
  69244. }
  69245. return null;
  69246. };
  69247. /**
  69248. * Remove a key/value from the dictionary.
  69249. * @param key the key to remove
  69250. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69251. */
  69252. StringDictionary.prototype.remove = function (key) {
  69253. if (this.contains(key)) {
  69254. delete this._data[key];
  69255. --this._count;
  69256. return true;
  69257. }
  69258. return false;
  69259. };
  69260. /**
  69261. * Clear the whole content of the dictionary
  69262. */
  69263. StringDictionary.prototype.clear = function () {
  69264. this._data = {};
  69265. this._count = 0;
  69266. };
  69267. Object.defineProperty(StringDictionary.prototype, "count", {
  69268. get: function () {
  69269. return this._count;
  69270. },
  69271. enumerable: true,
  69272. configurable: true
  69273. });
  69274. /**
  69275. * Execute a callback on each key/val of the dictionary.
  69276. * Note that you can remove any element in this dictionary in the callback implementation
  69277. * @param callback the callback to execute on a given key/value pair
  69278. */
  69279. StringDictionary.prototype.forEach = function (callback) {
  69280. for (var cur in this._data) {
  69281. var val = this._data[cur];
  69282. callback(cur, val);
  69283. }
  69284. };
  69285. /**
  69286. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69287. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69288. * Note that you can remove any element in this dictionary in the callback implementation
  69289. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69290. */
  69291. StringDictionary.prototype.first = function (callback) {
  69292. for (var cur in this._data) {
  69293. var val = this._data[cur];
  69294. var res = callback(cur, val);
  69295. if (res) {
  69296. return res;
  69297. }
  69298. }
  69299. return null;
  69300. };
  69301. return StringDictionary;
  69302. }());
  69303. BABYLON.StringDictionary = StringDictionary;
  69304. })(BABYLON || (BABYLON = {}));
  69305. //# sourceMappingURL=babylon.stringDictionary.js.map
  69306. var BABYLON;
  69307. (function (BABYLON) {
  69308. var Tags = /** @class */ (function () {
  69309. function Tags() {
  69310. }
  69311. Tags.EnableFor = function (obj) {
  69312. obj._tags = obj._tags || {};
  69313. obj.hasTags = function () {
  69314. return Tags.HasTags(obj);
  69315. };
  69316. obj.addTags = function (tagsString) {
  69317. return Tags.AddTagsTo(obj, tagsString);
  69318. };
  69319. obj.removeTags = function (tagsString) {
  69320. return Tags.RemoveTagsFrom(obj, tagsString);
  69321. };
  69322. obj.matchesTagsQuery = function (tagsQuery) {
  69323. return Tags.MatchesQuery(obj, tagsQuery);
  69324. };
  69325. };
  69326. Tags.DisableFor = function (obj) {
  69327. delete obj._tags;
  69328. delete obj.hasTags;
  69329. delete obj.addTags;
  69330. delete obj.removeTags;
  69331. delete obj.matchesTagsQuery;
  69332. };
  69333. Tags.HasTags = function (obj) {
  69334. if (!obj._tags) {
  69335. return false;
  69336. }
  69337. return !BABYLON.Tools.IsEmpty(obj._tags);
  69338. };
  69339. Tags.GetTags = function (obj, asString) {
  69340. if (asString === void 0) { asString = true; }
  69341. if (!obj._tags) {
  69342. return null;
  69343. }
  69344. if (asString) {
  69345. var tagsArray = [];
  69346. for (var tag in obj._tags) {
  69347. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69348. tagsArray.push(tag);
  69349. }
  69350. }
  69351. return tagsArray.join(" ");
  69352. }
  69353. else {
  69354. return obj._tags;
  69355. }
  69356. };
  69357. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69358. // a tag cannot start with '||', '&&', and '!'
  69359. // it cannot contain whitespaces
  69360. Tags.AddTagsTo = function (obj, tagsString) {
  69361. if (!tagsString) {
  69362. return;
  69363. }
  69364. if (typeof tagsString !== "string") {
  69365. return;
  69366. }
  69367. var tags = tagsString.split(" ");
  69368. tags.forEach(function (tag, index, array) {
  69369. Tags._AddTagTo(obj, tag);
  69370. });
  69371. };
  69372. Tags._AddTagTo = function (obj, tag) {
  69373. tag = tag.trim();
  69374. if (tag === "" || tag === "true" || tag === "false") {
  69375. return;
  69376. }
  69377. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69378. return;
  69379. }
  69380. Tags.EnableFor(obj);
  69381. obj._tags[tag] = true;
  69382. };
  69383. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69384. if (!Tags.HasTags(obj)) {
  69385. return;
  69386. }
  69387. var tags = tagsString.split(" ");
  69388. for (var t in tags) {
  69389. Tags._RemoveTagFrom(obj, tags[t]);
  69390. }
  69391. };
  69392. Tags._RemoveTagFrom = function (obj, tag) {
  69393. delete obj._tags[tag];
  69394. };
  69395. Tags.MatchesQuery = function (obj, tagsQuery) {
  69396. if (tagsQuery === undefined) {
  69397. return true;
  69398. }
  69399. if (tagsQuery === "") {
  69400. return Tags.HasTags(obj);
  69401. }
  69402. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69403. };
  69404. return Tags;
  69405. }());
  69406. BABYLON.Tags = Tags;
  69407. })(BABYLON || (BABYLON = {}));
  69408. //# sourceMappingURL=babylon.tags.js.map
  69409. var BABYLON;
  69410. (function (BABYLON) {
  69411. /**
  69412. * Class used to evalaute queries containing `and` and `or` operators
  69413. */
  69414. var AndOrNotEvaluator = /** @class */ (function () {
  69415. function AndOrNotEvaluator() {
  69416. }
  69417. /**
  69418. * Evaluate a query
  69419. * @param query defines the query to evaluate
  69420. * @param evaluateCallback defines the callback used to filter result
  69421. * @returns true if the query matches
  69422. */
  69423. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69424. if (!query.match(/\([^\(\)]*\)/g)) {
  69425. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69426. }
  69427. else {
  69428. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69429. // remove parenthesis
  69430. r = r.slice(1, r.length - 1);
  69431. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69432. });
  69433. }
  69434. if (query === "true") {
  69435. return true;
  69436. }
  69437. if (query === "false") {
  69438. return false;
  69439. }
  69440. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69441. };
  69442. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69443. evaluateCallback = evaluateCallback || (function (r) {
  69444. return r === "true" ? true : false;
  69445. });
  69446. var result;
  69447. var or = parenthesisContent.split("||");
  69448. for (var i in or) {
  69449. if (or.hasOwnProperty(i)) {
  69450. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69451. var and = ori.split("&&");
  69452. if (and.length > 1) {
  69453. for (var j = 0; j < and.length; ++j) {
  69454. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69455. if (andj !== "true" && andj !== "false") {
  69456. if (andj[0] === "!") {
  69457. result = !evaluateCallback(andj.substring(1));
  69458. }
  69459. else {
  69460. result = evaluateCallback(andj);
  69461. }
  69462. }
  69463. else {
  69464. result = andj === "true" ? true : false;
  69465. }
  69466. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69467. ori = "false";
  69468. break;
  69469. }
  69470. }
  69471. }
  69472. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69473. result = true;
  69474. break;
  69475. }
  69476. // result equals false (or undefined)
  69477. if (ori !== "true" && ori !== "false") {
  69478. if (ori[0] === "!") {
  69479. result = !evaluateCallback(ori.substring(1));
  69480. }
  69481. else {
  69482. result = evaluateCallback(ori);
  69483. }
  69484. }
  69485. else {
  69486. result = ori === "true" ? true : false;
  69487. }
  69488. }
  69489. }
  69490. // the whole parenthesis scope is replaced by 'true' or 'false'
  69491. return result ? "true" : "false";
  69492. };
  69493. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69494. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69495. // remove whitespaces
  69496. r = r.replace(/[\s]/g, function () { return ""; });
  69497. return r.length % 2 ? "!" : "";
  69498. });
  69499. booleanString = booleanString.trim();
  69500. if (booleanString === "!true") {
  69501. booleanString = "false";
  69502. }
  69503. else if (booleanString === "!false") {
  69504. booleanString = "true";
  69505. }
  69506. return booleanString;
  69507. };
  69508. return AndOrNotEvaluator;
  69509. }());
  69510. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69511. })(BABYLON || (BABYLON = {}));
  69512. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69513. var BABYLON;
  69514. (function (BABYLON) {
  69515. /**
  69516. * Class used to enable access to IndexedDB
  69517. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69518. */
  69519. var Database = /** @class */ (function () {
  69520. /**
  69521. * Creates a new Database
  69522. * @param urlToScene defines the url to load the scene
  69523. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69524. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69525. */
  69526. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69527. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69528. var _this = this;
  69529. // Handling various flavors of prefixed version of IndexedDB
  69530. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69531. this.callbackManifestChecked = callbackManifestChecked;
  69532. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69533. this.db = null;
  69534. this._enableSceneOffline = false;
  69535. this._enableTexturesOffline = false;
  69536. this.manifestVersionFound = 0;
  69537. this.mustUpdateRessources = false;
  69538. this.hasReachedQuota = false;
  69539. if (!Database.IDBStorageEnabled) {
  69540. this.callbackManifestChecked(true);
  69541. }
  69542. else {
  69543. if (disableManifestCheck) {
  69544. this._enableSceneOffline = true;
  69545. this._enableTexturesOffline = true;
  69546. this.manifestVersionFound = 1;
  69547. BABYLON.Tools.SetImmediate(function () {
  69548. _this.callbackManifestChecked(true);
  69549. });
  69550. }
  69551. else {
  69552. this._checkManifestFile();
  69553. }
  69554. }
  69555. }
  69556. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69557. /**
  69558. * Gets a boolean indicating if scene must be saved in the database
  69559. */
  69560. get: function () {
  69561. return this._enableSceneOffline;
  69562. },
  69563. enumerable: true,
  69564. configurable: true
  69565. });
  69566. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69567. /**
  69568. * Gets a boolean indicating if textures must be saved in the database
  69569. */
  69570. get: function () {
  69571. return this._enableTexturesOffline;
  69572. },
  69573. enumerable: true,
  69574. configurable: true
  69575. });
  69576. Database.prototype._checkManifestFile = function () {
  69577. var _this = this;
  69578. var noManifestFile = function () {
  69579. _this._enableSceneOffline = false;
  69580. _this._enableTexturesOffline = false;
  69581. _this.callbackManifestChecked(false);
  69582. };
  69583. var timeStampUsed = false;
  69584. var manifestURL = this.currentSceneUrl + ".manifest";
  69585. var xhr = new XMLHttpRequest();
  69586. if (navigator.onLine) {
  69587. // Adding a timestamp to by-pass browsers' cache
  69588. timeStampUsed = true;
  69589. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69590. }
  69591. xhr.open("GET", manifestURL, true);
  69592. xhr.addEventListener("load", function () {
  69593. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69594. try {
  69595. var manifestFile = JSON.parse(xhr.response);
  69596. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69597. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69598. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69599. _this.manifestVersionFound = manifestFile.version;
  69600. }
  69601. if (_this.callbackManifestChecked) {
  69602. _this.callbackManifestChecked(true);
  69603. }
  69604. }
  69605. catch (ex) {
  69606. noManifestFile();
  69607. }
  69608. }
  69609. else {
  69610. noManifestFile();
  69611. }
  69612. }, false);
  69613. xhr.addEventListener("error", function (event) {
  69614. if (timeStampUsed) {
  69615. timeStampUsed = false;
  69616. // Let's retry without the timeStamp
  69617. // It could fail when coupled with HTML5 Offline API
  69618. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69619. xhr.open("GET", retryManifestURL, true);
  69620. xhr.send();
  69621. }
  69622. else {
  69623. noManifestFile();
  69624. }
  69625. }, false);
  69626. try {
  69627. xhr.send();
  69628. }
  69629. catch (ex) {
  69630. BABYLON.Tools.Error("Error on XHR send request.");
  69631. this.callbackManifestChecked(false);
  69632. }
  69633. };
  69634. /**
  69635. * Open the database and make it available
  69636. * @param successCallback defines the callback to call on success
  69637. * @param errorCallback defines the callback to call on error
  69638. */
  69639. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69640. var _this = this;
  69641. var handleError = function () {
  69642. _this.isSupported = false;
  69643. if (errorCallback)
  69644. errorCallback();
  69645. };
  69646. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69647. // Your browser doesn't support IndexedDB
  69648. this.isSupported = false;
  69649. if (errorCallback)
  69650. errorCallback();
  69651. }
  69652. else {
  69653. // If the DB hasn't been opened or created yet
  69654. if (!this.db) {
  69655. this.hasReachedQuota = false;
  69656. this.isSupported = true;
  69657. var request = this.idbFactory.open("babylonjs", 1);
  69658. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69659. request.onerror = function (event) {
  69660. handleError();
  69661. };
  69662. // executes when a version change transaction cannot complete due to other active transactions
  69663. request.onblocked = function (event) {
  69664. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69665. handleError();
  69666. };
  69667. // DB has been opened successfully
  69668. request.onsuccess = function (event) {
  69669. _this.db = request.result;
  69670. successCallback();
  69671. };
  69672. // Initialization of the DB. Creating Scenes & Textures stores
  69673. request.onupgradeneeded = function (event) {
  69674. _this.db = (event.target).result;
  69675. if (_this.db) {
  69676. try {
  69677. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69678. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69679. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69680. }
  69681. catch (ex) {
  69682. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69683. handleError();
  69684. }
  69685. }
  69686. };
  69687. }
  69688. // DB has already been created and opened
  69689. else {
  69690. if (successCallback)
  69691. successCallback();
  69692. }
  69693. }
  69694. };
  69695. /**
  69696. * Loads an image from the database
  69697. * @param url defines the url to load from
  69698. * @param image defines the target DOM image
  69699. */
  69700. Database.prototype.loadImageFromDB = function (url, image) {
  69701. var _this = this;
  69702. var completeURL = Database._ReturnFullUrlLocation(url);
  69703. var saveAndLoadImage = function () {
  69704. if (!_this.hasReachedQuota && _this.db !== null) {
  69705. // the texture is not yet in the DB, let's try to save it
  69706. _this._saveImageIntoDBAsync(completeURL, image);
  69707. }
  69708. // If the texture is not in the DB and we've reached the DB quota limit
  69709. // let's load it directly from the web
  69710. else {
  69711. image.src = url;
  69712. }
  69713. };
  69714. if (!this.mustUpdateRessources) {
  69715. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69716. }
  69717. // First time we're download the images or update requested in the manifest file by a version change
  69718. else {
  69719. saveAndLoadImage();
  69720. }
  69721. };
  69722. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69723. if (this.isSupported && this.db !== null) {
  69724. var texture;
  69725. var transaction = this.db.transaction(["textures"]);
  69726. transaction.onabort = function (event) {
  69727. image.src = url;
  69728. };
  69729. transaction.oncomplete = function (event) {
  69730. var blobTextureURL;
  69731. if (texture) {
  69732. var URL = window.URL || window.webkitURL;
  69733. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69734. image.onerror = function () {
  69735. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69736. image.src = url;
  69737. };
  69738. image.src = blobTextureURL;
  69739. }
  69740. else {
  69741. notInDBCallback();
  69742. }
  69743. };
  69744. var getRequest = transaction.objectStore("textures").get(url);
  69745. getRequest.onsuccess = function (event) {
  69746. texture = (event.target).result;
  69747. };
  69748. getRequest.onerror = function (event) {
  69749. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69750. image.src = url;
  69751. };
  69752. }
  69753. else {
  69754. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69755. image.src = url;
  69756. }
  69757. };
  69758. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69759. var _this = this;
  69760. if (this.isSupported) {
  69761. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69762. var generateBlobUrl = function () {
  69763. var blobTextureURL;
  69764. if (blob) {
  69765. var URL = window.URL || window.webkitURL;
  69766. try {
  69767. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69768. }
  69769. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69770. catch (ex) {
  69771. blobTextureURL = URL.createObjectURL(blob);
  69772. }
  69773. }
  69774. if (blobTextureURL) {
  69775. image.src = blobTextureURL;
  69776. }
  69777. };
  69778. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69779. var xhr = new XMLHttpRequest(), blob;
  69780. xhr.open("GET", url, true);
  69781. xhr.responseType = "blob";
  69782. xhr.addEventListener("load", function () {
  69783. if (xhr.status === 200 && _this.db) {
  69784. // Blob as response (XHR2)
  69785. blob = xhr.response;
  69786. var transaction = _this.db.transaction(["textures"], "readwrite");
  69787. // the transaction could abort because of a QuotaExceededError error
  69788. transaction.onabort = function (event) {
  69789. try {
  69790. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69791. var srcElement = (event.srcElement || event.target);
  69792. var error = srcElement.error;
  69793. if (error && error.name === "QuotaExceededError") {
  69794. _this.hasReachedQuota = true;
  69795. }
  69796. }
  69797. catch (ex) { }
  69798. generateBlobUrl();
  69799. };
  69800. transaction.oncomplete = function (event) {
  69801. generateBlobUrl();
  69802. };
  69803. var newTexture = { textureUrl: url, data: blob };
  69804. try {
  69805. // Put the blob into the dabase
  69806. var addRequest = transaction.objectStore("textures").put(newTexture);
  69807. addRequest.onsuccess = function (event) {
  69808. };
  69809. addRequest.onerror = function (event) {
  69810. generateBlobUrl();
  69811. };
  69812. }
  69813. catch (ex) {
  69814. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69815. if (ex.code === 25) {
  69816. Database.IsUASupportingBlobStorage = false;
  69817. }
  69818. image.src = url;
  69819. }
  69820. }
  69821. else {
  69822. image.src = url;
  69823. }
  69824. }, false);
  69825. xhr.addEventListener("error", function (event) {
  69826. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69827. image.src = url;
  69828. }, false);
  69829. xhr.send();
  69830. }
  69831. else {
  69832. image.src = url;
  69833. }
  69834. }
  69835. else {
  69836. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69837. image.src = url;
  69838. }
  69839. };
  69840. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69841. var _this = this;
  69842. var updateVersion = function () {
  69843. // the version is not yet in the DB or we need to update it
  69844. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69845. };
  69846. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69847. };
  69848. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69849. var _this = this;
  69850. if (this.isSupported && this.db) {
  69851. var version;
  69852. try {
  69853. var transaction = this.db.transaction(["versions"]);
  69854. transaction.oncomplete = function (event) {
  69855. if (version) {
  69856. // If the version in the JSON file is different from the version in DB
  69857. if (_this.manifestVersionFound !== version.data) {
  69858. _this.mustUpdateRessources = true;
  69859. updateInDBCallback();
  69860. }
  69861. else {
  69862. callback(version.data);
  69863. }
  69864. }
  69865. // version was not found in DB
  69866. else {
  69867. _this.mustUpdateRessources = true;
  69868. updateInDBCallback();
  69869. }
  69870. };
  69871. transaction.onabort = function (event) {
  69872. callback(-1);
  69873. };
  69874. var getRequest = transaction.objectStore("versions").get(url);
  69875. getRequest.onsuccess = function (event) {
  69876. version = (event.target).result;
  69877. };
  69878. getRequest.onerror = function (event) {
  69879. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69880. callback(-1);
  69881. };
  69882. }
  69883. catch (ex) {
  69884. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69885. callback(-1);
  69886. }
  69887. }
  69888. else {
  69889. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69890. callback(-1);
  69891. }
  69892. };
  69893. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69894. var _this = this;
  69895. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69896. try {
  69897. // Open a transaction to the database
  69898. var transaction = this.db.transaction(["versions"], "readwrite");
  69899. // the transaction could abort because of a QuotaExceededError error
  69900. transaction.onabort = function (event) {
  69901. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69902. var error = event.srcElement['error'];
  69903. if (error && error.name === "QuotaExceededError") {
  69904. _this.hasReachedQuota = true;
  69905. }
  69906. }
  69907. catch (ex) { }
  69908. callback(-1);
  69909. };
  69910. transaction.oncomplete = function (event) {
  69911. callback(_this.manifestVersionFound);
  69912. };
  69913. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69914. // Put the scene into the database
  69915. var addRequest = transaction.objectStore("versions").put(newVersion);
  69916. addRequest.onsuccess = function (event) {
  69917. };
  69918. addRequest.onerror = function (event) {
  69919. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69920. };
  69921. }
  69922. catch (ex) {
  69923. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69924. callback(-1);
  69925. }
  69926. }
  69927. else {
  69928. callback(-1);
  69929. }
  69930. };
  69931. /**
  69932. * Loads a file from database
  69933. * @param url defines the URL to load from
  69934. * @param sceneLoaded defines a callback to call on success
  69935. * @param progressCallBack defines a callback to call when progress changed
  69936. * @param errorCallback defines a callback to call on error
  69937. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69938. */
  69939. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69940. var _this = this;
  69941. var completeUrl = Database._ReturnFullUrlLocation(url);
  69942. var saveAndLoadFile = function () {
  69943. // the scene is not yet in the DB, let's try to save it
  69944. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  69945. };
  69946. this._checkVersionFromDB(completeUrl, function (version) {
  69947. if (version !== -1) {
  69948. if (!_this.mustUpdateRessources) {
  69949. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69950. }
  69951. else {
  69952. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  69953. }
  69954. }
  69955. else {
  69956. if (errorCallback) {
  69957. errorCallback();
  69958. }
  69959. }
  69960. });
  69961. };
  69962. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69963. if (this.isSupported && this.db) {
  69964. var targetStore;
  69965. if (url.indexOf(".babylon") !== -1) {
  69966. targetStore = "scenes";
  69967. }
  69968. else {
  69969. targetStore = "textures";
  69970. }
  69971. var file;
  69972. var transaction = this.db.transaction([targetStore]);
  69973. transaction.oncomplete = function (event) {
  69974. if (file) {
  69975. callback(file.data);
  69976. }
  69977. // file was not found in DB
  69978. else {
  69979. notInDBCallback();
  69980. }
  69981. };
  69982. transaction.onabort = function (event) {
  69983. notInDBCallback();
  69984. };
  69985. var getRequest = transaction.objectStore(targetStore).get(url);
  69986. getRequest.onsuccess = function (event) {
  69987. file = (event.target).result;
  69988. };
  69989. getRequest.onerror = function (event) {
  69990. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69991. notInDBCallback();
  69992. };
  69993. }
  69994. else {
  69995. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69996. callback();
  69997. }
  69998. };
  69999. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  70000. var _this = this;
  70001. if (this.isSupported) {
  70002. var targetStore;
  70003. if (url.indexOf(".babylon") !== -1) {
  70004. targetStore = "scenes";
  70005. }
  70006. else {
  70007. targetStore = "textures";
  70008. }
  70009. // Create XHR
  70010. var xhr = new XMLHttpRequest();
  70011. var fileData;
  70012. xhr.open("GET", url, true);
  70013. if (useArrayBuffer) {
  70014. xhr.responseType = "arraybuffer";
  70015. }
  70016. if (progressCallback) {
  70017. xhr.onprogress = progressCallback;
  70018. }
  70019. xhr.addEventListener("load", function () {
  70020. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  70021. // Blob as response (XHR2)
  70022. //fileData = xhr.responseText;
  70023. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  70024. if (!_this.hasReachedQuota && _this.db) {
  70025. // Open a transaction to the database
  70026. var transaction = _this.db.transaction([targetStore], "readwrite");
  70027. // the transaction could abort because of a QuotaExceededError error
  70028. transaction.onabort = function (event) {
  70029. try {
  70030. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70031. var error = event.srcElement['error'];
  70032. if (error && error.name === "QuotaExceededError") {
  70033. _this.hasReachedQuota = true;
  70034. }
  70035. }
  70036. catch (ex) { }
  70037. callback(fileData);
  70038. };
  70039. transaction.oncomplete = function (event) {
  70040. callback(fileData);
  70041. };
  70042. var newFile;
  70043. if (targetStore === "scenes") {
  70044. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  70045. }
  70046. else {
  70047. newFile = { textureUrl: url, data: fileData };
  70048. }
  70049. try {
  70050. // Put the scene into the database
  70051. var addRequest = transaction.objectStore(targetStore).put(newFile);
  70052. addRequest.onsuccess = function (event) {
  70053. };
  70054. addRequest.onerror = function (event) {
  70055. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  70056. };
  70057. }
  70058. catch (ex) {
  70059. callback(fileData);
  70060. }
  70061. }
  70062. else {
  70063. callback(fileData);
  70064. }
  70065. }
  70066. else {
  70067. if (xhr.status >= 400 && errorCallback) {
  70068. errorCallback(xhr);
  70069. }
  70070. else {
  70071. callback();
  70072. }
  70073. }
  70074. }, false);
  70075. xhr.addEventListener("error", function (event) {
  70076. BABYLON.Tools.Error("error on XHR request.");
  70077. callback();
  70078. }, false);
  70079. xhr.send();
  70080. }
  70081. else {
  70082. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70083. callback();
  70084. }
  70085. };
  70086. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  70087. Database.IsUASupportingBlobStorage = true;
  70088. /** Gets a boolean indicating if Database storate is enabled */
  70089. Database.IDBStorageEnabled = true;
  70090. Database._ParseURL = function (url) {
  70091. var a = document.createElement('a');
  70092. a.href = url;
  70093. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  70094. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  70095. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  70096. return absLocation;
  70097. };
  70098. Database._ReturnFullUrlLocation = function (url) {
  70099. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70100. return (Database._ParseURL(window.location.href) + url);
  70101. }
  70102. else {
  70103. return url;
  70104. }
  70105. };
  70106. return Database;
  70107. }());
  70108. BABYLON.Database = Database;
  70109. })(BABYLON || (BABYLON = {}));
  70110. //# sourceMappingURL=babylon.database.js.map
  70111. var BABYLON;
  70112. (function (BABYLON) {
  70113. var FresnelParameters = /** @class */ (function () {
  70114. function FresnelParameters() {
  70115. this._isEnabled = true;
  70116. this.leftColor = BABYLON.Color3.White();
  70117. this.rightColor = BABYLON.Color3.Black();
  70118. this.bias = 0;
  70119. this.power = 1;
  70120. }
  70121. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70122. get: function () {
  70123. return this._isEnabled;
  70124. },
  70125. set: function (value) {
  70126. if (this._isEnabled === value) {
  70127. return;
  70128. }
  70129. this._isEnabled = value;
  70130. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70131. },
  70132. enumerable: true,
  70133. configurable: true
  70134. });
  70135. FresnelParameters.prototype.clone = function () {
  70136. var newFresnelParameters = new FresnelParameters();
  70137. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70138. return newFresnelParameters;
  70139. };
  70140. FresnelParameters.prototype.serialize = function () {
  70141. var serializationObject = {};
  70142. serializationObject.isEnabled = this.isEnabled;
  70143. serializationObject.leftColor = this.leftColor.asArray();
  70144. serializationObject.rightColor = this.rightColor.asArray();
  70145. serializationObject.bias = this.bias;
  70146. serializationObject.power = this.power;
  70147. return serializationObject;
  70148. };
  70149. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70150. var fresnelParameters = new FresnelParameters();
  70151. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70152. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70153. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70154. fresnelParameters.bias = parsedFresnelParameters.bias;
  70155. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70156. return fresnelParameters;
  70157. };
  70158. return FresnelParameters;
  70159. }());
  70160. BABYLON.FresnelParameters = FresnelParameters;
  70161. })(BABYLON || (BABYLON = {}));
  70162. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70163. var BABYLON;
  70164. (function (BABYLON) {
  70165. var MultiMaterial = /** @class */ (function (_super) {
  70166. __extends(MultiMaterial, _super);
  70167. function MultiMaterial(name, scene) {
  70168. var _this = _super.call(this, name, scene, true) || this;
  70169. scene.multiMaterials.push(_this);
  70170. _this.subMaterials = new Array();
  70171. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70172. return _this;
  70173. }
  70174. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70175. get: function () {
  70176. return this._subMaterials;
  70177. },
  70178. set: function (value) {
  70179. this._subMaterials = value;
  70180. this._hookArray(value);
  70181. },
  70182. enumerable: true,
  70183. configurable: true
  70184. });
  70185. MultiMaterial.prototype._hookArray = function (array) {
  70186. var _this = this;
  70187. var oldPush = array.push;
  70188. array.push = function () {
  70189. var items = [];
  70190. for (var _i = 0; _i < arguments.length; _i++) {
  70191. items[_i] = arguments[_i];
  70192. }
  70193. var result = oldPush.apply(array, items);
  70194. _this._markAllSubMeshesAsTexturesDirty();
  70195. return result;
  70196. };
  70197. var oldSplice = array.splice;
  70198. array.splice = function (index, deleteCount) {
  70199. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70200. _this._markAllSubMeshesAsTexturesDirty();
  70201. return deleted;
  70202. };
  70203. };
  70204. // Properties
  70205. MultiMaterial.prototype.getSubMaterial = function (index) {
  70206. if (index < 0 || index >= this.subMaterials.length) {
  70207. return this.getScene().defaultMaterial;
  70208. }
  70209. return this.subMaterials[index];
  70210. };
  70211. MultiMaterial.prototype.getActiveTextures = function () {
  70212. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70213. if (subMaterial) {
  70214. return subMaterial.getActiveTextures();
  70215. }
  70216. else {
  70217. return [];
  70218. }
  70219. }));
  70220. var _a;
  70221. };
  70222. // Methods
  70223. MultiMaterial.prototype.getClassName = function () {
  70224. return "MultiMaterial";
  70225. };
  70226. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70227. for (var index = 0; index < this.subMaterials.length; index++) {
  70228. var subMaterial = this.subMaterials[index];
  70229. if (subMaterial) {
  70230. if (subMaterial.storeEffectOnSubMeshes) {
  70231. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70232. return false;
  70233. }
  70234. continue;
  70235. }
  70236. if (!subMaterial.isReady(mesh)) {
  70237. return false;
  70238. }
  70239. }
  70240. }
  70241. return true;
  70242. };
  70243. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70244. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70245. for (var index = 0; index < this.subMaterials.length; index++) {
  70246. var subMaterial = null;
  70247. var current = this.subMaterials[index];
  70248. if (cloneChildren && current) {
  70249. subMaterial = current.clone(name + "-" + current.name);
  70250. }
  70251. else {
  70252. subMaterial = this.subMaterials[index];
  70253. }
  70254. newMultiMaterial.subMaterials.push(subMaterial);
  70255. }
  70256. return newMultiMaterial;
  70257. };
  70258. MultiMaterial.prototype.serialize = function () {
  70259. var serializationObject = {};
  70260. serializationObject.name = this.name;
  70261. serializationObject.id = this.id;
  70262. if (BABYLON.Tags) {
  70263. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70264. }
  70265. serializationObject.materials = [];
  70266. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70267. var subMat = this.subMaterials[matIndex];
  70268. if (subMat) {
  70269. serializationObject.materials.push(subMat.id);
  70270. }
  70271. else {
  70272. serializationObject.materials.push(null);
  70273. }
  70274. }
  70275. return serializationObject;
  70276. };
  70277. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70278. var scene = this.getScene();
  70279. if (!scene) {
  70280. return;
  70281. }
  70282. var index = scene.multiMaterials.indexOf(this);
  70283. if (index >= 0) {
  70284. scene.multiMaterials.splice(index, 1);
  70285. }
  70286. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70287. };
  70288. return MultiMaterial;
  70289. }(BABYLON.Material));
  70290. BABYLON.MultiMaterial = MultiMaterial;
  70291. })(BABYLON || (BABYLON = {}));
  70292. //# sourceMappingURL=babylon.multiMaterial.js.map
  70293. var BABYLON;
  70294. (function (BABYLON) {
  70295. var FreeCameraTouchInput = /** @class */ (function () {
  70296. function FreeCameraTouchInput() {
  70297. this._offsetX = null;
  70298. this._offsetY = null;
  70299. this._pointerPressed = new Array();
  70300. this.touchAngularSensibility = 200000.0;
  70301. this.touchMoveSensibility = 250.0;
  70302. }
  70303. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70304. var _this = this;
  70305. var previousPosition = null;
  70306. if (this._pointerInput === undefined) {
  70307. this._onLostFocus = function (evt) {
  70308. _this._offsetX = null;
  70309. _this._offsetY = null;
  70310. };
  70311. this._pointerInput = function (p, s) {
  70312. var evt = p.event;
  70313. if (evt.pointerType === "mouse") {
  70314. return;
  70315. }
  70316. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70317. if (!noPreventDefault) {
  70318. evt.preventDefault();
  70319. }
  70320. _this._pointerPressed.push(evt.pointerId);
  70321. if (_this._pointerPressed.length !== 1) {
  70322. return;
  70323. }
  70324. previousPosition = {
  70325. x: evt.clientX,
  70326. y: evt.clientY
  70327. };
  70328. }
  70329. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70330. if (!noPreventDefault) {
  70331. evt.preventDefault();
  70332. }
  70333. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70334. if (index === -1) {
  70335. return;
  70336. }
  70337. _this._pointerPressed.splice(index, 1);
  70338. if (index != 0) {
  70339. return;
  70340. }
  70341. previousPosition = null;
  70342. _this._offsetX = null;
  70343. _this._offsetY = null;
  70344. }
  70345. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70346. if (!noPreventDefault) {
  70347. evt.preventDefault();
  70348. }
  70349. if (!previousPosition) {
  70350. return;
  70351. }
  70352. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70353. if (index != 0) {
  70354. return;
  70355. }
  70356. _this._offsetX = evt.clientX - previousPosition.x;
  70357. _this._offsetY = -(evt.clientY - previousPosition.y);
  70358. }
  70359. };
  70360. }
  70361. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70362. if (this._onLostFocus) {
  70363. element.addEventListener("blur", this._onLostFocus);
  70364. }
  70365. };
  70366. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70367. if (this._pointerInput && element) {
  70368. if (this._observer) {
  70369. this.camera.getScene().onPointerObservable.remove(this._observer);
  70370. this._observer = null;
  70371. }
  70372. if (this._onLostFocus) {
  70373. element.removeEventListener("blur", this._onLostFocus);
  70374. this._onLostFocus = null;
  70375. }
  70376. this._pointerPressed = [];
  70377. this._offsetX = null;
  70378. this._offsetY = null;
  70379. }
  70380. };
  70381. FreeCameraTouchInput.prototype.checkInputs = function () {
  70382. if (this._offsetX && this._offsetY) {
  70383. var camera = this.camera;
  70384. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70385. if (this._pointerPressed.length > 1) {
  70386. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70387. }
  70388. else {
  70389. var speed = camera._computeLocalCameraSpeed();
  70390. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70391. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70392. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70393. }
  70394. }
  70395. };
  70396. FreeCameraTouchInput.prototype.getClassName = function () {
  70397. return "FreeCameraTouchInput";
  70398. };
  70399. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70400. return "touch";
  70401. };
  70402. __decorate([
  70403. BABYLON.serialize()
  70404. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70405. __decorate([
  70406. BABYLON.serialize()
  70407. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70408. return FreeCameraTouchInput;
  70409. }());
  70410. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70411. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70412. })(BABYLON || (BABYLON = {}));
  70413. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70414. var BABYLON;
  70415. (function (BABYLON) {
  70416. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  70417. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  70418. });
  70419. // We're mainly based on the logic defined into the FreeCamera code
  70420. var TouchCamera = /** @class */ (function (_super) {
  70421. __extends(TouchCamera, _super);
  70422. //-- end properties for backward compatibility for inputs
  70423. function TouchCamera(name, position, scene) {
  70424. var _this = _super.call(this, name, position, scene) || this;
  70425. _this.inputs.addTouch();
  70426. _this._setupInputs();
  70427. return _this;
  70428. }
  70429. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70430. //-- Begin properties for backward compatibility for inputs
  70431. get: function () {
  70432. var touch = this.inputs.attached["touch"];
  70433. if (touch)
  70434. return touch.touchAngularSensibility;
  70435. return 0;
  70436. },
  70437. set: function (value) {
  70438. var touch = this.inputs.attached["touch"];
  70439. if (touch)
  70440. touch.touchAngularSensibility = value;
  70441. },
  70442. enumerable: true,
  70443. configurable: true
  70444. });
  70445. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70446. get: function () {
  70447. var touch = this.inputs.attached["touch"];
  70448. if (touch)
  70449. return touch.touchMoveSensibility;
  70450. return 0;
  70451. },
  70452. set: function (value) {
  70453. var touch = this.inputs.attached["touch"];
  70454. if (touch)
  70455. touch.touchMoveSensibility = value;
  70456. },
  70457. enumerable: true,
  70458. configurable: true
  70459. });
  70460. TouchCamera.prototype.getClassName = function () {
  70461. return "TouchCamera";
  70462. };
  70463. TouchCamera.prototype._setupInputs = function () {
  70464. var mouse = this.inputs.attached["mouse"];
  70465. if (mouse) {
  70466. mouse.touchEnabled = false;
  70467. }
  70468. };
  70469. return TouchCamera;
  70470. }(BABYLON.FreeCamera));
  70471. BABYLON.TouchCamera = TouchCamera;
  70472. })(BABYLON || (BABYLON = {}));
  70473. //# sourceMappingURL=babylon.touchCamera.js.map
  70474. var BABYLON;
  70475. (function (BABYLON) {
  70476. var ProceduralTexture = /** @class */ (function (_super) {
  70477. __extends(ProceduralTexture, _super);
  70478. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70479. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70480. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70481. if (isCube === void 0) { isCube = false; }
  70482. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70483. _this.isCube = isCube;
  70484. _this.isEnabled = true;
  70485. _this._currentRefreshId = -1;
  70486. _this._refreshRate = 1;
  70487. _this._vertexBuffers = {};
  70488. _this._uniforms = new Array();
  70489. _this._samplers = new Array();
  70490. _this._textures = {};
  70491. _this._floats = {};
  70492. _this._floatsArrays = {};
  70493. _this._colors3 = {};
  70494. _this._colors4 = {};
  70495. _this._vectors2 = {};
  70496. _this._vectors3 = {};
  70497. _this._matrices = {};
  70498. _this._fallbackTextureUsed = false;
  70499. scene.proceduralTextures.push(_this);
  70500. _this._engine = scene.getEngine();
  70501. _this.name = name;
  70502. _this.isRenderTarget = true;
  70503. _this._size = size;
  70504. _this._generateMipMaps = generateMipMaps;
  70505. _this.setFragment(fragment);
  70506. _this._fallbackTexture = fallbackTexture;
  70507. if (isCube) {
  70508. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70509. _this.setFloat("face", 0);
  70510. }
  70511. else {
  70512. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70513. }
  70514. // VBO
  70515. var vertices = [];
  70516. vertices.push(1, 1);
  70517. vertices.push(-1, 1);
  70518. vertices.push(-1, -1);
  70519. vertices.push(1, -1);
  70520. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70521. _this._createIndexBuffer();
  70522. return _this;
  70523. }
  70524. ProceduralTexture.prototype._createIndexBuffer = function () {
  70525. var engine = this._engine;
  70526. // Indices
  70527. var indices = [];
  70528. indices.push(0);
  70529. indices.push(1);
  70530. indices.push(2);
  70531. indices.push(0);
  70532. indices.push(2);
  70533. indices.push(3);
  70534. this._indexBuffer = engine.createIndexBuffer(indices);
  70535. };
  70536. ProceduralTexture.prototype._rebuild = function () {
  70537. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70538. if (vb) {
  70539. vb._rebuild();
  70540. }
  70541. this._createIndexBuffer();
  70542. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70543. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70544. }
  70545. };
  70546. ProceduralTexture.prototype.reset = function () {
  70547. if (this._effect === undefined) {
  70548. return;
  70549. }
  70550. var engine = this._engine;
  70551. engine._releaseEffect(this._effect);
  70552. };
  70553. ProceduralTexture.prototype.isReady = function () {
  70554. var _this = this;
  70555. var engine = this._engine;
  70556. var shaders;
  70557. if (!this._fragment) {
  70558. return false;
  70559. }
  70560. if (this._fallbackTextureUsed) {
  70561. return true;
  70562. }
  70563. if (this._fragment.fragmentElement !== undefined) {
  70564. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70565. }
  70566. else {
  70567. shaders = { vertex: "procedural", fragment: this._fragment };
  70568. }
  70569. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70570. _this.releaseInternalTexture();
  70571. if (_this._fallbackTexture) {
  70572. _this._texture = _this._fallbackTexture._texture;
  70573. if (_this._texture) {
  70574. _this._texture.incrementReferences();
  70575. }
  70576. }
  70577. _this._fallbackTextureUsed = true;
  70578. });
  70579. return this._effect.isReady();
  70580. };
  70581. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70582. this._currentRefreshId = -1;
  70583. };
  70584. ProceduralTexture.prototype.setFragment = function (fragment) {
  70585. this._fragment = fragment;
  70586. };
  70587. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70588. get: function () {
  70589. return this._refreshRate;
  70590. },
  70591. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70592. set: function (value) {
  70593. this._refreshRate = value;
  70594. this.resetRefreshCounter();
  70595. },
  70596. enumerable: true,
  70597. configurable: true
  70598. });
  70599. ProceduralTexture.prototype._shouldRender = function () {
  70600. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70601. return false;
  70602. }
  70603. if (this._fallbackTextureUsed) {
  70604. return false;
  70605. }
  70606. if (this._currentRefreshId === -1) { // At least render once
  70607. this._currentRefreshId = 1;
  70608. return true;
  70609. }
  70610. if (this.refreshRate === this._currentRefreshId) {
  70611. this._currentRefreshId = 1;
  70612. return true;
  70613. }
  70614. this._currentRefreshId++;
  70615. return false;
  70616. };
  70617. ProceduralTexture.prototype.getRenderSize = function () {
  70618. return this._size;
  70619. };
  70620. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70621. if (this._fallbackTextureUsed) {
  70622. return;
  70623. }
  70624. this.releaseInternalTexture();
  70625. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70626. // Update properties
  70627. this._size = size;
  70628. this._generateMipMaps = generateMipMaps;
  70629. };
  70630. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70631. if (this._uniforms.indexOf(uniformName) === -1) {
  70632. this._uniforms.push(uniformName);
  70633. }
  70634. };
  70635. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70636. if (this._samplers.indexOf(name) === -1) {
  70637. this._samplers.push(name);
  70638. }
  70639. this._textures[name] = texture;
  70640. return this;
  70641. };
  70642. ProceduralTexture.prototype.setFloat = function (name, value) {
  70643. this._checkUniform(name);
  70644. this._floats[name] = value;
  70645. return this;
  70646. };
  70647. ProceduralTexture.prototype.setFloats = function (name, value) {
  70648. this._checkUniform(name);
  70649. this._floatsArrays[name] = value;
  70650. return this;
  70651. };
  70652. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70653. this._checkUniform(name);
  70654. this._colors3[name] = value;
  70655. return this;
  70656. };
  70657. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70658. this._checkUniform(name);
  70659. this._colors4[name] = value;
  70660. return this;
  70661. };
  70662. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70663. this._checkUniform(name);
  70664. this._vectors2[name] = value;
  70665. return this;
  70666. };
  70667. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70668. this._checkUniform(name);
  70669. this._vectors3[name] = value;
  70670. return this;
  70671. };
  70672. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70673. this._checkUniform(name);
  70674. this._matrices[name] = value;
  70675. return this;
  70676. };
  70677. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70678. var scene = this.getScene();
  70679. if (!scene) {
  70680. return;
  70681. }
  70682. var engine = this._engine;
  70683. // Render
  70684. engine.enableEffect(this._effect);
  70685. engine.setState(false);
  70686. // Texture
  70687. for (var name in this._textures) {
  70688. this._effect.setTexture(name, this._textures[name]);
  70689. }
  70690. // Float
  70691. for (name in this._floats) {
  70692. this._effect.setFloat(name, this._floats[name]);
  70693. }
  70694. // Floats
  70695. for (name in this._floatsArrays) {
  70696. this._effect.setArray(name, this._floatsArrays[name]);
  70697. }
  70698. // Color3
  70699. for (name in this._colors3) {
  70700. this._effect.setColor3(name, this._colors3[name]);
  70701. }
  70702. // Color4
  70703. for (name in this._colors4) {
  70704. var color = this._colors4[name];
  70705. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70706. }
  70707. // Vector2
  70708. for (name in this._vectors2) {
  70709. this._effect.setVector2(name, this._vectors2[name]);
  70710. }
  70711. // Vector3
  70712. for (name in this._vectors3) {
  70713. this._effect.setVector3(name, this._vectors3[name]);
  70714. }
  70715. // Matrix
  70716. for (name in this._matrices) {
  70717. this._effect.setMatrix(name, this._matrices[name]);
  70718. }
  70719. if (!this._texture) {
  70720. return;
  70721. }
  70722. if (this.isCube) {
  70723. for (var face = 0; face < 6; face++) {
  70724. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70725. // VBOs
  70726. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70727. this._effect.setFloat("face", face);
  70728. // Clear
  70729. engine.clear(scene.clearColor, true, true, true);
  70730. // Draw order
  70731. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70732. // Mipmaps
  70733. if (face === 5) {
  70734. engine.generateMipMapsForCubemap(this._texture);
  70735. }
  70736. }
  70737. }
  70738. else {
  70739. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70740. // VBOs
  70741. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70742. // Clear
  70743. engine.clear(scene.clearColor, true, true, true);
  70744. // Draw order
  70745. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70746. }
  70747. // Unbind
  70748. engine.unBindFramebuffer(this._texture, this.isCube);
  70749. if (this.onGenerated) {
  70750. this.onGenerated();
  70751. }
  70752. };
  70753. ProceduralTexture.prototype.clone = function () {
  70754. var textureSize = this.getSize();
  70755. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70756. // Base texture
  70757. newTexture.hasAlpha = this.hasAlpha;
  70758. newTexture.level = this.level;
  70759. // RenderTarget Texture
  70760. newTexture.coordinatesMode = this.coordinatesMode;
  70761. return newTexture;
  70762. };
  70763. ProceduralTexture.prototype.dispose = function () {
  70764. var scene = this.getScene();
  70765. if (!scene) {
  70766. return;
  70767. }
  70768. var index = scene.proceduralTextures.indexOf(this);
  70769. if (index >= 0) {
  70770. scene.proceduralTextures.splice(index, 1);
  70771. }
  70772. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70773. if (vertexBuffer) {
  70774. vertexBuffer.dispose();
  70775. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70776. }
  70777. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70778. this._indexBuffer = null;
  70779. }
  70780. _super.prototype.dispose.call(this);
  70781. };
  70782. __decorate([
  70783. BABYLON.serialize()
  70784. ], ProceduralTexture.prototype, "_size", void 0);
  70785. __decorate([
  70786. BABYLON.serialize()
  70787. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70788. __decorate([
  70789. BABYLON.serialize()
  70790. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70791. __decorate([
  70792. BABYLON.serialize()
  70793. ], ProceduralTexture.prototype, "refreshRate", null);
  70794. return ProceduralTexture;
  70795. }(BABYLON.Texture));
  70796. BABYLON.ProceduralTexture = ProceduralTexture;
  70797. })(BABYLON || (BABYLON = {}));
  70798. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70799. var BABYLON;
  70800. (function (BABYLON) {
  70801. var CustomProceduralTexture = /** @class */ (function (_super) {
  70802. __extends(CustomProceduralTexture, _super);
  70803. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70804. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70805. _this._animate = true;
  70806. _this._time = 0;
  70807. _this._texturePath = texturePath;
  70808. //Try to load json
  70809. _this.loadJson(texturePath);
  70810. _this.refreshRate = 1;
  70811. return _this;
  70812. }
  70813. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70814. var _this = this;
  70815. var noConfigFile = function () {
  70816. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70817. try {
  70818. _this.setFragment(_this._texturePath);
  70819. }
  70820. catch (ex) {
  70821. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70822. }
  70823. };
  70824. var configFileUrl = jsonUrl + "/config.json";
  70825. var xhr = new XMLHttpRequest();
  70826. xhr.open("GET", configFileUrl, true);
  70827. xhr.addEventListener("load", function () {
  70828. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70829. try {
  70830. _this._config = JSON.parse(xhr.response);
  70831. _this.updateShaderUniforms();
  70832. _this.updateTextures();
  70833. _this.setFragment(_this._texturePath + "/custom");
  70834. _this._animate = _this._config.animate;
  70835. _this.refreshRate = _this._config.refreshrate;
  70836. }
  70837. catch (ex) {
  70838. noConfigFile();
  70839. }
  70840. }
  70841. else {
  70842. noConfigFile();
  70843. }
  70844. }, false);
  70845. xhr.addEventListener("error", function () {
  70846. noConfigFile();
  70847. }, false);
  70848. try {
  70849. xhr.send();
  70850. }
  70851. catch (ex) {
  70852. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70853. }
  70854. };
  70855. CustomProceduralTexture.prototype.isReady = function () {
  70856. if (!_super.prototype.isReady.call(this)) {
  70857. return false;
  70858. }
  70859. for (var name in this._textures) {
  70860. var texture = this._textures[name];
  70861. if (!texture.isReady()) {
  70862. return false;
  70863. }
  70864. }
  70865. return true;
  70866. };
  70867. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70868. var scene = this.getScene();
  70869. if (this._animate && scene) {
  70870. this._time += scene.getAnimationRatio() * 0.03;
  70871. this.updateShaderUniforms();
  70872. }
  70873. _super.prototype.render.call(this, useCameraPostProcess);
  70874. };
  70875. CustomProceduralTexture.prototype.updateTextures = function () {
  70876. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70877. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70878. }
  70879. };
  70880. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70881. if (this._config) {
  70882. for (var j = 0; j < this._config.uniforms.length; j++) {
  70883. var uniform = this._config.uniforms[j];
  70884. switch (uniform.type) {
  70885. case "float":
  70886. this.setFloat(uniform.name, uniform.value);
  70887. break;
  70888. case "color3":
  70889. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70890. break;
  70891. case "color4":
  70892. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70893. break;
  70894. case "vector2":
  70895. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70896. break;
  70897. case "vector3":
  70898. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70899. break;
  70900. }
  70901. }
  70902. }
  70903. this.setFloat("time", this._time);
  70904. };
  70905. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70906. get: function () {
  70907. return this._animate;
  70908. },
  70909. set: function (value) {
  70910. this._animate = value;
  70911. },
  70912. enumerable: true,
  70913. configurable: true
  70914. });
  70915. return CustomProceduralTexture;
  70916. }(BABYLON.ProceduralTexture));
  70917. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70918. })(BABYLON || (BABYLON = {}));
  70919. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70920. var BABYLON;
  70921. (function (BABYLON) {
  70922. var FreeCameraGamepadInput = /** @class */ (function () {
  70923. function FreeCameraGamepadInput() {
  70924. this.gamepadAngularSensibility = 200;
  70925. this.gamepadMoveSensibility = 40;
  70926. // private members
  70927. this._cameraTransform = BABYLON.Matrix.Identity();
  70928. this._deltaTransform = BABYLON.Vector3.Zero();
  70929. this._vector3 = BABYLON.Vector3.Zero();
  70930. this._vector2 = BABYLON.Vector2.Zero();
  70931. }
  70932. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70933. var _this = this;
  70934. var manager = this.camera.getScene().gamepadManager;
  70935. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70936. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70937. // prioritize XBOX gamepads.
  70938. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70939. _this.gamepad = gamepad;
  70940. }
  70941. }
  70942. });
  70943. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70944. if (_this.gamepad === gamepad) {
  70945. _this.gamepad = null;
  70946. }
  70947. });
  70948. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70949. };
  70950. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70951. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70952. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70953. this.gamepad = null;
  70954. };
  70955. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70956. if (this.gamepad && this.gamepad.leftStick) {
  70957. var camera = this.camera;
  70958. var LSValues = this.gamepad.leftStick;
  70959. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70960. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70961. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70962. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70963. var RSValues = this.gamepad.rightStick;
  70964. if (RSValues) {
  70965. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70966. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70967. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70968. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70969. }
  70970. else {
  70971. RSValues = { x: 0, y: 0 };
  70972. }
  70973. if (!camera.rotationQuaternion) {
  70974. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70975. }
  70976. else {
  70977. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70978. }
  70979. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70980. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70981. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70982. camera.cameraDirection.addInPlace(this._deltaTransform);
  70983. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70984. camera.cameraRotation.addInPlace(this._vector2);
  70985. }
  70986. };
  70987. FreeCameraGamepadInput.prototype.getClassName = function () {
  70988. return "FreeCameraGamepadInput";
  70989. };
  70990. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70991. return "gamepad";
  70992. };
  70993. __decorate([
  70994. BABYLON.serialize()
  70995. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70996. __decorate([
  70997. BABYLON.serialize()
  70998. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70999. return FreeCameraGamepadInput;
  71000. }());
  71001. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  71002. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  71003. })(BABYLON || (BABYLON = {}));
  71004. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  71005. var BABYLON;
  71006. (function (BABYLON) {
  71007. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  71008. function ArcRotateCameraGamepadInput() {
  71009. this.gamepadRotationSensibility = 80;
  71010. this.gamepadMoveSensibility = 40;
  71011. }
  71012. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71013. var _this = this;
  71014. var manager = this.camera.getScene().gamepadManager;
  71015. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71016. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71017. // prioritize XBOX gamepads.
  71018. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71019. _this.gamepad = gamepad;
  71020. }
  71021. }
  71022. });
  71023. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71024. if (_this.gamepad === gamepad) {
  71025. _this.gamepad = null;
  71026. }
  71027. });
  71028. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71029. };
  71030. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  71031. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71032. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71033. this.gamepad = null;
  71034. };
  71035. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  71036. if (this.gamepad) {
  71037. var camera = this.camera;
  71038. var RSValues = this.gamepad.rightStick;
  71039. if (RSValues) {
  71040. if (RSValues.x != 0) {
  71041. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  71042. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  71043. camera.inertialAlphaOffset += normalizedRX;
  71044. }
  71045. }
  71046. if (RSValues.y != 0) {
  71047. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  71048. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  71049. camera.inertialBetaOffset += normalizedRY;
  71050. }
  71051. }
  71052. }
  71053. var LSValues = this.gamepad.leftStick;
  71054. if (LSValues && LSValues.y != 0) {
  71055. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71056. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  71057. this.camera.inertialRadiusOffset -= normalizedLY;
  71058. }
  71059. }
  71060. }
  71061. };
  71062. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  71063. return "ArcRotateCameraGamepadInput";
  71064. };
  71065. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  71066. return "gamepad";
  71067. };
  71068. __decorate([
  71069. BABYLON.serialize()
  71070. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  71071. __decorate([
  71072. BABYLON.serialize()
  71073. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71074. return ArcRotateCameraGamepadInput;
  71075. }());
  71076. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  71077. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  71078. })(BABYLON || (BABYLON = {}));
  71079. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  71080. var BABYLON;
  71081. (function (BABYLON) {
  71082. var GamepadManager = /** @class */ (function () {
  71083. function GamepadManager(_scene) {
  71084. var _this = this;
  71085. this._scene = _scene;
  71086. this._babylonGamepads = [];
  71087. this._oneGamepadConnected = false;
  71088. this._isMonitoring = false;
  71089. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  71090. if (!BABYLON.Tools.IsWindowObjectExist()) {
  71091. this._gamepadEventSupported = false;
  71092. }
  71093. else {
  71094. this._gamepadEventSupported = 'GamepadEvent' in window;
  71095. this._gamepadSupport = (navigator.getGamepads ||
  71096. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  71097. }
  71098. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  71099. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  71100. for (var i in _this._babylonGamepads) {
  71101. var gamepad = _this._babylonGamepads[i];
  71102. if (gamepad && gamepad._isConnected) {
  71103. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  71104. }
  71105. }
  71106. });
  71107. this._onGamepadConnectedEvent = function (evt) {
  71108. var gamepad = evt.gamepad;
  71109. if (gamepad.index in _this._babylonGamepads) {
  71110. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71111. return;
  71112. }
  71113. }
  71114. var newGamepad;
  71115. if (_this._babylonGamepads[gamepad.index]) {
  71116. newGamepad = _this._babylonGamepads[gamepad.index];
  71117. newGamepad.browserGamepad = gamepad;
  71118. newGamepad._isConnected = true;
  71119. }
  71120. else {
  71121. newGamepad = _this._addNewGamepad(gamepad);
  71122. }
  71123. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71124. _this._startMonitoringGamepads();
  71125. };
  71126. this._onGamepadDisconnectedEvent = function (evt) {
  71127. var gamepad = evt.gamepad;
  71128. // Remove the gamepad from the list of gamepads to monitor.
  71129. for (var i in _this._babylonGamepads) {
  71130. if (_this._babylonGamepads[i].index === gamepad.index) {
  71131. var disconnectedGamepad = _this._babylonGamepads[i];
  71132. disconnectedGamepad._isConnected = false;
  71133. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71134. break;
  71135. }
  71136. }
  71137. };
  71138. if (this._gamepadSupport) {
  71139. //first add already-connected gamepads
  71140. this._updateGamepadObjects();
  71141. if (this._babylonGamepads.length) {
  71142. this._startMonitoringGamepads();
  71143. }
  71144. // Checking if the gamepad connected event is supported (like in Firefox)
  71145. if (this._gamepadEventSupported) {
  71146. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71147. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71148. }
  71149. else {
  71150. this._startMonitoringGamepads();
  71151. }
  71152. }
  71153. }
  71154. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71155. get: function () {
  71156. return this._babylonGamepads;
  71157. },
  71158. enumerable: true,
  71159. configurable: true
  71160. });
  71161. GamepadManager.prototype.getGamepadByType = function (type) {
  71162. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71163. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71164. var gamepad = _a[_i];
  71165. if (gamepad && gamepad.type === type) {
  71166. return gamepad;
  71167. }
  71168. }
  71169. return null;
  71170. };
  71171. GamepadManager.prototype.dispose = function () {
  71172. if (this._gamepadEventSupported) {
  71173. if (this._onGamepadConnectedEvent) {
  71174. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71175. }
  71176. if (this._onGamepadDisconnectedEvent) {
  71177. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71178. }
  71179. this._onGamepadConnectedEvent = null;
  71180. this._onGamepadDisconnectedEvent = null;
  71181. }
  71182. this._babylonGamepads.forEach(function (gamepad) {
  71183. gamepad.dispose();
  71184. });
  71185. this.onGamepadConnectedObservable.clear();
  71186. this.onGamepadDisconnectedObservable.clear();
  71187. this._oneGamepadConnected = false;
  71188. this._stopMonitoringGamepads();
  71189. this._babylonGamepads = [];
  71190. };
  71191. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71192. if (!this._oneGamepadConnected) {
  71193. this._oneGamepadConnected = true;
  71194. }
  71195. var newGamepad;
  71196. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71197. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71198. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71199. }
  71200. // if pose is supported, use the (WebVR) pose enabled controller
  71201. else if (gamepad.pose) {
  71202. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71203. }
  71204. else {
  71205. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71206. }
  71207. this._babylonGamepads[newGamepad.index] = newGamepad;
  71208. return newGamepad;
  71209. };
  71210. GamepadManager.prototype._startMonitoringGamepads = function () {
  71211. if (!this._isMonitoring) {
  71212. this._isMonitoring = true;
  71213. //back-comp
  71214. if (!this._scene) {
  71215. this._checkGamepadsStatus();
  71216. }
  71217. }
  71218. };
  71219. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71220. this._isMonitoring = false;
  71221. };
  71222. GamepadManager.prototype._checkGamepadsStatus = function () {
  71223. var _this = this;
  71224. // Hack to be compatible Chrome
  71225. this._updateGamepadObjects();
  71226. for (var i in this._babylonGamepads) {
  71227. var gamepad = this._babylonGamepads[i];
  71228. if (!gamepad || !gamepad.isConnected) {
  71229. continue;
  71230. }
  71231. gamepad.update();
  71232. }
  71233. if (this._isMonitoring && !this._scene) {
  71234. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71235. }
  71236. };
  71237. // This function is called only on Chrome, which does not properly support
  71238. // connection/disconnection events and forces you to recopy again the gamepad object
  71239. GamepadManager.prototype._updateGamepadObjects = function () {
  71240. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71241. for (var i = 0; i < gamepads.length; i++) {
  71242. var gamepad = gamepads[i];
  71243. if (gamepad) {
  71244. if (!this._babylonGamepads[gamepad.index]) {
  71245. var newGamepad = this._addNewGamepad(gamepad);
  71246. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71247. }
  71248. else {
  71249. // Forced to copy again this object for Chrome for unknown reason
  71250. this._babylonGamepads[i].browserGamepad = gamepad;
  71251. if (!this._babylonGamepads[i].isConnected) {
  71252. this._babylonGamepads[i]._isConnected = true;
  71253. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71254. }
  71255. }
  71256. }
  71257. }
  71258. };
  71259. return GamepadManager;
  71260. }());
  71261. BABYLON.GamepadManager = GamepadManager;
  71262. })(BABYLON || (BABYLON = {}));
  71263. //# sourceMappingURL=babylon.gamepadManager.js.map
  71264. var BABYLON;
  71265. (function (BABYLON) {
  71266. var StickValues = /** @class */ (function () {
  71267. function StickValues(x, y) {
  71268. this.x = x;
  71269. this.y = y;
  71270. }
  71271. return StickValues;
  71272. }());
  71273. BABYLON.StickValues = StickValues;
  71274. var Gamepad = /** @class */ (function () {
  71275. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71276. if (leftStickX === void 0) { leftStickX = 0; }
  71277. if (leftStickY === void 0) { leftStickY = 1; }
  71278. if (rightStickX === void 0) { rightStickX = 2; }
  71279. if (rightStickY === void 0) { rightStickY = 3; }
  71280. this.id = id;
  71281. this.index = index;
  71282. this.browserGamepad = browserGamepad;
  71283. this._isConnected = true;
  71284. this._invertLeftStickY = false;
  71285. this.type = Gamepad.GAMEPAD;
  71286. this._leftStickAxisX = leftStickX;
  71287. this._leftStickAxisY = leftStickY;
  71288. this._rightStickAxisX = rightStickX;
  71289. this._rightStickAxisY = rightStickY;
  71290. if (this.browserGamepad.axes.length >= 2) {
  71291. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71292. }
  71293. if (this.browserGamepad.axes.length >= 4) {
  71294. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71295. }
  71296. }
  71297. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71298. get: function () {
  71299. return this._isConnected;
  71300. },
  71301. enumerable: true,
  71302. configurable: true
  71303. });
  71304. Gamepad.prototype.onleftstickchanged = function (callback) {
  71305. this._onleftstickchanged = callback;
  71306. };
  71307. Gamepad.prototype.onrightstickchanged = function (callback) {
  71308. this._onrightstickchanged = callback;
  71309. };
  71310. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71311. get: function () {
  71312. return this._leftStick;
  71313. },
  71314. set: function (newValues) {
  71315. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71316. this._onleftstickchanged(newValues);
  71317. }
  71318. this._leftStick = newValues;
  71319. },
  71320. enumerable: true,
  71321. configurable: true
  71322. });
  71323. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71324. get: function () {
  71325. return this._rightStick;
  71326. },
  71327. set: function (newValues) {
  71328. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71329. this._onrightstickchanged(newValues);
  71330. }
  71331. this._rightStick = newValues;
  71332. },
  71333. enumerable: true,
  71334. configurable: true
  71335. });
  71336. Gamepad.prototype.update = function () {
  71337. if (this._leftStick) {
  71338. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71339. if (this._invertLeftStickY) {
  71340. this.leftStick.y *= -1;
  71341. }
  71342. }
  71343. if (this._rightStick) {
  71344. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71345. }
  71346. };
  71347. Gamepad.prototype.dispose = function () {
  71348. };
  71349. Gamepad.GAMEPAD = 0;
  71350. Gamepad.GENERIC = 1;
  71351. Gamepad.XBOX = 2;
  71352. Gamepad.POSE_ENABLED = 3;
  71353. return Gamepad;
  71354. }());
  71355. BABYLON.Gamepad = Gamepad;
  71356. var GenericPad = /** @class */ (function (_super) {
  71357. __extends(GenericPad, _super);
  71358. function GenericPad(id, index, browserGamepad) {
  71359. var _this = _super.call(this, id, index, browserGamepad) || this;
  71360. _this.onButtonDownObservable = new BABYLON.Observable();
  71361. _this.onButtonUpObservable = new BABYLON.Observable();
  71362. _this.type = Gamepad.GENERIC;
  71363. _this._buttons = new Array(browserGamepad.buttons.length);
  71364. return _this;
  71365. }
  71366. GenericPad.prototype.onbuttondown = function (callback) {
  71367. this._onbuttondown = callback;
  71368. };
  71369. GenericPad.prototype.onbuttonup = function (callback) {
  71370. this._onbuttonup = callback;
  71371. };
  71372. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71373. if (newValue !== currentValue) {
  71374. if (newValue === 1) {
  71375. if (this._onbuttondown) {
  71376. this._onbuttondown(buttonIndex);
  71377. }
  71378. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71379. }
  71380. if (newValue === 0) {
  71381. if (this._onbuttonup) {
  71382. this._onbuttonup(buttonIndex);
  71383. }
  71384. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71385. }
  71386. }
  71387. return newValue;
  71388. };
  71389. GenericPad.prototype.update = function () {
  71390. _super.prototype.update.call(this);
  71391. for (var index = 0; index < this._buttons.length; index++) {
  71392. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71393. }
  71394. };
  71395. GenericPad.prototype.dispose = function () {
  71396. _super.prototype.dispose.call(this);
  71397. this.onButtonDownObservable.clear();
  71398. this.onButtonUpObservable.clear();
  71399. };
  71400. return GenericPad;
  71401. }(Gamepad));
  71402. BABYLON.GenericPad = GenericPad;
  71403. })(BABYLON || (BABYLON = {}));
  71404. //# sourceMappingURL=babylon.gamepad.js.map
  71405. var BABYLON;
  71406. (function (BABYLON) {
  71407. /**
  71408. * Defines supported buttons for XBox360 compatible gamepads
  71409. */
  71410. var Xbox360Button;
  71411. (function (Xbox360Button) {
  71412. /** A */
  71413. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71414. /** B */
  71415. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71416. /** X */
  71417. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71418. /** Y */
  71419. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71420. /** Start */
  71421. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71422. /** Back */
  71423. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71424. /** Left button */
  71425. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71426. /** Right button */
  71427. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71428. /** Left stick */
  71429. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71430. /** Right stick */
  71431. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71432. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71433. /** Defines values for XBox360 DPad */
  71434. var Xbox360Dpad;
  71435. (function (Xbox360Dpad) {
  71436. /** Up */
  71437. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71438. /** Down */
  71439. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71440. /** Left */
  71441. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71442. /** Right */
  71443. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71444. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71445. /**
  71446. * Defines a XBox360 gamepad
  71447. */
  71448. var Xbox360Pad = /** @class */ (function (_super) {
  71449. __extends(Xbox360Pad, _super);
  71450. /**
  71451. * Creates a new XBox360 gamepad object
  71452. * @param id defines the id of this gamepad
  71453. * @param index defines its index
  71454. * @param gamepad defines the internal HTML gamepad object
  71455. * @param xboxOne defines if it is a XBox One gamepad
  71456. */
  71457. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71458. if (xboxOne === void 0) { xboxOne = false; }
  71459. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71460. _this._leftTrigger = 0;
  71461. _this._rightTrigger = 0;
  71462. /** Observable raised when a button is pressed */
  71463. _this.onButtonDownObservable = new BABYLON.Observable();
  71464. /** Observable raised when a button is released */
  71465. _this.onButtonUpObservable = new BABYLON.Observable();
  71466. /** Observable raised when a pad is pressed */
  71467. _this.onPadDownObservable = new BABYLON.Observable();
  71468. /** Observable raised when a pad is released */
  71469. _this.onPadUpObservable = new BABYLON.Observable();
  71470. _this._buttonA = 0;
  71471. _this._buttonB = 0;
  71472. _this._buttonX = 0;
  71473. _this._buttonY = 0;
  71474. _this._buttonBack = 0;
  71475. _this._buttonStart = 0;
  71476. _this._buttonLB = 0;
  71477. _this._buttonRB = 0;
  71478. _this._buttonLeftStick = 0;
  71479. _this._buttonRightStick = 0;
  71480. _this._dPadUp = 0;
  71481. _this._dPadDown = 0;
  71482. _this._dPadLeft = 0;
  71483. _this._dPadRight = 0;
  71484. _this._isXboxOnePad = false;
  71485. _this.type = BABYLON.Gamepad.XBOX;
  71486. _this._isXboxOnePad = xboxOne;
  71487. return _this;
  71488. }
  71489. /**
  71490. * Defines the callback to call when left trigger is pressed
  71491. * @param callback defines the callback to use
  71492. */
  71493. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71494. this._onlefttriggerchanged = callback;
  71495. };
  71496. /**
  71497. * Defines the callback to call when right trigger is pressed
  71498. * @param callback defines the callback to use
  71499. */
  71500. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71501. this._onrighttriggerchanged = callback;
  71502. };
  71503. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71504. /**
  71505. * Gets or sets left trigger value
  71506. */
  71507. get: function () {
  71508. return this._leftTrigger;
  71509. },
  71510. set: function (newValue) {
  71511. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71512. this._onlefttriggerchanged(newValue);
  71513. }
  71514. this._leftTrigger = newValue;
  71515. },
  71516. enumerable: true,
  71517. configurable: true
  71518. });
  71519. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71520. /**
  71521. * Gets or sets right trigger value
  71522. */
  71523. get: function () {
  71524. return this._rightTrigger;
  71525. },
  71526. set: function (newValue) {
  71527. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71528. this._onrighttriggerchanged(newValue);
  71529. }
  71530. this._rightTrigger = newValue;
  71531. },
  71532. enumerable: true,
  71533. configurable: true
  71534. });
  71535. /**
  71536. * Defines the callback to call when a button is pressed
  71537. * @param callback defines the callback to use
  71538. */
  71539. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71540. this._onbuttondown = callback;
  71541. };
  71542. /**
  71543. * Defines the callback to call when a button is released
  71544. * @param callback defines the callback to use
  71545. */
  71546. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71547. this._onbuttonup = callback;
  71548. };
  71549. /**
  71550. * Defines the callback to call when a pad is pressed
  71551. * @param callback defines the callback to use
  71552. */
  71553. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71554. this._ondpaddown = callback;
  71555. };
  71556. /**
  71557. * Defines the callback to call when a pad is released
  71558. * @param callback defines the callback to use
  71559. */
  71560. Xbox360Pad.prototype.ondpadup = function (callback) {
  71561. this._ondpadup = callback;
  71562. };
  71563. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71564. if (newValue !== currentValue) {
  71565. if (newValue === 1) {
  71566. if (this._onbuttondown) {
  71567. this._onbuttondown(buttonType);
  71568. }
  71569. this.onButtonDownObservable.notifyObservers(buttonType);
  71570. }
  71571. if (newValue === 0) {
  71572. if (this._onbuttonup) {
  71573. this._onbuttonup(buttonType);
  71574. }
  71575. this.onButtonUpObservable.notifyObservers(buttonType);
  71576. }
  71577. }
  71578. return newValue;
  71579. };
  71580. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71581. if (newValue !== currentValue) {
  71582. if (newValue === 1) {
  71583. if (this._ondpaddown) {
  71584. this._ondpaddown(buttonType);
  71585. }
  71586. this.onPadDownObservable.notifyObservers(buttonType);
  71587. }
  71588. if (newValue === 0) {
  71589. if (this._ondpadup) {
  71590. this._ondpadup(buttonType);
  71591. }
  71592. this.onPadUpObservable.notifyObservers(buttonType);
  71593. }
  71594. }
  71595. return newValue;
  71596. };
  71597. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71598. /** Gets or sets value of A button */
  71599. get: function () {
  71600. return this._buttonA;
  71601. },
  71602. set: function (value) {
  71603. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71604. },
  71605. enumerable: true,
  71606. configurable: true
  71607. });
  71608. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71609. /** Gets or sets value of B button */
  71610. get: function () {
  71611. return this._buttonB;
  71612. },
  71613. set: function (value) {
  71614. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71615. },
  71616. enumerable: true,
  71617. configurable: true
  71618. });
  71619. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71620. /** Gets or sets value of X button */
  71621. get: function () {
  71622. return this._buttonX;
  71623. },
  71624. set: function (value) {
  71625. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71626. },
  71627. enumerable: true,
  71628. configurable: true
  71629. });
  71630. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71631. /** Gets or sets value of Y button */
  71632. get: function () {
  71633. return this._buttonY;
  71634. },
  71635. set: function (value) {
  71636. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71637. },
  71638. enumerable: true,
  71639. configurable: true
  71640. });
  71641. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71642. /** Gets or sets value of Start button */
  71643. get: function () {
  71644. return this._buttonStart;
  71645. },
  71646. set: function (value) {
  71647. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71648. },
  71649. enumerable: true,
  71650. configurable: true
  71651. });
  71652. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71653. /** Gets or sets value of Back button */
  71654. get: function () {
  71655. return this._buttonBack;
  71656. },
  71657. set: function (value) {
  71658. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71659. },
  71660. enumerable: true,
  71661. configurable: true
  71662. });
  71663. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71664. /** Gets or sets value of Left button */
  71665. get: function () {
  71666. return this._buttonLB;
  71667. },
  71668. set: function (value) {
  71669. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71670. },
  71671. enumerable: true,
  71672. configurable: true
  71673. });
  71674. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71675. /** Gets or sets value of Right button */
  71676. get: function () {
  71677. return this._buttonRB;
  71678. },
  71679. set: function (value) {
  71680. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71681. },
  71682. enumerable: true,
  71683. configurable: true
  71684. });
  71685. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71686. /** Gets or sets value of left stick */
  71687. get: function () {
  71688. return this._buttonLeftStick;
  71689. },
  71690. set: function (value) {
  71691. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71692. },
  71693. enumerable: true,
  71694. configurable: true
  71695. });
  71696. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71697. /** Gets or sets value of right stick */
  71698. get: function () {
  71699. return this._buttonRightStick;
  71700. },
  71701. set: function (value) {
  71702. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71703. },
  71704. enumerable: true,
  71705. configurable: true
  71706. });
  71707. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71708. /** Gets or sets value of DPad up */
  71709. get: function () {
  71710. return this._dPadUp;
  71711. },
  71712. set: function (value) {
  71713. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71714. },
  71715. enumerable: true,
  71716. configurable: true
  71717. });
  71718. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71719. /** Gets or sets value of DPad down */
  71720. get: function () {
  71721. return this._dPadDown;
  71722. },
  71723. set: function (value) {
  71724. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71725. },
  71726. enumerable: true,
  71727. configurable: true
  71728. });
  71729. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71730. /** Gets or sets value of DPad left */
  71731. get: function () {
  71732. return this._dPadLeft;
  71733. },
  71734. set: function (value) {
  71735. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71736. },
  71737. enumerable: true,
  71738. configurable: true
  71739. });
  71740. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71741. /** Gets or sets value of DPad right */
  71742. get: function () {
  71743. return this._dPadRight;
  71744. },
  71745. set: function (value) {
  71746. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71747. },
  71748. enumerable: true,
  71749. configurable: true
  71750. });
  71751. /**
  71752. * Force the gamepad to synchronize with device values
  71753. */
  71754. Xbox360Pad.prototype.update = function () {
  71755. _super.prototype.update.call(this);
  71756. if (this._isXboxOnePad) {
  71757. this.buttonA = this.browserGamepad.buttons[0].value;
  71758. this.buttonB = this.browserGamepad.buttons[1].value;
  71759. this.buttonX = this.browserGamepad.buttons[2].value;
  71760. this.buttonY = this.browserGamepad.buttons[3].value;
  71761. this.buttonLB = this.browserGamepad.buttons[4].value;
  71762. this.buttonRB = this.browserGamepad.buttons[5].value;
  71763. this.leftTrigger = this.browserGamepad.axes[2];
  71764. this.rightTrigger = this.browserGamepad.axes[5];
  71765. this.buttonBack = this.browserGamepad.buttons[9].value;
  71766. this.buttonStart = this.browserGamepad.buttons[8].value;
  71767. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71768. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71769. this.dPadUp = this.browserGamepad.buttons[11].value;
  71770. this.dPadDown = this.browserGamepad.buttons[12].value;
  71771. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71772. this.dPadRight = this.browserGamepad.buttons[14].value;
  71773. }
  71774. else {
  71775. this.buttonA = this.browserGamepad.buttons[0].value;
  71776. this.buttonB = this.browserGamepad.buttons[1].value;
  71777. this.buttonX = this.browserGamepad.buttons[2].value;
  71778. this.buttonY = this.browserGamepad.buttons[3].value;
  71779. this.buttonLB = this.browserGamepad.buttons[4].value;
  71780. this.buttonRB = this.browserGamepad.buttons[5].value;
  71781. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71782. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71783. this.buttonBack = this.browserGamepad.buttons[8].value;
  71784. this.buttonStart = this.browserGamepad.buttons[9].value;
  71785. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71786. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71787. this.dPadUp = this.browserGamepad.buttons[12].value;
  71788. this.dPadDown = this.browserGamepad.buttons[13].value;
  71789. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71790. this.dPadRight = this.browserGamepad.buttons[15].value;
  71791. }
  71792. };
  71793. Xbox360Pad.prototype.dispose = function () {
  71794. _super.prototype.dispose.call(this);
  71795. this.onButtonDownObservable.clear();
  71796. this.onButtonUpObservable.clear();
  71797. this.onPadDownObservable.clear();
  71798. this.onPadUpObservable.clear();
  71799. };
  71800. return Xbox360Pad;
  71801. }(BABYLON.Gamepad));
  71802. BABYLON.Xbox360Pad = Xbox360Pad;
  71803. })(BABYLON || (BABYLON = {}));
  71804. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71805. var BABYLON;
  71806. (function (BABYLON) {
  71807. /**
  71808. * Defines the types of pose enabled controllers that are supported
  71809. */
  71810. var PoseEnabledControllerType;
  71811. (function (PoseEnabledControllerType) {
  71812. /**
  71813. * HTC Vive
  71814. */
  71815. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71816. /**
  71817. * Oculus Rift
  71818. */
  71819. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71820. /**
  71821. * Windows mixed reality
  71822. */
  71823. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71824. /**
  71825. * Samsung gear VR
  71826. */
  71827. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71828. /**
  71829. * Google Daydream
  71830. */
  71831. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71832. /**
  71833. * Generic
  71834. */
  71835. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71836. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71837. /**
  71838. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71839. */
  71840. var PoseEnabledControllerHelper = /** @class */ (function () {
  71841. function PoseEnabledControllerHelper() {
  71842. }
  71843. /**
  71844. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71845. * @param vrGamepad the gamepad to initialized
  71846. * @returns a vr controller of the type the gamepad identified as
  71847. */
  71848. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71849. // Oculus Touch
  71850. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71851. return new BABYLON.OculusTouchController(vrGamepad);
  71852. }
  71853. // Windows Mixed Reality controllers
  71854. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71855. return new BABYLON.WindowsMotionController(vrGamepad);
  71856. }
  71857. // HTC Vive
  71858. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71859. return new BABYLON.ViveController(vrGamepad);
  71860. }
  71861. // Samsung/Oculus Gear VR or Oculus Go
  71862. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71863. return new BABYLON.GearVRController(vrGamepad);
  71864. }
  71865. // Google Daydream
  71866. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71867. return new BABYLON.DaydreamController(vrGamepad);
  71868. }
  71869. // Generic
  71870. else {
  71871. return new BABYLON.GenericController(vrGamepad);
  71872. }
  71873. };
  71874. return PoseEnabledControllerHelper;
  71875. }());
  71876. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71877. /**
  71878. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71879. */
  71880. var PoseEnabledController = /** @class */ (function (_super) {
  71881. __extends(PoseEnabledController, _super);
  71882. /**
  71883. * Creates a new PoseEnabledController from a gamepad
  71884. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71885. */
  71886. function PoseEnabledController(browserGamepad) {
  71887. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71888. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71889. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71890. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71891. /**
  71892. * The device position in babylon space
  71893. */
  71894. _this.devicePosition = BABYLON.Vector3.Zero();
  71895. /**
  71896. * The device rotation in babylon space
  71897. */
  71898. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71899. /**
  71900. * The scale factor of the device in babylon space
  71901. */
  71902. _this.deviceScaleFactor = 1;
  71903. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71904. /**
  71905. * Internal, matrix used to convert room space to babylon space
  71906. */
  71907. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71908. /**
  71909. * Node to be used when casting a ray from the controller
  71910. */
  71911. _this._pointingPoseNode = null;
  71912. _this._workingMatrix = BABYLON.Matrix.Identity();
  71913. /**
  71914. * @hidden
  71915. */
  71916. _this._meshAttachedObservable = new BABYLON.Observable();
  71917. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71918. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71919. _this.position = BABYLON.Vector3.Zero();
  71920. _this.rotationQuaternion = new BABYLON.Quaternion();
  71921. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71922. _this._calculatedRotation = new BABYLON.Quaternion();
  71923. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71924. return _this;
  71925. }
  71926. /**
  71927. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71928. */
  71929. PoseEnabledController.prototype.update = function () {
  71930. _super.prototype.update.call(this);
  71931. this._updatePoseAndMesh();
  71932. };
  71933. /**
  71934. * Updates only the pose device and mesh without doing any button event checking
  71935. */
  71936. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71937. var pose = this.browserGamepad.pose;
  71938. this.updateFromDevice(pose);
  71939. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71940. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71941. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71942. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71943. if (this._mesh) {
  71944. this._mesh.position.copyFrom(this.devicePosition);
  71945. if (this._mesh.rotationQuaternion) {
  71946. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71947. }
  71948. }
  71949. };
  71950. /**
  71951. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71952. * @param poseData raw pose fromthe device
  71953. */
  71954. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71955. if (poseData) {
  71956. this.rawPose = poseData;
  71957. if (poseData.position) {
  71958. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71959. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71960. this._deviceRoomPosition.z *= -1;
  71961. }
  71962. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71963. this._calculatedPosition.addInPlace(this.position);
  71964. }
  71965. var pose = this.rawPose;
  71966. if (poseData.orientation && pose.orientation) {
  71967. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71968. if (this._mesh) {
  71969. if (this._mesh.getScene().useRightHandedSystem) {
  71970. this._deviceRoomRotationQuaternion.z *= -1;
  71971. this._deviceRoomRotationQuaternion.w *= -1;
  71972. }
  71973. else {
  71974. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71975. }
  71976. }
  71977. // if the camera is set, rotate to the camera's rotation
  71978. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71979. }
  71980. }
  71981. };
  71982. /**
  71983. * Attaches a mesh to the controller
  71984. * @param mesh the mesh to be attached
  71985. */
  71986. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71987. if (this._mesh) {
  71988. this._mesh.parent = null;
  71989. }
  71990. this._mesh = mesh;
  71991. if (this._poseControlledCamera) {
  71992. this._mesh.parent = this._poseControlledCamera;
  71993. }
  71994. if (!this._mesh.rotationQuaternion) {
  71995. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71996. }
  71997. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  71998. this._updatePoseAndMesh();
  71999. if (this._pointingPoseNode) {
  72000. var parents = [];
  72001. var obj = this._pointingPoseNode;
  72002. while (obj.parent) {
  72003. parents.push(obj.parent);
  72004. obj = obj.parent;
  72005. }
  72006. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  72007. }
  72008. this._meshAttachedObservable.notifyObservers(mesh);
  72009. };
  72010. /**
  72011. * Attaches the controllers mesh to a camera
  72012. * @param camera the camera the mesh should be attached to
  72013. */
  72014. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  72015. this._poseControlledCamera = camera;
  72016. if (this._mesh) {
  72017. this._mesh.parent = this._poseControlledCamera;
  72018. }
  72019. };
  72020. /**
  72021. * Disposes of the controller
  72022. */
  72023. PoseEnabledController.prototype.dispose = function () {
  72024. if (this._mesh) {
  72025. this._mesh.dispose();
  72026. }
  72027. this._mesh = null;
  72028. _super.prototype.dispose.call(this);
  72029. };
  72030. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  72031. /**
  72032. * The mesh that is attached to the controller
  72033. */
  72034. get: function () {
  72035. return this._mesh;
  72036. },
  72037. enumerable: true,
  72038. configurable: true
  72039. });
  72040. /**
  72041. * Gets the ray of the controller in the direction the controller is pointing
  72042. * @param length the length the resulting ray should be
  72043. * @returns a ray in the direction the controller is pointing
  72044. */
  72045. PoseEnabledController.prototype.getForwardRay = function (length) {
  72046. if (length === void 0) { length = 100; }
  72047. if (!this.mesh) {
  72048. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  72049. }
  72050. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  72051. var origin = m.getTranslation();
  72052. var forward = new BABYLON.Vector3(0, 0, -1);
  72053. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72054. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72055. return new BABYLON.Ray(origin, direction, length);
  72056. };
  72057. /**
  72058. * Name of the child mesh that can be used to cast a ray from the controller
  72059. */
  72060. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  72061. return PoseEnabledController;
  72062. }(BABYLON.Gamepad));
  72063. BABYLON.PoseEnabledController = PoseEnabledController;
  72064. })(BABYLON || (BABYLON = {}));
  72065. //# sourceMappingURL=babylon.poseEnabledController.js.map
  72066. var BABYLON;
  72067. (function (BABYLON) {
  72068. /**
  72069. * Defines the WebVRController object that represents controllers tracked in 3D space
  72070. */
  72071. var WebVRController = /** @class */ (function (_super) {
  72072. __extends(WebVRController, _super);
  72073. /**
  72074. * Creates a new WebVRController from a gamepad
  72075. * @param vrGamepad the gamepad that the WebVRController should be created from
  72076. */
  72077. function WebVRController(vrGamepad) {
  72078. var _this = _super.call(this, vrGamepad) || this;
  72079. // Observables
  72080. /**
  72081. * Fired when the trigger state has changed
  72082. */
  72083. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  72084. /**
  72085. * Fired when the main button state has changed
  72086. */
  72087. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  72088. /**
  72089. * Fired when the secondary button state has changed
  72090. */
  72091. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  72092. /**
  72093. * Fired when the pad state has changed
  72094. */
  72095. _this.onPadStateChangedObservable = new BABYLON.Observable();
  72096. /**
  72097. * Fired when controllers stick values have changed
  72098. */
  72099. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  72100. /**
  72101. * X and Y axis corrisponding to the controllers joystick
  72102. */
  72103. _this.pad = { x: 0, y: 0 };
  72104. // avoid GC, store state in a tmp object
  72105. _this._changes = {
  72106. pressChanged: false,
  72107. touchChanged: false,
  72108. valueChanged: false,
  72109. changed: false
  72110. };
  72111. _this._buttons = new Array(vrGamepad.buttons.length);
  72112. _this.hand = vrGamepad.hand;
  72113. return _this;
  72114. }
  72115. /**
  72116. * Fired when a controller button's state has changed
  72117. * @param callback the callback containing the button that was modified
  72118. */
  72119. WebVRController.prototype.onButtonStateChange = function (callback) {
  72120. this._onButtonStateChange = callback;
  72121. };
  72122. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72123. /**
  72124. * The default controller model for the controller
  72125. */
  72126. get: function () {
  72127. return this._defaultModel;
  72128. },
  72129. enumerable: true,
  72130. configurable: true
  72131. });
  72132. /**
  72133. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72134. */
  72135. WebVRController.prototype.update = function () {
  72136. _super.prototype.update.call(this);
  72137. for (var index = 0; index < this._buttons.length; index++) {
  72138. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72139. }
  72140. ;
  72141. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72142. this.pad.x = this.leftStick.x;
  72143. this.pad.y = this.leftStick.y;
  72144. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72145. }
  72146. };
  72147. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72148. if (!newState) {
  72149. newState = {
  72150. pressed: false,
  72151. touched: false,
  72152. value: 0
  72153. };
  72154. }
  72155. if (!currentState) {
  72156. this._buttons[buttonIndex] = {
  72157. pressed: newState.pressed,
  72158. touched: newState.touched,
  72159. value: newState.value
  72160. };
  72161. return;
  72162. }
  72163. this._checkChanges(newState, currentState);
  72164. if (this._changes.changed) {
  72165. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72166. this._handleButtonChange(buttonIndex, newState, this._changes);
  72167. }
  72168. this._buttons[buttonIndex].pressed = newState.pressed;
  72169. this._buttons[buttonIndex].touched = newState.touched;
  72170. // oculus triggers are never 0, thou not touched.
  72171. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72172. };
  72173. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72174. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72175. this._changes.touchChanged = newState.touched !== currentState.touched;
  72176. this._changes.valueChanged = newState.value !== currentState.value;
  72177. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72178. return this._changes;
  72179. };
  72180. /**
  72181. * Disposes of th webVRCOntroller
  72182. */
  72183. WebVRController.prototype.dispose = function () {
  72184. _super.prototype.dispose.call(this);
  72185. this.onTriggerStateChangedObservable.clear();
  72186. this.onMainButtonStateChangedObservable.clear();
  72187. this.onSecondaryButtonStateChangedObservable.clear();
  72188. this.onPadStateChangedObservable.clear();
  72189. this.onPadValuesChangedObservable.clear();
  72190. };
  72191. return WebVRController;
  72192. }(BABYLON.PoseEnabledController));
  72193. BABYLON.WebVRController = WebVRController;
  72194. })(BABYLON || (BABYLON = {}));
  72195. //# sourceMappingURL=babylon.webVRController.js.map
  72196. var BABYLON;
  72197. (function (BABYLON) {
  72198. /**
  72199. * Oculus Touch Controller
  72200. */
  72201. var OculusTouchController = /** @class */ (function (_super) {
  72202. __extends(OculusTouchController, _super);
  72203. /**
  72204. * Creates a new OculusTouchController from a gamepad
  72205. * @param vrGamepad the gamepad that the controller should be created from
  72206. */
  72207. function OculusTouchController(vrGamepad) {
  72208. var _this = _super.call(this, vrGamepad) || this;
  72209. /**
  72210. * Fired when the secondary trigger on this controller is modified
  72211. */
  72212. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72213. /**
  72214. * Fired when the thumb rest on this controller is modified
  72215. */
  72216. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72217. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72218. return _this;
  72219. }
  72220. /**
  72221. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72222. * @param scene scene in which to add meshes
  72223. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72224. */
  72225. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72226. var _this = this;
  72227. var meshName;
  72228. // Hand
  72229. if (this.hand === 'left') {
  72230. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72231. }
  72232. else { // Right is the default if no hand is specified
  72233. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72234. }
  72235. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72236. /*
  72237. Parent Mesh name: oculus_touch_left
  72238. - body
  72239. - trigger
  72240. - thumbstick
  72241. - grip
  72242. - button_y
  72243. - button_x
  72244. - button_enter
  72245. */
  72246. _this._defaultModel = newMeshes[1];
  72247. _this.attachToMesh(_this._defaultModel);
  72248. if (meshLoaded) {
  72249. meshLoaded(_this._defaultModel);
  72250. }
  72251. });
  72252. };
  72253. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72254. /**
  72255. * Fired when the A button on this controller is modified
  72256. */
  72257. get: function () {
  72258. if (this.hand === 'right') {
  72259. return this.onMainButtonStateChangedObservable;
  72260. }
  72261. else {
  72262. throw new Error('No A button on left hand');
  72263. }
  72264. },
  72265. enumerable: true,
  72266. configurable: true
  72267. });
  72268. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72269. /**
  72270. * Fired when the B button on this controller is modified
  72271. */
  72272. get: function () {
  72273. if (this.hand === 'right') {
  72274. return this.onSecondaryButtonStateChangedObservable;
  72275. }
  72276. else {
  72277. throw new Error('No B button on left hand');
  72278. }
  72279. },
  72280. enumerable: true,
  72281. configurable: true
  72282. });
  72283. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72284. /**
  72285. * Fired when the X button on this controller is modified
  72286. */
  72287. get: function () {
  72288. if (this.hand === 'left') {
  72289. return this.onMainButtonStateChangedObservable;
  72290. }
  72291. else {
  72292. throw new Error('No X button on right hand');
  72293. }
  72294. },
  72295. enumerable: true,
  72296. configurable: true
  72297. });
  72298. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72299. /**
  72300. * Fired when the Y button on this controller is modified
  72301. */
  72302. get: function () {
  72303. if (this.hand === 'left') {
  72304. return this.onSecondaryButtonStateChangedObservable;
  72305. }
  72306. else {
  72307. throw new Error('No Y button on right hand');
  72308. }
  72309. },
  72310. enumerable: true,
  72311. configurable: true
  72312. });
  72313. /**
  72314. * Called once for each button that changed state since the last frame
  72315. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72316. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72317. * 2) secondary trigger (same)
  72318. * 3) A (right) X (left), touch, pressed = value
  72319. * 4) B / Y
  72320. * 5) thumb rest
  72321. * @param buttonIdx Which button index changed
  72322. * @param state New state of the button
  72323. * @param changes Which properties on the state changed since last frame
  72324. */
  72325. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72326. var notifyObject = state; //{ state: state, changes: changes };
  72327. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72328. switch (buttonIdx) {
  72329. case 0:
  72330. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72331. return;
  72332. case 1: // index trigger
  72333. if (this._defaultModel) {
  72334. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72335. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72336. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72337. }
  72338. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72339. return;
  72340. case 2: // secondary trigger
  72341. if (this._defaultModel) {
  72342. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72343. }
  72344. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72345. return;
  72346. case 3:
  72347. if (this._defaultModel) {
  72348. if (notifyObject.pressed) {
  72349. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72350. }
  72351. else {
  72352. (this._defaultModel.getChildren()[1]).position.y = 0;
  72353. }
  72354. }
  72355. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72356. return;
  72357. case 4:
  72358. if (this._defaultModel) {
  72359. if (notifyObject.pressed) {
  72360. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72361. }
  72362. else {
  72363. (this._defaultModel.getChildren()[2]).position.y = 0;
  72364. }
  72365. }
  72366. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72367. return;
  72368. case 5:
  72369. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72370. return;
  72371. }
  72372. };
  72373. /**
  72374. * Base Url for the controller model.
  72375. */
  72376. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72377. /**
  72378. * File name for the left controller model.
  72379. */
  72380. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72381. /**
  72382. * File name for the right controller model.
  72383. */
  72384. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72385. return OculusTouchController;
  72386. }(BABYLON.WebVRController));
  72387. BABYLON.OculusTouchController = OculusTouchController;
  72388. })(BABYLON || (BABYLON = {}));
  72389. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72390. var BABYLON;
  72391. (function (BABYLON) {
  72392. /**
  72393. * Vive Controller
  72394. */
  72395. var ViveController = /** @class */ (function (_super) {
  72396. __extends(ViveController, _super);
  72397. /**
  72398. * Creates a new ViveController from a gamepad
  72399. * @param vrGamepad the gamepad that the controller should be created from
  72400. */
  72401. function ViveController(vrGamepad) {
  72402. var _this = _super.call(this, vrGamepad) || this;
  72403. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72404. _this._invertLeftStickY = true;
  72405. return _this;
  72406. }
  72407. /**
  72408. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72409. * @param scene scene in which to add meshes
  72410. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72411. */
  72412. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72413. var _this = this;
  72414. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72415. /*
  72416. Parent Mesh name: ViveWand
  72417. - body
  72418. - r_gripper
  72419. - l_gripper
  72420. - menu_button
  72421. - system_button
  72422. - trackpad
  72423. - trigger
  72424. - LED
  72425. */
  72426. _this._defaultModel = newMeshes[1];
  72427. _this.attachToMesh(_this._defaultModel);
  72428. if (meshLoaded) {
  72429. meshLoaded(_this._defaultModel);
  72430. }
  72431. });
  72432. };
  72433. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72434. /**
  72435. * Fired when the left button on this controller is modified
  72436. */
  72437. get: function () {
  72438. return this.onMainButtonStateChangedObservable;
  72439. },
  72440. enumerable: true,
  72441. configurable: true
  72442. });
  72443. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72444. /**
  72445. * Fired when the right button on this controller is modified
  72446. */
  72447. get: function () {
  72448. return this.onMainButtonStateChangedObservable;
  72449. },
  72450. enumerable: true,
  72451. configurable: true
  72452. });
  72453. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72454. /**
  72455. * Fired when the menu button on this controller is modified
  72456. */
  72457. get: function () {
  72458. return this.onSecondaryButtonStateChangedObservable;
  72459. },
  72460. enumerable: true,
  72461. configurable: true
  72462. });
  72463. /**
  72464. * Called once for each button that changed state since the last frame
  72465. * Vive mapping:
  72466. * 0: touchpad
  72467. * 1: trigger
  72468. * 2: left AND right buttons
  72469. * 3: menu button
  72470. * @param buttonIdx Which button index changed
  72471. * @param state New state of the button
  72472. * @param changes Which properties on the state changed since last frame
  72473. */
  72474. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72475. var notifyObject = state; //{ state: state, changes: changes };
  72476. switch (buttonIdx) {
  72477. case 0:
  72478. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72479. return;
  72480. case 1: // index trigger
  72481. if (this._defaultModel) {
  72482. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72483. }
  72484. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72485. return;
  72486. case 2: // left AND right button
  72487. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72488. return;
  72489. case 3:
  72490. if (this._defaultModel) {
  72491. if (notifyObject.pressed) {
  72492. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72493. }
  72494. else {
  72495. (this._defaultModel.getChildren()[2]).position.y = 0;
  72496. }
  72497. }
  72498. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72499. return;
  72500. }
  72501. };
  72502. /**
  72503. * Base Url for the controller model.
  72504. */
  72505. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72506. /**
  72507. * File name for the controller model.
  72508. */
  72509. ViveController.MODEL_FILENAME = 'wand.babylon';
  72510. return ViveController;
  72511. }(BABYLON.WebVRController));
  72512. BABYLON.ViveController = ViveController;
  72513. })(BABYLON || (BABYLON = {}));
  72514. //# sourceMappingURL=babylon.viveController.js.map
  72515. var BABYLON;
  72516. (function (BABYLON) {
  72517. /**
  72518. * Generic Controller
  72519. */
  72520. var GenericController = /** @class */ (function (_super) {
  72521. __extends(GenericController, _super);
  72522. /**
  72523. * Creates a new GenericController from a gamepad
  72524. * @param vrGamepad the gamepad that the controller should be created from
  72525. */
  72526. function GenericController(vrGamepad) {
  72527. return _super.call(this, vrGamepad) || this;
  72528. }
  72529. /**
  72530. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72531. * @param scene scene in which to add meshes
  72532. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72533. */
  72534. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72535. var _this = this;
  72536. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72537. _this._defaultModel = newMeshes[1];
  72538. _this.attachToMesh(_this._defaultModel);
  72539. if (meshLoaded) {
  72540. meshLoaded(_this._defaultModel);
  72541. }
  72542. });
  72543. };
  72544. /**
  72545. * Called once for each button that changed state since the last frame
  72546. * @param buttonIdx Which button index changed
  72547. * @param state New state of the button
  72548. * @param changes Which properties on the state changed since last frame
  72549. */
  72550. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72551. console.log("Button id: " + buttonIdx + "state: ");
  72552. console.dir(state);
  72553. };
  72554. /**
  72555. * Base Url for the controller model.
  72556. */
  72557. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72558. /**
  72559. * File name for the controller model.
  72560. */
  72561. GenericController.MODEL_FILENAME = 'generic.babylon';
  72562. return GenericController;
  72563. }(BABYLON.WebVRController));
  72564. BABYLON.GenericController = GenericController;
  72565. })(BABYLON || (BABYLON = {}));
  72566. //# sourceMappingURL=babylon.genericController.js.map
  72567. var BABYLON;
  72568. (function (BABYLON) {
  72569. /**
  72570. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72571. */
  72572. var LoadedMeshInfo = /** @class */ (function () {
  72573. function LoadedMeshInfo() {
  72574. /**
  72575. * Map of the button meshes contained in the controller
  72576. */
  72577. this.buttonMeshes = {};
  72578. /**
  72579. * Map of the axis meshes contained in the controller
  72580. */
  72581. this.axisMeshes = {};
  72582. }
  72583. return LoadedMeshInfo;
  72584. }());
  72585. /**
  72586. * Defines the WindowsMotionController object that the state of the windows motion controller
  72587. */
  72588. var WindowsMotionController = /** @class */ (function (_super) {
  72589. __extends(WindowsMotionController, _super);
  72590. /**
  72591. * Creates a new WindowsMotionController from a gamepad
  72592. * @param vrGamepad the gamepad that the controller should be created from
  72593. */
  72594. function WindowsMotionController(vrGamepad) {
  72595. var _this = _super.call(this, vrGamepad) || this;
  72596. _this._mapping = {
  72597. // Semantic button names
  72598. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72599. // A mapping of the button name to glTF model node name
  72600. // that should be transformed by button value.
  72601. buttonMeshNames: {
  72602. 'trigger': 'SELECT',
  72603. 'menu': 'MENU',
  72604. 'grip': 'GRASP',
  72605. 'thumbstick': 'THUMBSTICK_PRESS',
  72606. 'trackpad': 'TOUCHPAD_PRESS'
  72607. },
  72608. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72609. buttonObservableNames: {
  72610. 'trigger': 'onTriggerStateChangedObservable',
  72611. 'menu': 'onSecondaryButtonStateChangedObservable',
  72612. 'grip': 'onMainButtonStateChangedObservable',
  72613. 'thumbstick': 'onPadStateChangedObservable',
  72614. 'trackpad': 'onTrackpadChangedObservable'
  72615. },
  72616. // A mapping of the axis name to glTF model node name
  72617. // that should be transformed by axis value.
  72618. // This array mirrors the browserGamepad.axes array, such that
  72619. // the mesh corresponding to axis 0 is in this array index 0.
  72620. axisMeshNames: [
  72621. 'THUMBSTICK_X',
  72622. 'THUMBSTICK_Y',
  72623. 'TOUCHPAD_TOUCH_X',
  72624. 'TOUCHPAD_TOUCH_Y'
  72625. ],
  72626. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72627. };
  72628. /**
  72629. * Fired when the trackpad on this controller is clicked
  72630. */
  72631. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72632. /**
  72633. * Fired when the trackpad on this controller is modified
  72634. */
  72635. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72636. /**
  72637. * The current x and y values of this controller's trackpad
  72638. */
  72639. _this.trackpad = { x: 0, y: 0 };
  72640. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72641. _this._loadedMeshInfo = null;
  72642. return _this;
  72643. }
  72644. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72645. /**
  72646. * Fired when the trigger on this controller is modified
  72647. */
  72648. get: function () {
  72649. return this.onTriggerStateChangedObservable;
  72650. },
  72651. enumerable: true,
  72652. configurable: true
  72653. });
  72654. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72655. /**
  72656. * Fired when the menu button on this controller is modified
  72657. */
  72658. get: function () {
  72659. return this.onSecondaryButtonStateChangedObservable;
  72660. },
  72661. enumerable: true,
  72662. configurable: true
  72663. });
  72664. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72665. /**
  72666. * Fired when the grip button on this controller is modified
  72667. */
  72668. get: function () {
  72669. return this.onMainButtonStateChangedObservable;
  72670. },
  72671. enumerable: true,
  72672. configurable: true
  72673. });
  72674. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72675. /**
  72676. * Fired when the thumbstick button on this controller is modified
  72677. */
  72678. get: function () {
  72679. return this.onPadStateChangedObservable;
  72680. },
  72681. enumerable: true,
  72682. configurable: true
  72683. });
  72684. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72685. /**
  72686. * Fired when the touchpad button on this controller is modified
  72687. */
  72688. get: function () {
  72689. return this.onTrackpadChangedObservable;
  72690. },
  72691. enumerable: true,
  72692. configurable: true
  72693. });
  72694. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72695. /**
  72696. * Fired when the touchpad values on this controller are modified
  72697. */
  72698. get: function () {
  72699. return this.onTrackpadValuesChangedObservable;
  72700. },
  72701. enumerable: true,
  72702. configurable: true
  72703. });
  72704. WindowsMotionController.prototype._updateTrackpad = function () {
  72705. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72706. this.trackpad.x = this.browserGamepad["axes"][2];
  72707. this.trackpad.y = this.browserGamepad["axes"][3];
  72708. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72709. }
  72710. };
  72711. /**
  72712. * Called once per frame by the engine.
  72713. */
  72714. WindowsMotionController.prototype.update = function () {
  72715. _super.prototype.update.call(this);
  72716. if (this.browserGamepad.axes) {
  72717. this._updateTrackpad();
  72718. // Only need to animate axes if there is a loaded mesh
  72719. if (this._loadedMeshInfo) {
  72720. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72721. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72722. }
  72723. }
  72724. }
  72725. };
  72726. /**
  72727. * Called once for each button that changed state since the last frame
  72728. * @param buttonIdx Which button index changed
  72729. * @param state New state of the button
  72730. * @param changes Which properties on the state changed since last frame
  72731. */
  72732. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72733. var buttonName = this._mapping.buttons[buttonIdx];
  72734. if (!buttonName) {
  72735. return;
  72736. }
  72737. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72738. this._updateTrackpad();
  72739. // Only emit events for buttons that we know how to map from index to name
  72740. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72741. if (observable) {
  72742. observable.notifyObservers(state);
  72743. }
  72744. this._lerpButtonTransform(buttonName, state.value);
  72745. };
  72746. /**
  72747. * Moves the buttons on the controller mesh based on their current state
  72748. * @param buttonName the name of the button to move
  72749. * @param buttonValue the value of the button which determines the buttons new position
  72750. */
  72751. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72752. // If there is no loaded mesh, there is nothing to transform.
  72753. if (!this._loadedMeshInfo) {
  72754. return;
  72755. }
  72756. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72757. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72758. return;
  72759. }
  72760. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72761. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72762. };
  72763. /**
  72764. * Moves the axis on the controller mesh based on its current state
  72765. * @param axis the index of the axis
  72766. * @param axisValue the value of the axis which determines the meshes new position
  72767. * @hidden
  72768. */
  72769. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72770. if (!this._loadedMeshInfo) {
  72771. return;
  72772. }
  72773. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72774. if (!meshInfo) {
  72775. return;
  72776. }
  72777. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72778. return;
  72779. }
  72780. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72781. var lerpValue = axisValue * 0.5 + 0.5;
  72782. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72783. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72784. };
  72785. /**
  72786. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72787. * @param scene scene in which to add meshes
  72788. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72789. */
  72790. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72791. var _this = this;
  72792. if (forceDefault === void 0) { forceDefault = false; }
  72793. var path;
  72794. var filename;
  72795. // Checking if GLB loader is present
  72796. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72797. // Determine the device specific folder based on the ID suffix
  72798. var device = 'default';
  72799. if (this.id && !forceDefault) {
  72800. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72801. device = ((match && match[0]) || device);
  72802. }
  72803. // Hand
  72804. if (this.hand === 'left') {
  72805. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72806. }
  72807. else { // Right is the default if no hand is specified
  72808. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72809. }
  72810. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72811. }
  72812. else {
  72813. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72814. path = BABYLON.GenericController.MODEL_BASE_URL;
  72815. filename = BABYLON.GenericController.MODEL_FILENAME;
  72816. }
  72817. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72818. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72819. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72820. if (!_this._loadedMeshInfo) {
  72821. return;
  72822. }
  72823. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72824. _this.attachToMesh(_this._defaultModel);
  72825. if (meshLoaded) {
  72826. meshLoaded(_this._defaultModel);
  72827. }
  72828. }, null, function (scene, message) {
  72829. BABYLON.Tools.Log(message);
  72830. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72831. if (!forceDefault) {
  72832. _this.initControllerMesh(scene, meshLoaded, true);
  72833. }
  72834. });
  72835. };
  72836. /**
  72837. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72838. * can be transformed by button presses and axes values, based on this._mapping.
  72839. *
  72840. * @param scene scene in which the meshes exist
  72841. * @param meshes list of meshes that make up the controller model to process
  72842. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72843. */
  72844. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72845. var loadedMeshInfo = null;
  72846. // Create a new mesh to contain the glTF hierarchy
  72847. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72848. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72849. var childMesh = null;
  72850. for (var i = 0; i < meshes.length; i++) {
  72851. var mesh = meshes[i];
  72852. if (!mesh.parent) {
  72853. // Exclude controller meshes from picking results
  72854. mesh.isPickable = false;
  72855. // Handle root node, attach to the new parentMesh
  72856. childMesh = mesh;
  72857. break;
  72858. }
  72859. }
  72860. if (childMesh) {
  72861. childMesh.setParent(parentMesh);
  72862. // Create our mesh info. Note that this method will always return non-null.
  72863. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72864. }
  72865. else {
  72866. BABYLON.Tools.Warn('Could not find root node in model file.');
  72867. }
  72868. return loadedMeshInfo;
  72869. };
  72870. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72871. var loadedMeshInfo = new LoadedMeshInfo();
  72872. var i;
  72873. loadedMeshInfo.rootNode = rootNode;
  72874. // Reset the caches
  72875. loadedMeshInfo.buttonMeshes = {};
  72876. loadedMeshInfo.axisMeshes = {};
  72877. // Button Meshes
  72878. for (i = 0; i < this._mapping.buttons.length; i++) {
  72879. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72880. if (!buttonMeshName) {
  72881. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72882. continue;
  72883. }
  72884. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72885. if (!buttonMesh) {
  72886. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72887. continue;
  72888. }
  72889. var buttonMeshInfo = {
  72890. index: i,
  72891. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72892. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72893. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72894. };
  72895. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72896. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72897. }
  72898. else {
  72899. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72900. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72901. '(VALUE: ' + !!buttonMeshInfo.value +
  72902. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72903. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72904. ')');
  72905. }
  72906. }
  72907. // Axis Meshes
  72908. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72909. var axisMeshName = this._mapping.axisMeshNames[i];
  72910. if (!axisMeshName) {
  72911. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72912. continue;
  72913. }
  72914. var axisMesh = getChildByName(rootNode, axisMeshName);
  72915. if (!axisMesh) {
  72916. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72917. continue;
  72918. }
  72919. var axisMeshInfo = {
  72920. index: i,
  72921. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72922. min: getImmediateChildByName(axisMesh, 'MIN'),
  72923. max: getImmediateChildByName(axisMesh, 'MAX')
  72924. };
  72925. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72926. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72927. }
  72928. else {
  72929. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72930. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72931. '(VALUE: ' + !!axisMeshInfo.value +
  72932. ', MIN: ' + !!axisMeshInfo.min +
  72933. ', MAX:' + !!axisMeshInfo.max +
  72934. ')');
  72935. }
  72936. }
  72937. // Pointing Ray
  72938. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72939. if (!loadedMeshInfo.pointingPoseNode) {
  72940. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72941. }
  72942. else {
  72943. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72944. }
  72945. return loadedMeshInfo;
  72946. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72947. function getChildByName(node, name) {
  72948. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72949. }
  72950. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72951. function getImmediateChildByName(node, name) {
  72952. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72953. }
  72954. };
  72955. /**
  72956. * Gets the ray of the controller in the direction the controller is pointing
  72957. * @param length the length the resulting ray should be
  72958. * @returns a ray in the direction the controller is pointing
  72959. */
  72960. WindowsMotionController.prototype.getForwardRay = function (length) {
  72961. if (length === void 0) { length = 100; }
  72962. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72963. return _super.prototype.getForwardRay.call(this, length);
  72964. }
  72965. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72966. var origin = m.getTranslation();
  72967. var forward = new BABYLON.Vector3(0, 0, -1);
  72968. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72969. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72970. return new BABYLON.Ray(origin, direction, length);
  72971. };
  72972. /**
  72973. * Disposes of the controller
  72974. */
  72975. WindowsMotionController.prototype.dispose = function () {
  72976. _super.prototype.dispose.call(this);
  72977. this.onTrackpadChangedObservable.clear();
  72978. };
  72979. /**
  72980. * The base url used to load the left and right controller models
  72981. */
  72982. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72983. /**
  72984. * The name of the left controller model file
  72985. */
  72986. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72987. /**
  72988. * The name of the right controller model file
  72989. */
  72990. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72991. /**
  72992. * The controller name prefix for this controller type
  72993. */
  72994. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72995. /**
  72996. * The controller id pattern for this controller type
  72997. */
  72998. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72999. return WindowsMotionController;
  73000. }(BABYLON.WebVRController));
  73001. BABYLON.WindowsMotionController = WindowsMotionController;
  73002. })(BABYLON || (BABYLON = {}));
  73003. //# sourceMappingURL=babylon.windowsMotionController.js.map
  73004. var BABYLON;
  73005. (function (BABYLON) {
  73006. /**
  73007. * Gear VR Controller
  73008. */
  73009. var GearVRController = /** @class */ (function (_super) {
  73010. __extends(GearVRController, _super);
  73011. /**
  73012. * Creates a new GearVRController from a gamepad
  73013. * @param vrGamepad the gamepad that the controller should be created from
  73014. */
  73015. function GearVRController(vrGamepad) {
  73016. var _this = _super.call(this, vrGamepad) || this;
  73017. _this._buttonIndexToObservableNameMap = [
  73018. 'onTrackpadChangedObservable',
  73019. 'onTriggerStateChangedObservable' // Trigger
  73020. ];
  73021. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  73022. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  73023. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  73024. return _this;
  73025. }
  73026. /**
  73027. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73028. * @param scene scene in which to add meshes
  73029. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73030. */
  73031. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73032. var _this = this;
  73033. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  73034. _this._defaultModel = newMeshes[1];
  73035. _this.attachToMesh(_this._defaultModel);
  73036. if (meshLoaded) {
  73037. meshLoaded(_this._defaultModel);
  73038. }
  73039. });
  73040. };
  73041. /**
  73042. * Called once for each button that changed state since the last frame
  73043. * @param buttonIdx Which button index changed
  73044. * @param state New state of the button
  73045. * @param changes Which properties on the state changed since last frame
  73046. */
  73047. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73048. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  73049. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  73050. // Only emit events for buttons that we know how to map from index to observable
  73051. var observable = this[observableName];
  73052. if (observable) {
  73053. observable.notifyObservers(state);
  73054. }
  73055. }
  73056. };
  73057. /**
  73058. * Base Url for the controller model.
  73059. */
  73060. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73061. /**
  73062. * File name for the controller model.
  73063. */
  73064. GearVRController.MODEL_FILENAME = 'generic.babylon';
  73065. /**
  73066. * Gamepad Id prefix used to identify this controller.
  73067. */
  73068. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  73069. return GearVRController;
  73070. }(BABYLON.WebVRController));
  73071. BABYLON.GearVRController = GearVRController;
  73072. })(BABYLON || (BABYLON = {}));
  73073. //# sourceMappingURL=babylon.gearVRController.js.map
  73074. var BABYLON;
  73075. (function (BABYLON) {
  73076. /**
  73077. * Google Daydream controller
  73078. */
  73079. var DaydreamController = /** @class */ (function (_super) {
  73080. __extends(DaydreamController, _super);
  73081. /**
  73082. * Creates a new DaydreamController from a gamepad
  73083. * @param vrGamepad the gamepad that the controller should be created from
  73084. */
  73085. function DaydreamController(vrGamepad) {
  73086. var _this = _super.call(this, vrGamepad) || this;
  73087. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  73088. return _this;
  73089. }
  73090. /**
  73091. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73092. * @param scene scene in which to add meshes
  73093. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73094. */
  73095. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73096. var _this = this;
  73097. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  73098. _this._defaultModel = newMeshes[1];
  73099. _this.attachToMesh(_this._defaultModel);
  73100. if (meshLoaded) {
  73101. meshLoaded(_this._defaultModel);
  73102. }
  73103. });
  73104. };
  73105. /**
  73106. * Called once for each button that changed state since the last frame
  73107. * @param buttonIdx Which button index changed
  73108. * @param state New state of the button
  73109. * @param changes Which properties on the state changed since last frame
  73110. */
  73111. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73112. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73113. if (buttonIdx === 0) {
  73114. var observable = this.onTriggerStateChangedObservable;
  73115. if (observable) {
  73116. observable.notifyObservers(state);
  73117. }
  73118. }
  73119. else {
  73120. // If the app or home buttons are ever made available
  73121. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73122. }
  73123. };
  73124. /**
  73125. * Base Url for the controller model.
  73126. */
  73127. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73128. /**
  73129. * File name for the controller model.
  73130. */
  73131. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73132. /**
  73133. * Gamepad Id prefix used to identify Daydream Controller.
  73134. */
  73135. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73136. return DaydreamController;
  73137. }(BABYLON.WebVRController));
  73138. BABYLON.DaydreamController = DaydreamController;
  73139. })(BABYLON || (BABYLON = {}));
  73140. //# sourceMappingURL=babylon.daydreamController.js.map
  73141. var BABYLON;
  73142. (function (BABYLON) {
  73143. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  73144. get: function () {
  73145. if (!this._gamepadManager) {
  73146. this._gamepadManager = new BABYLON.GamepadManager(this);
  73147. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  73148. if (!component) {
  73149. component = new GamepadSystemSceneComponent(this);
  73150. this._addComponent(component);
  73151. }
  73152. }
  73153. return this._gamepadManager;
  73154. },
  73155. enumerable: true,
  73156. configurable: true
  73157. });
  73158. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  73159. this.add(new BABYLON.FreeCameraGamepadInput());
  73160. return this;
  73161. };
  73162. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  73163. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  73164. return this;
  73165. };
  73166. /**
  73167. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  73168. */
  73169. var GamepadSystemSceneComponent = /** @class */ (function () {
  73170. /**
  73171. * Creates a new instance of the component for the given scene
  73172. * @param scene Defines the scene to register the component in
  73173. */
  73174. function GamepadSystemSceneComponent(scene) {
  73175. /**
  73176. * The component name helpfull to identify the component in the list of scene components.
  73177. */
  73178. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  73179. this.scene = scene;
  73180. }
  73181. /**
  73182. * Registers the component in a given scene
  73183. */
  73184. GamepadSystemSceneComponent.prototype.register = function () {
  73185. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  73186. };
  73187. /**
  73188. * Rebuilds the elements related to this component in case of
  73189. * context lost for instance.
  73190. */
  73191. GamepadSystemSceneComponent.prototype.rebuild = function () {
  73192. // Nothing to do for gamepads
  73193. };
  73194. /**
  73195. * Disposes the component and the associated ressources
  73196. */
  73197. GamepadSystemSceneComponent.prototype.dispose = function () {
  73198. var gamepadManager = this.scene._gamepadManager;
  73199. if (gamepadManager) {
  73200. gamepadManager.dispose();
  73201. this.scene._gamepadManager = null;
  73202. }
  73203. };
  73204. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  73205. var gamepadManager = this.scene._gamepadManager;
  73206. if (gamepadManager && gamepadManager._isMonitoring) {
  73207. gamepadManager._checkGamepadsStatus();
  73208. }
  73209. };
  73210. return GamepadSystemSceneComponent;
  73211. }());
  73212. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  73213. })(BABYLON || (BABYLON = {}));
  73214. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  73215. var BABYLON;
  73216. (function (BABYLON) {
  73217. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  73218. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  73219. });
  73220. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  73221. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  73222. });
  73223. var FollowCamera = /** @class */ (function (_super) {
  73224. __extends(FollowCamera, _super);
  73225. function FollowCamera(name, position, scene, lockedTarget) {
  73226. if (lockedTarget === void 0) { lockedTarget = null; }
  73227. var _this = _super.call(this, name, position, scene) || this;
  73228. _this.radius = 12;
  73229. _this.rotationOffset = 0;
  73230. _this.heightOffset = 4;
  73231. _this.cameraAcceleration = 0.05;
  73232. _this.maxCameraSpeed = 20;
  73233. _this.lockedTarget = lockedTarget;
  73234. return _this;
  73235. }
  73236. FollowCamera.prototype.getRadians = function (degrees) {
  73237. return degrees * Math.PI / 180;
  73238. };
  73239. FollowCamera.prototype.follow = function (cameraTarget) {
  73240. if (!cameraTarget)
  73241. return;
  73242. var yRotation;
  73243. if (cameraTarget.rotationQuaternion) {
  73244. var rotMatrix = new BABYLON.Matrix();
  73245. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73246. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73247. }
  73248. else {
  73249. yRotation = cameraTarget.rotation.y;
  73250. }
  73251. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73252. var targetPosition = cameraTarget.getAbsolutePosition();
  73253. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73254. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73255. var dx = targetX - this.position.x;
  73256. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73257. var dz = (targetZ) - this.position.z;
  73258. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73259. var vy = dy * this.cameraAcceleration;
  73260. var vz = dz * this.cameraAcceleration * 2;
  73261. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73262. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73263. }
  73264. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73265. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73266. }
  73267. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73268. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73269. }
  73270. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73271. this.setTarget(targetPosition);
  73272. };
  73273. FollowCamera.prototype._checkInputs = function () {
  73274. _super.prototype._checkInputs.call(this);
  73275. if (this.lockedTarget) {
  73276. this.follow(this.lockedTarget);
  73277. }
  73278. };
  73279. FollowCamera.prototype.getClassName = function () {
  73280. return "FollowCamera";
  73281. };
  73282. __decorate([
  73283. BABYLON.serialize()
  73284. ], FollowCamera.prototype, "radius", void 0);
  73285. __decorate([
  73286. BABYLON.serialize()
  73287. ], FollowCamera.prototype, "rotationOffset", void 0);
  73288. __decorate([
  73289. BABYLON.serialize()
  73290. ], FollowCamera.prototype, "heightOffset", void 0);
  73291. __decorate([
  73292. BABYLON.serialize()
  73293. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73294. __decorate([
  73295. BABYLON.serialize()
  73296. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73297. __decorate([
  73298. BABYLON.serializeAsMeshReference("lockedTargetId")
  73299. ], FollowCamera.prototype, "lockedTarget", void 0);
  73300. return FollowCamera;
  73301. }(BABYLON.TargetCamera));
  73302. BABYLON.FollowCamera = FollowCamera;
  73303. var ArcFollowCamera = /** @class */ (function (_super) {
  73304. __extends(ArcFollowCamera, _super);
  73305. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73306. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73307. _this.alpha = alpha;
  73308. _this.beta = beta;
  73309. _this.radius = radius;
  73310. _this.target = target;
  73311. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73312. _this.follow();
  73313. return _this;
  73314. }
  73315. ArcFollowCamera.prototype.follow = function () {
  73316. if (!this.target) {
  73317. return;
  73318. }
  73319. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73320. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73321. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73322. var targetPosition = this.target.getAbsolutePosition();
  73323. this.position = targetPosition.add(this._cartesianCoordinates);
  73324. this.setTarget(targetPosition);
  73325. };
  73326. ArcFollowCamera.prototype._checkInputs = function () {
  73327. _super.prototype._checkInputs.call(this);
  73328. this.follow();
  73329. };
  73330. ArcFollowCamera.prototype.getClassName = function () {
  73331. return "ArcFollowCamera";
  73332. };
  73333. return ArcFollowCamera;
  73334. }(BABYLON.TargetCamera));
  73335. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73336. })(BABYLON || (BABYLON = {}));
  73337. //# sourceMappingURL=babylon.followCamera.js.map
  73338. var BABYLON;
  73339. (function (BABYLON) {
  73340. // We're mainly based on the logic defined into the FreeCamera code
  73341. var UniversalCamera = /** @class */ (function (_super) {
  73342. __extends(UniversalCamera, _super);
  73343. //-- end properties for backward compatibility for inputs
  73344. function UniversalCamera(name, position, scene) {
  73345. var _this = _super.call(this, name, position, scene) || this;
  73346. _this.inputs.addGamepad();
  73347. return _this;
  73348. }
  73349. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73350. //-- Begin properties for backward compatibility for inputs
  73351. get: function () {
  73352. var gamepad = this.inputs.attached["gamepad"];
  73353. if (gamepad)
  73354. return gamepad.gamepadAngularSensibility;
  73355. return 0;
  73356. },
  73357. set: function (value) {
  73358. var gamepad = this.inputs.attached["gamepad"];
  73359. if (gamepad)
  73360. gamepad.gamepadAngularSensibility = value;
  73361. },
  73362. enumerable: true,
  73363. configurable: true
  73364. });
  73365. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73366. get: function () {
  73367. var gamepad = this.inputs.attached["gamepad"];
  73368. if (gamepad)
  73369. return gamepad.gamepadMoveSensibility;
  73370. return 0;
  73371. },
  73372. set: function (value) {
  73373. var gamepad = this.inputs.attached["gamepad"];
  73374. if (gamepad)
  73375. gamepad.gamepadMoveSensibility = value;
  73376. },
  73377. enumerable: true,
  73378. configurable: true
  73379. });
  73380. UniversalCamera.prototype.getClassName = function () {
  73381. return "UniversalCamera";
  73382. };
  73383. return UniversalCamera;
  73384. }(BABYLON.TouchCamera));
  73385. BABYLON.UniversalCamera = UniversalCamera;
  73386. })(BABYLON || (BABYLON = {}));
  73387. //# sourceMappingURL=babylon.universalCamera.js.map
  73388. var BABYLON;
  73389. (function (BABYLON) {
  73390. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  73391. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  73392. });
  73393. // We're mainly based on the logic defined into the FreeCamera code
  73394. var GamepadCamera = /** @class */ (function (_super) {
  73395. __extends(GamepadCamera, _super);
  73396. //-- end properties for backward compatibility for inputs
  73397. function GamepadCamera(name, position, scene) {
  73398. return _super.call(this, name, position, scene) || this;
  73399. }
  73400. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73401. //-- Begin properties for backward compatibility for inputs
  73402. get: function () {
  73403. var gamepad = this.inputs.attached["gamepad"];
  73404. if (gamepad)
  73405. return gamepad.gamepadAngularSensibility;
  73406. return 0;
  73407. },
  73408. set: function (value) {
  73409. var gamepad = this.inputs.attached["gamepad"];
  73410. if (gamepad)
  73411. gamepad.gamepadAngularSensibility = value;
  73412. },
  73413. enumerable: true,
  73414. configurable: true
  73415. });
  73416. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73417. get: function () {
  73418. var gamepad = this.inputs.attached["gamepad"];
  73419. if (gamepad)
  73420. return gamepad.gamepadMoveSensibility;
  73421. return 0;
  73422. },
  73423. set: function (value) {
  73424. var gamepad = this.inputs.attached["gamepad"];
  73425. if (gamepad)
  73426. gamepad.gamepadMoveSensibility = value;
  73427. },
  73428. enumerable: true,
  73429. configurable: true
  73430. });
  73431. GamepadCamera.prototype.getClassName = function () {
  73432. return "GamepadCamera";
  73433. };
  73434. return GamepadCamera;
  73435. }(BABYLON.UniversalCamera));
  73436. BABYLON.GamepadCamera = GamepadCamera;
  73437. })(BABYLON || (BABYLON = {}));
  73438. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73439. var BABYLON;
  73440. (function (BABYLON) {
  73441. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73442. function PostProcessRenderPipelineManager() {
  73443. this._renderPipelines = {};
  73444. }
  73445. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73446. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73447. };
  73448. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73449. if (unique === void 0) { unique = false; }
  73450. var renderPipeline = this._renderPipelines[renderPipelineName];
  73451. if (!renderPipeline) {
  73452. return;
  73453. }
  73454. renderPipeline._attachCameras(cameras, unique);
  73455. };
  73456. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73457. var renderPipeline = this._renderPipelines[renderPipelineName];
  73458. if (!renderPipeline) {
  73459. return;
  73460. }
  73461. renderPipeline._detachCameras(cameras);
  73462. };
  73463. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73464. var renderPipeline = this._renderPipelines[renderPipelineName];
  73465. if (!renderPipeline) {
  73466. return;
  73467. }
  73468. renderPipeline._enableEffect(renderEffectName, cameras);
  73469. };
  73470. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73471. var renderPipeline = this._renderPipelines[renderPipelineName];
  73472. if (!renderPipeline) {
  73473. return;
  73474. }
  73475. renderPipeline._disableEffect(renderEffectName, cameras);
  73476. };
  73477. PostProcessRenderPipelineManager.prototype.update = function () {
  73478. for (var renderPipelineName in this._renderPipelines) {
  73479. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73480. var pipeline = this._renderPipelines[renderPipelineName];
  73481. if (!pipeline.isSupported) {
  73482. pipeline.dispose();
  73483. delete this._renderPipelines[renderPipelineName];
  73484. }
  73485. else {
  73486. pipeline._update();
  73487. }
  73488. }
  73489. }
  73490. };
  73491. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73492. for (var renderPipelineName in this._renderPipelines) {
  73493. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73494. var pipeline = this._renderPipelines[renderPipelineName];
  73495. pipeline._rebuild();
  73496. }
  73497. }
  73498. };
  73499. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73500. for (var renderPipelineName in this._renderPipelines) {
  73501. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73502. var pipeline = this._renderPipelines[renderPipelineName];
  73503. pipeline.dispose();
  73504. }
  73505. }
  73506. };
  73507. return PostProcessRenderPipelineManager;
  73508. }());
  73509. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73510. })(BABYLON || (BABYLON = {}));
  73511. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73512. var BABYLON;
  73513. (function (BABYLON) {
  73514. /**
  73515. * This represents a set of one or more post processes in Babylon.
  73516. * A post process can be used to apply a shader to a texture after it is rendered.
  73517. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73518. */
  73519. var PostProcessRenderEffect = /** @class */ (function () {
  73520. /**
  73521. * Instantiates a post process render effect.
  73522. * A post process can be used to apply a shader to a texture after it is rendered.
  73523. * @param engine The engine the effect is tied to
  73524. * @param name The name of the effect
  73525. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73526. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73527. */
  73528. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73529. this._name = name;
  73530. this._singleInstance = singleInstance || true;
  73531. this._getPostProcesses = getPostProcesses;
  73532. this._cameras = {};
  73533. this._indicesForCamera = {};
  73534. this._postProcesses = {};
  73535. }
  73536. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73537. /**
  73538. * Checks if all the post processes in the effect are supported.
  73539. */
  73540. get: function () {
  73541. for (var index in this._postProcesses) {
  73542. if (this._postProcesses.hasOwnProperty(index)) {
  73543. var pps = this._postProcesses[index];
  73544. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73545. if (!pps[ppIndex].isSupported) {
  73546. return false;
  73547. }
  73548. }
  73549. }
  73550. }
  73551. return true;
  73552. },
  73553. enumerable: true,
  73554. configurable: true
  73555. });
  73556. /**
  73557. * Updates the current state of the effect
  73558. */
  73559. PostProcessRenderEffect.prototype._update = function () {
  73560. };
  73561. /**
  73562. * Attaches the effect on cameras
  73563. * @param cameras The camera to attach to.
  73564. */
  73565. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73566. var _this = this;
  73567. var cameraKey;
  73568. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73569. if (!cams) {
  73570. return;
  73571. }
  73572. for (var i = 0; i < cams.length; i++) {
  73573. var camera = cams[i];
  73574. var cameraName = camera.name;
  73575. if (this._singleInstance) {
  73576. cameraKey = 0;
  73577. }
  73578. else {
  73579. cameraKey = cameraName;
  73580. }
  73581. if (!this._postProcesses[cameraKey]) {
  73582. var postProcess = this._getPostProcesses();
  73583. if (postProcess) {
  73584. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73585. }
  73586. }
  73587. if (!this._indicesForCamera[cameraName]) {
  73588. this._indicesForCamera[cameraName] = [];
  73589. }
  73590. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73591. var index = camera.attachPostProcess(postProcess);
  73592. _this._indicesForCamera[cameraName].push(index);
  73593. });
  73594. if (!this._cameras[cameraName]) {
  73595. this._cameras[cameraName] = camera;
  73596. }
  73597. }
  73598. };
  73599. /**
  73600. * Detatches the effect on cameras
  73601. * @param cameras The camera to detatch from.
  73602. */
  73603. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73604. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73605. if (!cams) {
  73606. return;
  73607. }
  73608. for (var i = 0; i < cams.length; i++) {
  73609. var camera = cams[i];
  73610. var cameraName = camera.name;
  73611. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73612. camera.detachPostProcess(postProcess);
  73613. });
  73614. if (this._cameras[cameraName]) {
  73615. //this._indicesForCamera.splice(index, 1);
  73616. this._cameras[cameraName] = null;
  73617. }
  73618. }
  73619. };
  73620. /**
  73621. * Enables the effect on given cameras
  73622. * @param cameras The camera to enable.
  73623. */
  73624. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73625. var _this = this;
  73626. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73627. if (!cams) {
  73628. return;
  73629. }
  73630. for (var i = 0; i < cams.length; i++) {
  73631. var camera = cams[i];
  73632. var cameraName = camera.name;
  73633. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73634. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73635. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73636. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73637. });
  73638. }
  73639. }
  73640. }
  73641. };
  73642. /**
  73643. * Disables the effect on the given cameras
  73644. * @param cameras The camera to disable.
  73645. */
  73646. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73647. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73648. if (!cams) {
  73649. return;
  73650. }
  73651. for (var i = 0; i < cams.length; i++) {
  73652. var camera = cams[i];
  73653. var cameraName = camera.name;
  73654. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73655. camera.detachPostProcess(postProcess);
  73656. });
  73657. }
  73658. };
  73659. /**
  73660. * Gets a list of the post processes contained in the effect.
  73661. * @param camera The camera to get the post processes on.
  73662. * @returns The list of the post processes in the effect.
  73663. */
  73664. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73665. if (this._singleInstance) {
  73666. return this._postProcesses[0];
  73667. }
  73668. else {
  73669. if (!camera) {
  73670. return null;
  73671. }
  73672. return this._postProcesses[camera.name];
  73673. }
  73674. };
  73675. return PostProcessRenderEffect;
  73676. }());
  73677. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73678. })(BABYLON || (BABYLON = {}));
  73679. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73680. var BABYLON;
  73681. (function (BABYLON) {
  73682. var PostProcessRenderPipeline = /** @class */ (function () {
  73683. function PostProcessRenderPipeline(engine, name) {
  73684. this.engine = engine;
  73685. this._name = name;
  73686. this._renderEffects = {};
  73687. this._renderEffectsForIsolatedPass = new Array();
  73688. this._cameras = [];
  73689. }
  73690. PostProcessRenderPipeline.prototype.getClassName = function () {
  73691. return "PostProcessRenderPipeline";
  73692. };
  73693. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73694. get: function () {
  73695. for (var renderEffectName in this._renderEffects) {
  73696. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73697. if (!this._renderEffects[renderEffectName].isSupported) {
  73698. return false;
  73699. }
  73700. }
  73701. }
  73702. return true;
  73703. },
  73704. enumerable: true,
  73705. configurable: true
  73706. });
  73707. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73708. this._renderEffects[renderEffect._name] = renderEffect;
  73709. };
  73710. // private
  73711. PostProcessRenderPipeline.prototype._rebuild = function () {
  73712. };
  73713. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73714. var renderEffects = this._renderEffects[renderEffectName];
  73715. if (!renderEffects) {
  73716. return;
  73717. }
  73718. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73719. };
  73720. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73721. var renderEffects = this._renderEffects[renderEffectName];
  73722. if (!renderEffects) {
  73723. return;
  73724. }
  73725. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73726. };
  73727. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73728. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73729. if (!cams) {
  73730. return;
  73731. }
  73732. var indicesToDelete = [];
  73733. var i;
  73734. for (i = 0; i < cams.length; i++) {
  73735. var camera = cams[i];
  73736. var cameraName = camera.name;
  73737. if (this._cameras.indexOf(camera) === -1) {
  73738. this._cameras[cameraName] = camera;
  73739. }
  73740. else if (unique) {
  73741. indicesToDelete.push(i);
  73742. }
  73743. }
  73744. for (i = 0; i < indicesToDelete.length; i++) {
  73745. cameras.splice(indicesToDelete[i], 1);
  73746. }
  73747. for (var renderEffectName in this._renderEffects) {
  73748. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73749. this._renderEffects[renderEffectName]._attachCameras(cams);
  73750. }
  73751. }
  73752. };
  73753. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73754. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73755. if (!cams) {
  73756. return;
  73757. }
  73758. for (var renderEffectName in this._renderEffects) {
  73759. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73760. this._renderEffects[renderEffectName]._detachCameras(cams);
  73761. }
  73762. }
  73763. for (var i = 0; i < cams.length; i++) {
  73764. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73765. }
  73766. };
  73767. PostProcessRenderPipeline.prototype._update = function () {
  73768. for (var renderEffectName in this._renderEffects) {
  73769. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73770. this._renderEffects[renderEffectName]._update();
  73771. }
  73772. }
  73773. for (var i = 0; i < this._cameras.length; i++) {
  73774. var cameraName = this._cameras[i].name;
  73775. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73776. this._renderEffectsForIsolatedPass[cameraName]._update();
  73777. }
  73778. }
  73779. };
  73780. PostProcessRenderPipeline.prototype._reset = function () {
  73781. this._renderEffects = {};
  73782. this._renderEffectsForIsolatedPass = new Array();
  73783. };
  73784. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73785. // 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)
  73786. var effectKeys = Object.keys(this._renderEffects);
  73787. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73788. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73789. if (postProcesses) {
  73790. postProcesses[0].samples = sampleCount;
  73791. return true;
  73792. }
  73793. }
  73794. return false;
  73795. };
  73796. PostProcessRenderPipeline.prototype.dispose = function () {
  73797. // Must be implemented by children
  73798. };
  73799. __decorate([
  73800. BABYLON.serialize()
  73801. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73802. return PostProcessRenderPipeline;
  73803. }());
  73804. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73805. })(BABYLON || (BABYLON = {}));
  73806. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73807. var BABYLON;
  73808. (function (BABYLON) {
  73809. /**
  73810. * This represents a depth renderer in Babylon.
  73811. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73812. */
  73813. var DepthRenderer = /** @class */ (function () {
  73814. /**
  73815. * Instantiates a depth renderer
  73816. * @param scene The scene the renderer belongs to
  73817. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73818. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73819. */
  73820. function DepthRenderer(scene, type, camera) {
  73821. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73822. if (camera === void 0) { camera = null; }
  73823. var _this = this;
  73824. this._scene = scene;
  73825. this._camera = camera;
  73826. var engine = scene.getEngine();
  73827. // Render target
  73828. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73829. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73830. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73831. this._depthMap.refreshRate = 1;
  73832. this._depthMap.renderParticles = false;
  73833. this._depthMap.renderList = null;
  73834. // Camera to get depth map from to support multiple concurrent cameras
  73835. this._depthMap.activeCamera = this._camera;
  73836. this._depthMap.ignoreCameraViewport = true;
  73837. this._depthMap.useCameraPostProcesses = false;
  73838. // set default depth value to 1.0 (far away)
  73839. this._depthMap.onClearObservable.add(function (engine) {
  73840. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73841. });
  73842. // Custom render function
  73843. var renderSubMesh = function (subMesh) {
  73844. var mesh = subMesh.getRenderingMesh();
  73845. var scene = _this._scene;
  73846. var engine = scene.getEngine();
  73847. var material = subMesh.getMaterial();
  73848. if (!material) {
  73849. return;
  73850. }
  73851. // Culling and reverse (right handed system)
  73852. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73853. // Managing instances
  73854. var batch = mesh._getInstancesRenderList(subMesh._id);
  73855. if (batch.mustReturn) {
  73856. return;
  73857. }
  73858. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73859. var camera = _this._camera || scene.activeCamera;
  73860. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73861. engine.enableEffect(_this._effect);
  73862. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73863. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73864. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73865. // Alpha test
  73866. if (material && material.needAlphaTesting()) {
  73867. var alphaTexture = material.getAlphaTestTexture();
  73868. if (alphaTexture) {
  73869. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73870. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73871. }
  73872. }
  73873. // Bones
  73874. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73875. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73876. }
  73877. // Draw
  73878. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73879. }
  73880. };
  73881. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73882. var index;
  73883. if (depthOnlySubMeshes.length) {
  73884. engine.setColorWrite(false);
  73885. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73886. renderSubMesh(depthOnlySubMeshes.data[index]);
  73887. }
  73888. engine.setColorWrite(true);
  73889. }
  73890. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73891. renderSubMesh(opaqueSubMeshes.data[index]);
  73892. }
  73893. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73894. renderSubMesh(alphaTestSubMeshes.data[index]);
  73895. }
  73896. };
  73897. }
  73898. /**
  73899. * Creates the depth rendering effect and checks if the effect is ready.
  73900. * @param subMesh The submesh to be used to render the depth map of
  73901. * @param useInstances If multiple world instances should be used
  73902. * @returns if the depth renderer is ready to render the depth map
  73903. */
  73904. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73905. var material = subMesh.getMaterial();
  73906. if (material.disableDepthWrite) {
  73907. return false;
  73908. }
  73909. var defines = [];
  73910. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73911. var mesh = subMesh.getMesh();
  73912. // Alpha test
  73913. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73914. defines.push("#define ALPHATEST");
  73915. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73916. attribs.push(BABYLON.VertexBuffer.UVKind);
  73917. defines.push("#define UV1");
  73918. }
  73919. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73920. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73921. defines.push("#define UV2");
  73922. }
  73923. }
  73924. // Bones
  73925. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73926. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73927. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73928. if (mesh.numBoneInfluencers > 4) {
  73929. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73930. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73931. }
  73932. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73933. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73934. }
  73935. else {
  73936. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73937. }
  73938. // Instances
  73939. if (useInstances) {
  73940. defines.push("#define INSTANCES");
  73941. attribs.push("world0");
  73942. attribs.push("world1");
  73943. attribs.push("world2");
  73944. attribs.push("world3");
  73945. }
  73946. // Get correct effect
  73947. var join = defines.join("\n");
  73948. if (this._cachedDefines !== join) {
  73949. this._cachedDefines = join;
  73950. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73951. }
  73952. return this._effect.isReady();
  73953. };
  73954. /**
  73955. * Gets the texture which the depth map will be written to.
  73956. * @returns The depth map texture
  73957. */
  73958. DepthRenderer.prototype.getDepthMap = function () {
  73959. return this._depthMap;
  73960. };
  73961. /**
  73962. * Disposes of the depth renderer.
  73963. */
  73964. DepthRenderer.prototype.dispose = function () {
  73965. this._depthMap.dispose();
  73966. };
  73967. return DepthRenderer;
  73968. }());
  73969. BABYLON.DepthRenderer = DepthRenderer;
  73970. })(BABYLON || (BABYLON = {}));
  73971. //# sourceMappingURL=babylon.depthRenderer.js.map
  73972. var BABYLON;
  73973. (function (BABYLON) {
  73974. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73975. __extends(SSAORenderingPipeline, _super);
  73976. /**
  73977. * @constructor
  73978. * @param {string} name - The rendering pipeline name
  73979. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73980. * @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 }
  73981. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73982. */
  73983. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73984. var _this = _super.call(this, scene.getEngine(), name) || this;
  73985. // Members
  73986. /**
  73987. * The PassPostProcess id in the pipeline that contains the original scene color
  73988. */
  73989. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73990. /**
  73991. * The SSAO PostProcess id in the pipeline
  73992. */
  73993. _this.SSAORenderEffect = "SSAORenderEffect";
  73994. /**
  73995. * The horizontal blur PostProcess id in the pipeline
  73996. */
  73997. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73998. /**
  73999. * The vertical blur PostProcess id in the pipeline
  74000. */
  74001. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74002. /**
  74003. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74004. */
  74005. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74006. /**
  74007. * The output strength of the SSAO post-process. Default value is 1.0.
  74008. */
  74009. _this.totalStrength = 1.0;
  74010. /**
  74011. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  74012. */
  74013. _this.radius = 0.0001;
  74014. /**
  74015. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  74016. * Must not be equal to fallOff and superior to fallOff.
  74017. * Default value is 0.975
  74018. */
  74019. _this.area = 0.0075;
  74020. /**
  74021. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  74022. * Must not be equal to area and inferior to area.
  74023. * Default value is 0.0
  74024. */
  74025. _this.fallOff = 0.000001;
  74026. /**
  74027. * The base color of the SSAO post-process
  74028. * The final result is "base + ssao" between [0, 1]
  74029. */
  74030. _this.base = 0.5;
  74031. _this._firstUpdate = true;
  74032. _this._scene = scene;
  74033. // Set up assets
  74034. _this._createRandomTexture();
  74035. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74036. var ssaoRatio = ratio.ssaoRatio || ratio;
  74037. var combineRatio = ratio.combineRatio || ratio;
  74038. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74039. _this._createSSAOPostProcess(ssaoRatio);
  74040. _this._createBlurPostProcess(ssaoRatio);
  74041. _this._createSSAOCombinePostProcess(combineRatio);
  74042. // Set up pipeline
  74043. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74044. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74045. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74046. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74047. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74048. // Finish
  74049. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74050. if (cameras)
  74051. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74052. return _this;
  74053. }
  74054. // Public Methods
  74055. /**
  74056. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74057. */
  74058. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74059. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74060. for (var i = 0; i < this._scene.cameras.length; i++) {
  74061. var camera = this._scene.cameras[i];
  74062. this._originalColorPostProcess.dispose(camera);
  74063. this._ssaoPostProcess.dispose(camera);
  74064. this._blurHPostProcess.dispose(camera);
  74065. this._blurVPostProcess.dispose(camera);
  74066. this._ssaoCombinePostProcess.dispose(camera);
  74067. }
  74068. this._randomTexture.dispose();
  74069. if (disableDepthRender)
  74070. this._scene.disableDepthRenderer();
  74071. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74072. _super.prototype.dispose.call(this);
  74073. };
  74074. // Private Methods
  74075. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  74076. var _this = this;
  74077. var size = 16;
  74078. 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);
  74079. 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);
  74080. this._blurHPostProcess.onActivateObservable.add(function () {
  74081. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  74082. _this._blurHPostProcess.kernel = size * dw;
  74083. });
  74084. this._blurVPostProcess.onActivateObservable.add(function () {
  74085. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  74086. _this._blurVPostProcess.kernel = size * dw;
  74087. });
  74088. };
  74089. SSAORenderingPipeline.prototype._rebuild = function () {
  74090. this._firstUpdate = true;
  74091. _super.prototype._rebuild.call(this);
  74092. };
  74093. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74094. var _this = this;
  74095. var numSamples = 16;
  74096. var sampleSphere = [
  74097. 0.5381, 0.1856, -0.4319,
  74098. 0.1379, 0.2486, 0.4430,
  74099. 0.3371, 0.5679, -0.0057,
  74100. -0.6999, -0.0451, -0.0019,
  74101. 0.0689, -0.1598, -0.8547,
  74102. 0.0560, 0.0069, -0.1843,
  74103. -0.0146, 0.1402, 0.0762,
  74104. 0.0100, -0.1924, -0.0344,
  74105. -0.3577, -0.5301, -0.4358,
  74106. -0.3169, 0.1063, 0.0158,
  74107. 0.0103, -0.5869, 0.0046,
  74108. -0.0897, -0.4940, 0.3287,
  74109. 0.7119, -0.0154, -0.0918,
  74110. -0.0533, 0.0596, -0.5411,
  74111. 0.0352, -0.0631, 0.5460,
  74112. -0.4776, 0.2847, -0.0271
  74113. ];
  74114. var samplesFactor = 1.0 / numSamples;
  74115. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  74116. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74117. "area", "fallOff", "base", "range", "viewport"
  74118. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74119. this._ssaoPostProcess.onApply = function (effect) {
  74120. if (_this._firstUpdate) {
  74121. effect.setArray3("sampleSphere", sampleSphere);
  74122. effect.setFloat("samplesFactor", samplesFactor);
  74123. effect.setFloat("randTextureTiles", 4.0);
  74124. }
  74125. effect.setFloat("totalStrength", _this.totalStrength);
  74126. effect.setFloat("radius", _this.radius);
  74127. effect.setFloat("area", _this.area);
  74128. effect.setFloat("fallOff", _this.fallOff);
  74129. effect.setFloat("base", _this.base);
  74130. effect.setTexture("textureSampler", _this._depthTexture);
  74131. effect.setTexture("randomSampler", _this._randomTexture);
  74132. };
  74133. };
  74134. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74135. var _this = this;
  74136. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74137. this._ssaoCombinePostProcess.onApply = function (effect) {
  74138. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  74139. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74140. };
  74141. };
  74142. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  74143. var size = 512;
  74144. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74145. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74146. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74147. var context = this._randomTexture.getContext();
  74148. var rand = function (min, max) {
  74149. return Math.random() * (max - min) + min;
  74150. };
  74151. var randVector = BABYLON.Vector3.Zero();
  74152. for (var x = 0; x < size; x++) {
  74153. for (var y = 0; y < size; y++) {
  74154. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  74155. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  74156. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  74157. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74158. context.fillRect(x, y, 1, 1);
  74159. }
  74160. }
  74161. this._randomTexture.update(false);
  74162. };
  74163. __decorate([
  74164. BABYLON.serialize()
  74165. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  74166. __decorate([
  74167. BABYLON.serialize()
  74168. ], SSAORenderingPipeline.prototype, "radius", void 0);
  74169. __decorate([
  74170. BABYLON.serialize()
  74171. ], SSAORenderingPipeline.prototype, "area", void 0);
  74172. __decorate([
  74173. BABYLON.serialize()
  74174. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  74175. __decorate([
  74176. BABYLON.serialize()
  74177. ], SSAORenderingPipeline.prototype, "base", void 0);
  74178. return SSAORenderingPipeline;
  74179. }(BABYLON.PostProcessRenderPipeline));
  74180. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  74181. })(BABYLON || (BABYLON = {}));
  74182. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  74183. var BABYLON;
  74184. (function (BABYLON) {
  74185. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  74186. __extends(SSAO2RenderingPipeline, _super);
  74187. /**
  74188. * @constructor
  74189. * @param {string} name - The rendering pipeline name
  74190. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74191. * @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 }
  74192. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74193. */
  74194. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74195. var _this = _super.call(this, scene.getEngine(), name) || this;
  74196. // Members
  74197. /**
  74198. * The PassPostProcess id in the pipeline that contains the original scene color
  74199. */
  74200. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74201. /**
  74202. * The SSAO PostProcess id in the pipeline
  74203. */
  74204. _this.SSAORenderEffect = "SSAORenderEffect";
  74205. /**
  74206. * The horizontal blur PostProcess id in the pipeline
  74207. */
  74208. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74209. /**
  74210. * The vertical blur PostProcess id in the pipeline
  74211. */
  74212. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74213. /**
  74214. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74215. */
  74216. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74217. /**
  74218. * The output strength of the SSAO post-process. Default value is 1.0.
  74219. */
  74220. _this.totalStrength = 1.0;
  74221. /**
  74222. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74223. */
  74224. _this.maxZ = 100.0;
  74225. /**
  74226. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74227. */
  74228. _this.minZAspect = 0.2;
  74229. /**
  74230. * Number of samples used for the SSAO calculations. Default value is 8
  74231. */
  74232. _this._samples = 8;
  74233. /**
  74234. * Are we using bilateral blur ?
  74235. */
  74236. _this._expensiveBlur = true;
  74237. /**
  74238. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74239. */
  74240. _this.radius = 2.0;
  74241. /**
  74242. * The base color of the SSAO post-process
  74243. * The final result is "base + ssao" between [0, 1]
  74244. */
  74245. _this.base = 0.1;
  74246. _this._firstUpdate = true;
  74247. _this._scene = scene;
  74248. _this._ratio = ratio;
  74249. if (!_this.isSupported) {
  74250. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74251. return _this;
  74252. }
  74253. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74254. var blurRatio = _this._ratio.blurRatio || ratio;
  74255. // Set up assets
  74256. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74257. _this._createRandomTexture();
  74258. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74259. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74260. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74261. _this._createSSAOPostProcess(1.0);
  74262. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74263. _this._createSSAOCombinePostProcess(blurRatio);
  74264. // Set up pipeline
  74265. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74266. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74267. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74268. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74269. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74270. // Finish
  74271. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74272. if (cameras)
  74273. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74274. return _this;
  74275. }
  74276. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74277. get: function () {
  74278. return this._samples;
  74279. },
  74280. set: function (n) {
  74281. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74282. this._samples = n;
  74283. this._sampleSphere = this._generateHemisphere();
  74284. this._firstUpdate = true;
  74285. },
  74286. enumerable: true,
  74287. configurable: true
  74288. });
  74289. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74290. get: function () {
  74291. return this._expensiveBlur;
  74292. },
  74293. set: function (b) {
  74294. 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"]);
  74295. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74296. this._expensiveBlur = b;
  74297. this._firstUpdate = true;
  74298. },
  74299. enumerable: true,
  74300. configurable: true
  74301. });
  74302. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74303. /**
  74304. * Support test.
  74305. */
  74306. get: function () {
  74307. var engine = BABYLON.Engine.LastCreatedEngine;
  74308. if (!engine) {
  74309. return false;
  74310. }
  74311. return engine.getCaps().drawBuffersExtension;
  74312. },
  74313. enumerable: true,
  74314. configurable: true
  74315. });
  74316. // Public Methods
  74317. /**
  74318. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74319. */
  74320. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74321. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74322. for (var i = 0; i < this._scene.cameras.length; i++) {
  74323. var camera = this._scene.cameras[i];
  74324. this._originalColorPostProcess.dispose(camera);
  74325. this._ssaoPostProcess.dispose(camera);
  74326. this._blurHPostProcess.dispose(camera);
  74327. this._blurVPostProcess.dispose(camera);
  74328. this._ssaoCombinePostProcess.dispose(camera);
  74329. }
  74330. this._randomTexture.dispose();
  74331. if (disableGeometryBufferRenderer)
  74332. this._scene.disableGeometryBufferRenderer();
  74333. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74334. _super.prototype.dispose.call(this);
  74335. };
  74336. // Private Methods
  74337. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74338. var _this = this;
  74339. this._samplerOffsets = [];
  74340. var expensive = this.expensiveBlur;
  74341. for (var i = -8; i < 8; i++) {
  74342. this._samplerOffsets.push(i * 2 + 0.5);
  74343. }
  74344. 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");
  74345. this._blurHPostProcess.onApply = function (effect) {
  74346. if (!_this._scene.activeCamera) {
  74347. return;
  74348. }
  74349. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74350. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74351. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74352. effect.setFloat("radius", _this.radius);
  74353. effect.setTexture("depthSampler", _this._depthTexture);
  74354. if (_this._firstUpdate) {
  74355. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74356. }
  74357. };
  74358. 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");
  74359. this._blurVPostProcess.onApply = function (effect) {
  74360. if (!_this._scene.activeCamera) {
  74361. return;
  74362. }
  74363. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74364. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74365. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74366. effect.setFloat("radius", _this.radius);
  74367. effect.setTexture("depthSampler", _this._depthTexture);
  74368. if (_this._firstUpdate) {
  74369. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74370. _this._firstUpdate = false;
  74371. }
  74372. };
  74373. };
  74374. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74375. this._firstUpdate = true;
  74376. _super.prototype._rebuild.call(this);
  74377. };
  74378. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74379. var numSamples = this.samples;
  74380. var result = [];
  74381. var vector, scale;
  74382. var rand = function (min, max) {
  74383. return Math.random() * (max - min) + min;
  74384. };
  74385. var i = 0;
  74386. while (i < numSamples) {
  74387. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74388. vector.normalize();
  74389. scale = i / numSamples;
  74390. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74391. vector.scaleInPlace(scale);
  74392. result.push(vector.x, vector.y, vector.z);
  74393. i++;
  74394. }
  74395. return result;
  74396. };
  74397. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74398. var _this = this;
  74399. var numSamples = this.samples;
  74400. this._sampleSphere = this._generateHemisphere();
  74401. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74402. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74403. "base", "range", "projection", "near", "far", "texelSize",
  74404. "xViewport", "yViewport", "maxZ", "minZAspect"
  74405. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74406. this._ssaoPostProcess.onApply = function (effect) {
  74407. if (_this._firstUpdate) {
  74408. effect.setArray3("sampleSphere", _this._sampleSphere);
  74409. effect.setFloat("randTextureTiles", 4.0);
  74410. }
  74411. if (!_this._scene.activeCamera) {
  74412. return;
  74413. }
  74414. effect.setFloat("samplesFactor", 1 / _this.samples);
  74415. effect.setFloat("totalStrength", _this.totalStrength);
  74416. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74417. effect.setFloat("radius", _this.radius);
  74418. effect.setFloat("maxZ", _this.maxZ);
  74419. effect.setFloat("minZAspect", _this.minZAspect);
  74420. effect.setFloat("base", _this.base);
  74421. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74422. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74423. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74424. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74425. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74426. effect.setTexture("textureSampler", _this._depthTexture);
  74427. effect.setTexture("normalSampler", _this._normalTexture);
  74428. effect.setTexture("randomSampler", _this._randomTexture);
  74429. };
  74430. };
  74431. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74432. var _this = this;
  74433. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74434. this._ssaoCombinePostProcess.onApply = function (effect) {
  74435. var viewport = _this._scene.activeCamera.viewport;
  74436. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74437. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74438. };
  74439. };
  74440. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74441. var size = 512;
  74442. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74443. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74444. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74445. var context = this._randomTexture.getContext();
  74446. var rand = function (min, max) {
  74447. return Math.random() * (max - min) + min;
  74448. };
  74449. var randVector = BABYLON.Vector3.Zero();
  74450. for (var x = 0; x < size; x++) {
  74451. for (var y = 0; y < size; y++) {
  74452. randVector.x = rand(0.0, 1.0);
  74453. randVector.y = rand(0.0, 1.0);
  74454. randVector.z = 0.0;
  74455. randVector.normalize();
  74456. randVector.scaleInPlace(255);
  74457. randVector.x = Math.floor(randVector.x);
  74458. randVector.y = Math.floor(randVector.y);
  74459. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74460. context.fillRect(x, y, 1, 1);
  74461. }
  74462. }
  74463. this._randomTexture.update(false);
  74464. };
  74465. /**
  74466. * Serialize the rendering pipeline (Used when exporting)
  74467. * @returns the serialized object
  74468. */
  74469. SSAO2RenderingPipeline.prototype.serialize = function () {
  74470. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74471. serializationObject.customType = "SSAO2RenderingPipeline";
  74472. return serializationObject;
  74473. };
  74474. /**
  74475. * Parse the serialized pipeline
  74476. * @param source Source pipeline.
  74477. * @param scene The scene to load the pipeline to.
  74478. * @param rootUrl The URL of the serialized pipeline.
  74479. * @returns An instantiated pipeline from the serialized object.
  74480. */
  74481. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74482. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74483. };
  74484. __decorate([
  74485. BABYLON.serialize()
  74486. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74487. __decorate([
  74488. BABYLON.serialize()
  74489. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74490. __decorate([
  74491. BABYLON.serialize()
  74492. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74493. __decorate([
  74494. BABYLON.serialize("samples")
  74495. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74496. __decorate([
  74497. BABYLON.serialize()
  74498. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74499. __decorate([
  74500. BABYLON.serialize("expensiveBlur")
  74501. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74502. __decorate([
  74503. BABYLON.serialize()
  74504. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74505. __decorate([
  74506. BABYLON.serialize()
  74507. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74508. return SSAO2RenderingPipeline;
  74509. }(BABYLON.PostProcessRenderPipeline));
  74510. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74511. })(BABYLON || (BABYLON = {}));
  74512. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74513. // BABYLON.JS Chromatic Aberration GLSL Shader
  74514. // Author: Olivier Guyot
  74515. // Separates very slightly R, G and B colors on the edges of the screen
  74516. // Inspired by Francois Tarlier & Martins Upitis
  74517. var BABYLON;
  74518. (function (BABYLON) {
  74519. var LensRenderingPipeline = /** @class */ (function (_super) {
  74520. __extends(LensRenderingPipeline, _super);
  74521. /**
  74522. * @constructor
  74523. *
  74524. * Effect parameters are as follow:
  74525. * {
  74526. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74527. * edge_blur: number; // from 0 to x (1 for realism)
  74528. * distortion: number; // from 0 to x (1 for realism)
  74529. * grain_amount: number; // from 0 to 1
  74530. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74531. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74532. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74533. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74534. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74535. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74536. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74537. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74538. * }
  74539. * Note: if an effect parameter is unset, effect is disabled
  74540. *
  74541. * @param {string} name - The rendering pipeline name
  74542. * @param {object} parameters - An object containing all parameters (see above)
  74543. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74544. * @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)
  74545. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74546. */
  74547. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74548. if (ratio === void 0) { ratio = 1.0; }
  74549. var _this = _super.call(this, scene.getEngine(), name) || this;
  74550. // Lens effects can be of the following:
  74551. // - chromatic aberration (slight shift of RGB colors)
  74552. // - blur on the edge of the lens
  74553. // - lens distortion
  74554. // - depth-of-field blur & highlights enhancing
  74555. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74556. // - grain effect (noise or custom texture)
  74557. // Two additional texture samplers are needed:
  74558. // - depth map (for depth-of-field)
  74559. // - grain texture
  74560. /**
  74561. * The chromatic aberration PostProcess id in the pipeline
  74562. */
  74563. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74564. /**
  74565. * The highlights enhancing PostProcess id in the pipeline
  74566. */
  74567. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74568. /**
  74569. * The depth-of-field PostProcess id in the pipeline
  74570. */
  74571. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74572. _this._scene = scene;
  74573. // Fetch texture samplers
  74574. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74575. if (parameters.grain_texture) {
  74576. _this._grainTexture = parameters.grain_texture;
  74577. }
  74578. else {
  74579. _this._createGrainTexture();
  74580. }
  74581. // save parameters
  74582. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74583. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74584. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74585. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74586. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74587. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74588. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74589. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74590. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74591. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74592. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74593. // Create effects
  74594. _this._createChromaticAberrationPostProcess(ratio);
  74595. _this._createHighlightsPostProcess(ratio);
  74596. _this._createDepthOfFieldPostProcess(ratio / 4);
  74597. // Set up pipeline
  74598. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74599. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74600. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74601. if (_this._highlightsGain === -1) {
  74602. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74603. }
  74604. // Finish
  74605. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74606. if (cameras) {
  74607. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74608. }
  74609. return _this;
  74610. }
  74611. // public methods (self explanatory)
  74612. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74613. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74614. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74615. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74616. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74617. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74618. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74619. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74620. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74621. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74622. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74623. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74624. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74625. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74626. };
  74627. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74628. this._highlightsPostProcess.updateEffect();
  74629. };
  74630. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74631. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74632. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74633. this._highlightsGain = amount;
  74634. };
  74635. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74636. if (this._highlightsGain === -1) {
  74637. this._highlightsGain = 1.0;
  74638. }
  74639. this._highlightsThreshold = amount;
  74640. };
  74641. LensRenderingPipeline.prototype.disableHighlights = function () {
  74642. this._highlightsGain = -1;
  74643. };
  74644. /**
  74645. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74646. */
  74647. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74648. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74649. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74650. this._chromaticAberrationPostProcess = null;
  74651. this._highlightsPostProcess = null;
  74652. this._depthOfFieldPostProcess = null;
  74653. this._grainTexture.dispose();
  74654. if (disableDepthRender)
  74655. this._scene.disableDepthRenderer();
  74656. };
  74657. // colors shifting and distortion
  74658. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74659. var _this = this;
  74660. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74661. [], // samplers
  74662. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74663. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74664. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74665. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74666. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74667. effect.setFloat('radialIntensity', 1);
  74668. effect.setFloat2('direction', 17, 17);
  74669. effect.setFloat2('centerPosition', 0.5, 0.5);
  74670. };
  74671. };
  74672. // highlights enhancing
  74673. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74674. var _this = this;
  74675. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74676. [], // samplers
  74677. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74678. this._highlightsPostProcess.onApply = function (effect) {
  74679. effect.setFloat('gain', _this._highlightsGain);
  74680. effect.setFloat('threshold', _this._highlightsThreshold);
  74681. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74682. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74683. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74684. };
  74685. };
  74686. // colors shifting and distortion
  74687. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74688. var _this = this;
  74689. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74690. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74691. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74692. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74693. this._depthOfFieldPostProcess.onApply = function (effect) {
  74694. effect.setTexture("depthSampler", _this._depthTexture);
  74695. effect.setTexture("grainSampler", _this._grainTexture);
  74696. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74697. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74698. effect.setFloat('grain_amount', _this._grainAmount);
  74699. effect.setBool('blur_noise', _this._blurNoise);
  74700. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74701. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74702. effect.setFloat('distortion', _this._distortion);
  74703. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74704. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74705. effect.setFloat('aperture', _this._dofAperture);
  74706. effect.setFloat('darken', _this._dofDarken);
  74707. effect.setFloat('edge_blur', _this._edgeBlur);
  74708. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74709. if (_this._scene.activeCamera) {
  74710. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74711. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74712. }
  74713. };
  74714. };
  74715. // creates a black and white random noise texture, 512x512
  74716. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74717. var size = 512;
  74718. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74719. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74720. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74721. var context = this._grainTexture.getContext();
  74722. var rand = function (min, max) {
  74723. return Math.random() * (max - min) + min;
  74724. };
  74725. var value;
  74726. for (var x = 0; x < size; x++) {
  74727. for (var y = 0; y < size; y++) {
  74728. value = Math.floor(rand(0.42, 0.58) * 255);
  74729. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74730. context.fillRect(x, y, 1, 1);
  74731. }
  74732. }
  74733. this._grainTexture.update(false);
  74734. };
  74735. return LensRenderingPipeline;
  74736. }(BABYLON.PostProcessRenderPipeline));
  74737. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74738. })(BABYLON || (BABYLON = {}));
  74739. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74740. var BABYLON;
  74741. (function (BABYLON) {
  74742. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74743. __extends(StandardRenderingPipeline, _super);
  74744. /**
  74745. * @constructor
  74746. * @param {string} name - The rendering pipeline name
  74747. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74748. * @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)
  74749. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74750. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74751. */
  74752. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74753. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74754. var _this = _super.call(this, scene.getEngine(), name) || this;
  74755. _this.downSampleX4PostProcess = null;
  74756. _this.brightPassPostProcess = null;
  74757. _this.blurHPostProcesses = [];
  74758. _this.blurVPostProcesses = [];
  74759. _this.textureAdderPostProcess = null;
  74760. _this.volumetricLightPostProcess = null;
  74761. _this.volumetricLightSmoothXPostProcess = null;
  74762. _this.volumetricLightSmoothYPostProcess = null;
  74763. _this.volumetricLightMergePostProces = null;
  74764. _this.volumetricLightFinalPostProcess = null;
  74765. _this.luminancePostProcess = null;
  74766. _this.luminanceDownSamplePostProcesses = [];
  74767. _this.hdrPostProcess = null;
  74768. _this.textureAdderFinalPostProcess = null;
  74769. _this.lensFlareFinalPostProcess = null;
  74770. _this.hdrFinalPostProcess = null;
  74771. _this.lensFlarePostProcess = null;
  74772. _this.lensFlareComposePostProcess = null;
  74773. _this.motionBlurPostProcess = null;
  74774. _this.depthOfFieldPostProcess = null;
  74775. // Values
  74776. _this.brightThreshold = 1.0;
  74777. _this.blurWidth = 512.0;
  74778. _this.horizontalBlur = false;
  74779. _this.exposure = 1.0;
  74780. _this.lensTexture = null;
  74781. _this.volumetricLightCoefficient = 0.2;
  74782. _this.volumetricLightPower = 4.0;
  74783. _this.volumetricLightBlurScale = 64.0;
  74784. _this.sourceLight = null;
  74785. _this.hdrMinimumLuminance = 1.0;
  74786. _this.hdrDecreaseRate = 0.5;
  74787. _this.hdrIncreaseRate = 0.5;
  74788. _this.lensColorTexture = null;
  74789. _this.lensFlareStrength = 20.0;
  74790. _this.lensFlareGhostDispersal = 1.4;
  74791. _this.lensFlareHaloWidth = 0.7;
  74792. _this.lensFlareDistortionStrength = 16.0;
  74793. _this.lensStarTexture = null;
  74794. _this.lensFlareDirtTexture = null;
  74795. _this.depthOfFieldDistance = 10.0;
  74796. _this.depthOfFieldBlurWidth = 64.0;
  74797. _this.motionStrength = 1.0;
  74798. // IAnimatable
  74799. _this.animations = [];
  74800. _this._currentDepthOfFieldSource = null;
  74801. _this._hdrCurrentLuminance = 1.0;
  74802. // Getters and setters
  74803. _this._bloomEnabled = true;
  74804. _this._depthOfFieldEnabled = false;
  74805. _this._vlsEnabled = false;
  74806. _this._lensFlareEnabled = false;
  74807. _this._hdrEnabled = false;
  74808. _this._motionBlurEnabled = false;
  74809. _this._motionBlurSamples = 64.0;
  74810. _this._volumetricLightStepsCount = 50.0;
  74811. _this._cameras = cameras || [];
  74812. // Initialize
  74813. _this._scene = scene;
  74814. _this._basePostProcess = originalPostProcess;
  74815. _this._ratio = ratio;
  74816. // Misc
  74817. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74818. // Finish
  74819. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74820. _this._buildPipeline();
  74821. return _this;
  74822. }
  74823. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74824. get: function () {
  74825. return this._bloomEnabled;
  74826. },
  74827. set: function (enabled) {
  74828. if (this._bloomEnabled === enabled) {
  74829. return;
  74830. }
  74831. this._bloomEnabled = enabled;
  74832. this._buildPipeline();
  74833. },
  74834. enumerable: true,
  74835. configurable: true
  74836. });
  74837. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74838. get: function () {
  74839. return this._depthOfFieldEnabled;
  74840. },
  74841. set: function (enabled) {
  74842. if (this._depthOfFieldEnabled === enabled) {
  74843. return;
  74844. }
  74845. this._depthOfFieldEnabled = enabled;
  74846. this._buildPipeline();
  74847. },
  74848. enumerable: true,
  74849. configurable: true
  74850. });
  74851. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74852. get: function () {
  74853. return this._lensFlareEnabled;
  74854. },
  74855. set: function (enabled) {
  74856. if (this._lensFlareEnabled === enabled) {
  74857. return;
  74858. }
  74859. this._lensFlareEnabled = enabled;
  74860. this._buildPipeline();
  74861. },
  74862. enumerable: true,
  74863. configurable: true
  74864. });
  74865. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74866. get: function () {
  74867. return this._hdrEnabled;
  74868. },
  74869. set: function (enabled) {
  74870. if (this._hdrEnabled === enabled) {
  74871. return;
  74872. }
  74873. this._hdrEnabled = enabled;
  74874. this._buildPipeline();
  74875. },
  74876. enumerable: true,
  74877. configurable: true
  74878. });
  74879. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74880. get: function () {
  74881. return this._vlsEnabled;
  74882. },
  74883. set: function (enabled) {
  74884. if (this._vlsEnabled === enabled) {
  74885. return;
  74886. }
  74887. if (enabled) {
  74888. var geometry = this._scene.enableGeometryBufferRenderer();
  74889. if (!geometry) {
  74890. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74891. return;
  74892. }
  74893. }
  74894. this._vlsEnabled = enabled;
  74895. this._buildPipeline();
  74896. },
  74897. enumerable: true,
  74898. configurable: true
  74899. });
  74900. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74901. get: function () {
  74902. return this._motionBlurEnabled;
  74903. },
  74904. set: function (enabled) {
  74905. if (this._motionBlurEnabled === enabled) {
  74906. return;
  74907. }
  74908. this._motionBlurEnabled = enabled;
  74909. this._buildPipeline();
  74910. },
  74911. enumerable: true,
  74912. configurable: true
  74913. });
  74914. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74915. get: function () {
  74916. return this._volumetricLightStepsCount;
  74917. },
  74918. set: function (count) {
  74919. if (this.volumetricLightPostProcess) {
  74920. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74921. }
  74922. this._volumetricLightStepsCount = count;
  74923. },
  74924. enumerable: true,
  74925. configurable: true
  74926. });
  74927. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74928. get: function () {
  74929. return this._motionBlurSamples;
  74930. },
  74931. set: function (samples) {
  74932. if (this.motionBlurPostProcess) {
  74933. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74934. }
  74935. this._motionBlurSamples = samples;
  74936. },
  74937. enumerable: true,
  74938. configurable: true
  74939. });
  74940. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74941. var _this = this;
  74942. var ratio = this._ratio;
  74943. var scene = this._scene;
  74944. this._disposePostProcesses();
  74945. this._reset();
  74946. // Create pass post-process
  74947. if (!this._basePostProcess) {
  74948. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74949. this.originalPostProcess.onApply = function (effect) {
  74950. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74951. };
  74952. }
  74953. else {
  74954. this.originalPostProcess = this._basePostProcess;
  74955. }
  74956. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74957. this._currentDepthOfFieldSource = this.originalPostProcess;
  74958. if (this._bloomEnabled) {
  74959. // Create down sample X4 post-process
  74960. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74961. // Create bright pass post-process
  74962. this._createBrightPassPostProcess(scene, ratio / 2);
  74963. // Create gaussian blur post-processes (down sampling blurs)
  74964. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74965. // Create texture adder post-process
  74966. this._createTextureAdderPostProcess(scene, ratio);
  74967. // Create depth-of-field source post-process
  74968. 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);
  74969. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74970. }
  74971. if (this._vlsEnabled) {
  74972. // Create volumetric light
  74973. this._createVolumetricLightPostProcess(scene, ratio);
  74974. // Create volumetric light final post-process
  74975. 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);
  74976. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74977. }
  74978. if (this._lensFlareEnabled) {
  74979. // Create lens flare post-process
  74980. this._createLensFlarePostProcess(scene, ratio);
  74981. // Create depth-of-field source post-process post lens-flare and disable it now
  74982. 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);
  74983. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74984. }
  74985. if (this._hdrEnabled) {
  74986. // Create luminance
  74987. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74988. // Create HDR
  74989. this._createHdrPostProcess(scene, ratio);
  74990. // Create depth-of-field source post-process post hdr and disable it now
  74991. 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);
  74992. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74993. }
  74994. if (this._depthOfFieldEnabled) {
  74995. // Create gaussian blur used by depth-of-field
  74996. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74997. // Create depth-of-field post-process
  74998. this._createDepthOfFieldPostProcess(scene, ratio);
  74999. }
  75000. if (this._motionBlurEnabled) {
  75001. // Create motion blur post-process
  75002. this._createMotionBlurPostProcess(scene, ratio);
  75003. }
  75004. if (this._cameras !== null) {
  75005. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75006. }
  75007. };
  75008. // Down Sample X4 Post-Processs
  75009. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  75010. var _this = this;
  75011. var downSampleX4Offsets = new Array(32);
  75012. 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);
  75013. this.downSampleX4PostProcess.onApply = function (effect) {
  75014. var id = 0;
  75015. var width = _this.downSampleX4PostProcess.width;
  75016. var height = _this.downSampleX4PostProcess.height;
  75017. for (var i = -2; i < 2; i++) {
  75018. for (var j = -2; j < 2; j++) {
  75019. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  75020. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  75021. id += 2;
  75022. }
  75023. }
  75024. effect.setArray2("dsOffsets", downSampleX4Offsets);
  75025. };
  75026. // Add to pipeline
  75027. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  75028. };
  75029. // Brightpass Post-Process
  75030. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  75031. var _this = this;
  75032. var brightOffsets = new Array(8);
  75033. 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);
  75034. this.brightPassPostProcess.onApply = function (effect) {
  75035. var sU = (1.0 / _this.brightPassPostProcess.width);
  75036. var sV = (1.0 / _this.brightPassPostProcess.height);
  75037. brightOffsets[0] = -0.5 * sU;
  75038. brightOffsets[1] = 0.5 * sV;
  75039. brightOffsets[2] = 0.5 * sU;
  75040. brightOffsets[3] = 0.5 * sV;
  75041. brightOffsets[4] = -0.5 * sU;
  75042. brightOffsets[5] = -0.5 * sV;
  75043. brightOffsets[6] = 0.5 * sU;
  75044. brightOffsets[7] = -0.5 * sV;
  75045. effect.setArray2("dsOffsets", brightOffsets);
  75046. effect.setFloat("brightThreshold", _this.brightThreshold);
  75047. };
  75048. // Add to pipeline
  75049. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  75050. };
  75051. // Create blur H&V post-processes
  75052. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  75053. var _this = this;
  75054. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  75055. var engine = scene.getEngine();
  75056. 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);
  75057. 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);
  75058. blurX.onActivateObservable.add(function () {
  75059. var dw = blurX.width / engine.getRenderWidth();
  75060. blurX.kernel = _this[blurWidthKey] * dw;
  75061. });
  75062. blurY.onActivateObservable.add(function () {
  75063. var dw = blurY.height / engine.getRenderHeight();
  75064. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  75065. });
  75066. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  75067. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  75068. this.blurHPostProcesses.push(blurX);
  75069. this.blurVPostProcesses.push(blurY);
  75070. };
  75071. // Create texture adder post-process
  75072. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  75073. var _this = this;
  75074. 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);
  75075. this.textureAdderPostProcess.onApply = function (effect) {
  75076. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  75077. effect.setTexture("lensSampler", _this.lensTexture);
  75078. effect.setFloat("exposure", _this.exposure);
  75079. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  75080. };
  75081. // Add to pipeline
  75082. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  75083. };
  75084. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  75085. var _this = this;
  75086. var geometryRenderer = scene.enableGeometryBufferRenderer();
  75087. geometryRenderer.enablePosition = true;
  75088. var geometry = geometryRenderer.getGBuffer();
  75089. // Base post-process
  75090. 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));
  75091. var depthValues = BABYLON.Vector2.Zero();
  75092. this.volumetricLightPostProcess.onApply = function (effect) {
  75093. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  75094. var generator = _this.sourceLight.getShadowGenerator();
  75095. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  75096. effect.setTexture("positionSampler", geometry.textures[2]);
  75097. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  75098. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  75099. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  75100. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  75101. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  75102. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  75103. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  75104. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  75105. effect.setVector2("depthValues", depthValues);
  75106. }
  75107. };
  75108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  75109. // Smooth
  75110. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  75111. // Merge
  75112. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  75113. this.volumetricLightMergePostProces.onApply = function (effect) {
  75114. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  75115. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  75116. };
  75117. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  75118. };
  75119. // Create luminance
  75120. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  75121. var _this = this;
  75122. // Create luminance
  75123. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  75124. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  75125. var offsets = [];
  75126. this.luminancePostProcess.onApply = function (effect) {
  75127. var sU = (1.0 / _this.luminancePostProcess.width);
  75128. var sV = (1.0 / _this.luminancePostProcess.height);
  75129. offsets[0] = -0.5 * sU;
  75130. offsets[1] = 0.5 * sV;
  75131. offsets[2] = 0.5 * sU;
  75132. offsets[3] = 0.5 * sV;
  75133. offsets[4] = -0.5 * sU;
  75134. offsets[5] = -0.5 * sV;
  75135. offsets[6] = 0.5 * sU;
  75136. offsets[7] = -0.5 * sV;
  75137. effect.setArray2("lumOffsets", offsets);
  75138. };
  75139. // Add to pipeline
  75140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  75141. // Create down sample luminance
  75142. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  75143. var size = Math.pow(3, i);
  75144. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  75145. if (i === 0) {
  75146. defines += "#define FINAL_DOWN_SAMPLER";
  75147. }
  75148. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  75149. this.luminanceDownSamplePostProcesses.push(postProcess);
  75150. }
  75151. // Create callbacks and add effects
  75152. var lastLuminance = this.luminancePostProcess;
  75153. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  75154. var downSampleOffsets = new Array(18);
  75155. pp.onApply = function (effect) {
  75156. if (!lastLuminance) {
  75157. return;
  75158. }
  75159. var id = 0;
  75160. for (var x = -1; x < 2; x++) {
  75161. for (var y = -1; y < 2; y++) {
  75162. downSampleOffsets[id] = x / lastLuminance.width;
  75163. downSampleOffsets[id + 1] = y / lastLuminance.height;
  75164. id += 2;
  75165. }
  75166. }
  75167. effect.setArray2("dsOffsets", downSampleOffsets);
  75168. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  75169. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75170. lastLuminance = _this.luminancePostProcess;
  75171. }
  75172. else {
  75173. lastLuminance = pp;
  75174. }
  75175. };
  75176. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75177. pp.onAfterRender = function (effect) {
  75178. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  75179. 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);
  75180. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  75181. };
  75182. }
  75183. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  75184. });
  75185. };
  75186. // Create HDR post-process
  75187. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  75188. var _this = this;
  75189. 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);
  75190. var outputLiminance = 1;
  75191. var time = 0;
  75192. var lastTime = 0;
  75193. this.hdrPostProcess.onApply = function (effect) {
  75194. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75195. time += scene.getEngine().getDeltaTime();
  75196. if (outputLiminance < 0) {
  75197. outputLiminance = _this._hdrCurrentLuminance;
  75198. }
  75199. else {
  75200. var dt = (lastTime - time) / 1000.0;
  75201. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75202. outputLiminance += _this.hdrDecreaseRate * dt;
  75203. }
  75204. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75205. outputLiminance -= _this.hdrIncreaseRate * dt;
  75206. }
  75207. else {
  75208. outputLiminance = _this._hdrCurrentLuminance;
  75209. }
  75210. }
  75211. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75212. effect.setFloat("averageLuminance", outputLiminance);
  75213. lastTime = time;
  75214. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75215. };
  75216. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75217. };
  75218. // Create lens flare post-process
  75219. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75220. var _this = this;
  75221. 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);
  75222. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75223. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75224. 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);
  75225. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75226. var resolution = new BABYLON.Vector2(0, 0);
  75227. // Lens flare
  75228. this.lensFlarePostProcess.onApply = function (effect) {
  75229. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75230. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75231. effect.setFloat("strength", _this.lensFlareStrength);
  75232. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75233. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75234. // Shift
  75235. resolution.x = _this.lensFlarePostProcess.width;
  75236. resolution.y = _this.lensFlarePostProcess.height;
  75237. effect.setVector2("resolution", resolution);
  75238. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75239. };
  75240. // Compose
  75241. 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);
  75242. 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);
  75243. this.lensFlareComposePostProcess.onApply = function (effect) {
  75244. if (!_this._scene.activeCamera) {
  75245. return;
  75246. }
  75247. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75248. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75249. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75250. // Lens start rotation matrix
  75251. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75252. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75253. 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));
  75254. camRot *= 4.0;
  75255. 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);
  75256. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75257. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75258. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75259. };
  75260. };
  75261. // Create depth-of-field post-process
  75262. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75263. var _this = this;
  75264. 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);
  75265. this.depthOfFieldPostProcess.onApply = function (effect) {
  75266. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75267. effect.setTexture("depthSampler", _this._getDepthTexture());
  75268. effect.setFloat("distance", _this.depthOfFieldDistance);
  75269. };
  75270. // Add to pipeline
  75271. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75272. };
  75273. // Create motion blur post-process
  75274. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75275. var _this = this;
  75276. 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);
  75277. var motionScale = 0;
  75278. var prevViewProjection = BABYLON.Matrix.Identity();
  75279. var invViewProjection = BABYLON.Matrix.Identity();
  75280. var viewProjection = BABYLON.Matrix.Identity();
  75281. var screenSize = BABYLON.Vector2.Zero();
  75282. this.motionBlurPostProcess.onApply = function (effect) {
  75283. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75284. viewProjection.invertToRef(invViewProjection);
  75285. effect.setMatrix("inverseViewProjection", invViewProjection);
  75286. effect.setMatrix("prevViewProjection", prevViewProjection);
  75287. prevViewProjection = viewProjection;
  75288. screenSize.x = _this.motionBlurPostProcess.width;
  75289. screenSize.y = _this.motionBlurPostProcess.height;
  75290. effect.setVector2("screenSize", screenSize);
  75291. motionScale = scene.getEngine().getFps() / 60.0;
  75292. effect.setFloat("motionScale", motionScale);
  75293. effect.setFloat("motionStrength", _this.motionStrength);
  75294. effect.setTexture("depthSampler", _this._getDepthTexture());
  75295. };
  75296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75297. };
  75298. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75299. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75300. var renderer = this._scene.enableGeometryBufferRenderer();
  75301. return renderer.getGBuffer().textures[0];
  75302. }
  75303. return this._scene.enableDepthRenderer().getDepthMap();
  75304. };
  75305. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75306. for (var i = 0; i < this._cameras.length; i++) {
  75307. var camera = this._cameras[i];
  75308. if (this.originalPostProcess) {
  75309. this.originalPostProcess.dispose(camera);
  75310. }
  75311. if (this.downSampleX4PostProcess) {
  75312. this.downSampleX4PostProcess.dispose(camera);
  75313. }
  75314. if (this.brightPassPostProcess) {
  75315. this.brightPassPostProcess.dispose(camera);
  75316. }
  75317. if (this.textureAdderPostProcess) {
  75318. this.textureAdderPostProcess.dispose(camera);
  75319. }
  75320. if (this.textureAdderFinalPostProcess) {
  75321. this.textureAdderFinalPostProcess.dispose(camera);
  75322. }
  75323. if (this.volumetricLightPostProcess) {
  75324. this.volumetricLightPostProcess.dispose(camera);
  75325. }
  75326. if (this.volumetricLightSmoothXPostProcess) {
  75327. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75328. }
  75329. if (this.volumetricLightSmoothYPostProcess) {
  75330. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75331. }
  75332. if (this.volumetricLightMergePostProces) {
  75333. this.volumetricLightMergePostProces.dispose(camera);
  75334. }
  75335. if (this.volumetricLightFinalPostProcess) {
  75336. this.volumetricLightFinalPostProcess.dispose(camera);
  75337. }
  75338. if (this.lensFlarePostProcess) {
  75339. this.lensFlarePostProcess.dispose(camera);
  75340. }
  75341. if (this.lensFlareComposePostProcess) {
  75342. this.lensFlareComposePostProcess.dispose(camera);
  75343. }
  75344. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75345. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75346. }
  75347. if (this.luminancePostProcess) {
  75348. this.luminancePostProcess.dispose(camera);
  75349. }
  75350. if (this.hdrPostProcess) {
  75351. this.hdrPostProcess.dispose(camera);
  75352. }
  75353. if (this.hdrFinalPostProcess) {
  75354. this.hdrFinalPostProcess.dispose(camera);
  75355. }
  75356. if (this.depthOfFieldPostProcess) {
  75357. this.depthOfFieldPostProcess.dispose(camera);
  75358. }
  75359. if (this.motionBlurPostProcess) {
  75360. this.motionBlurPostProcess.dispose(camera);
  75361. }
  75362. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75363. this.blurHPostProcesses[j].dispose(camera);
  75364. }
  75365. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75366. this.blurVPostProcesses[j].dispose(camera);
  75367. }
  75368. }
  75369. this.originalPostProcess = null;
  75370. this.downSampleX4PostProcess = null;
  75371. this.brightPassPostProcess = null;
  75372. this.textureAdderPostProcess = null;
  75373. this.textureAdderFinalPostProcess = null;
  75374. this.volumetricLightPostProcess = null;
  75375. this.volumetricLightSmoothXPostProcess = null;
  75376. this.volumetricLightSmoothYPostProcess = null;
  75377. this.volumetricLightMergePostProces = null;
  75378. this.volumetricLightFinalPostProcess = null;
  75379. this.lensFlarePostProcess = null;
  75380. this.lensFlareComposePostProcess = null;
  75381. this.luminancePostProcess = null;
  75382. this.hdrPostProcess = null;
  75383. this.hdrFinalPostProcess = null;
  75384. this.depthOfFieldPostProcess = null;
  75385. this.motionBlurPostProcess = null;
  75386. this.luminanceDownSamplePostProcesses = [];
  75387. this.blurHPostProcesses = [];
  75388. this.blurVPostProcesses = [];
  75389. };
  75390. /**
  75391. * Dispose of the pipeline and stop all post processes
  75392. */
  75393. StandardRenderingPipeline.prototype.dispose = function () {
  75394. this._disposePostProcesses();
  75395. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75396. _super.prototype.dispose.call(this);
  75397. };
  75398. /**
  75399. * Serialize the rendering pipeline (Used when exporting)
  75400. * @returns the serialized object
  75401. */
  75402. StandardRenderingPipeline.prototype.serialize = function () {
  75403. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75404. if (this.sourceLight) {
  75405. serializationObject.sourceLightId = this.sourceLight.id;
  75406. }
  75407. serializationObject.customType = "StandardRenderingPipeline";
  75408. return serializationObject;
  75409. };
  75410. /**
  75411. * Parse the serialized pipeline
  75412. * @param source Source pipeline.
  75413. * @param scene The scene to load the pipeline to.
  75414. * @param rootUrl The URL of the serialized pipeline.
  75415. * @returns An instantiated pipeline from the serialized object.
  75416. */
  75417. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75418. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75419. if (source.sourceLightId) {
  75420. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75421. }
  75422. return p;
  75423. };
  75424. // Luminance steps
  75425. StandardRenderingPipeline.LuminanceSteps = 6;
  75426. __decorate([
  75427. BABYLON.serialize()
  75428. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75429. __decorate([
  75430. BABYLON.serialize()
  75431. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75432. __decorate([
  75433. BABYLON.serialize()
  75434. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75435. __decorate([
  75436. BABYLON.serialize()
  75437. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75438. __decorate([
  75439. BABYLON.serializeAsTexture("lensTexture")
  75440. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75441. __decorate([
  75442. BABYLON.serialize()
  75443. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75444. __decorate([
  75445. BABYLON.serialize()
  75446. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75447. __decorate([
  75448. BABYLON.serialize()
  75449. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75450. __decorate([
  75451. BABYLON.serialize()
  75452. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75453. __decorate([
  75454. BABYLON.serialize()
  75455. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75456. __decorate([
  75457. BABYLON.serialize()
  75458. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75459. __decorate([
  75460. BABYLON.serializeAsTexture("lensColorTexture")
  75461. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75462. __decorate([
  75463. BABYLON.serialize()
  75464. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75465. __decorate([
  75466. BABYLON.serialize()
  75467. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75468. __decorate([
  75469. BABYLON.serialize()
  75470. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75471. __decorate([
  75472. BABYLON.serialize()
  75473. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75474. __decorate([
  75475. BABYLON.serializeAsTexture("lensStarTexture")
  75476. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75477. __decorate([
  75478. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75479. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75480. __decorate([
  75481. BABYLON.serialize()
  75482. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75483. __decorate([
  75484. BABYLON.serialize()
  75485. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75486. __decorate([
  75487. BABYLON.serialize()
  75488. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75489. __decorate([
  75490. BABYLON.serialize()
  75491. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75492. __decorate([
  75493. BABYLON.serialize()
  75494. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75495. __decorate([
  75496. BABYLON.serialize()
  75497. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75498. __decorate([
  75499. BABYLON.serialize()
  75500. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75501. __decorate([
  75502. BABYLON.serialize()
  75503. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75504. __decorate([
  75505. BABYLON.serialize()
  75506. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75507. __decorate([
  75508. BABYLON.serialize()
  75509. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75510. __decorate([
  75511. BABYLON.serialize()
  75512. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75513. __decorate([
  75514. BABYLON.serialize()
  75515. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75516. return StandardRenderingPipeline;
  75517. }(BABYLON.PostProcessRenderPipeline));
  75518. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75519. })(BABYLON || (BABYLON = {}));
  75520. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75521. var BABYLON;
  75522. (function (BABYLON) {
  75523. var FxaaPostProcess = /** @class */ (function (_super) {
  75524. __extends(FxaaPostProcess, _super);
  75525. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75526. if (camera === void 0) { camera = null; }
  75527. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75528. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75529. var defines = _this._getDefines();
  75530. _this.updateEffect(defines);
  75531. _this.onApplyObservable.add(function (effect) {
  75532. var texelSize = _this.texelSize;
  75533. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75534. });
  75535. return _this;
  75536. }
  75537. FxaaPostProcess.prototype._getDefines = function () {
  75538. var engine = this.getEngine();
  75539. if (!engine) {
  75540. return null;
  75541. }
  75542. var glInfo = engine.getGlInfo();
  75543. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75544. return "#define MALI 1\n";
  75545. }
  75546. return null;
  75547. };
  75548. return FxaaPostProcess;
  75549. }(BABYLON.PostProcess));
  75550. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75551. })(BABYLON || (BABYLON = {}));
  75552. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75553. var BABYLON;
  75554. (function (BABYLON) {
  75555. /**
  75556. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75557. */
  75558. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75559. __extends(ChromaticAberrationPostProcess, _super);
  75560. /**
  75561. * Creates a new instance ChromaticAberrationPostProcess
  75562. * @param name The name of the effect.
  75563. * @param screenWidth The width of the screen to apply the effect on.
  75564. * @param screenHeight The height of the screen to apply the effect on.
  75565. * @param options The required width/height ratio to downsize to before computing the render pass.
  75566. * @param camera The camera to apply the render pass to.
  75567. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75568. * @param engine The engine which the post process will be applied. (default: current engine)
  75569. * @param reusable If the post process can be reused on the same frame. (default: false)
  75570. * @param textureType Type of textures used when performing the post process. (default: 0)
  75571. * @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)
  75572. */
  75573. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75574. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75575. if (blockCompilation === void 0) { blockCompilation = false; }
  75576. 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;
  75577. /**
  75578. * The amount of seperation of rgb channels (default: 30)
  75579. */
  75580. _this.aberrationAmount = 30;
  75581. /**
  75582. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75583. */
  75584. _this.radialIntensity = 0;
  75585. /**
  75586. * 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))
  75587. */
  75588. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75589. /**
  75590. * 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))
  75591. */
  75592. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75593. _this.onApplyObservable.add(function (effect) {
  75594. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75595. effect.setFloat('screen_width', screenWidth);
  75596. effect.setFloat('screen_height', screenHeight);
  75597. effect.setFloat('radialIntensity', _this.radialIntensity);
  75598. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75599. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75600. });
  75601. return _this;
  75602. }
  75603. return ChromaticAberrationPostProcess;
  75604. }(BABYLON.PostProcess));
  75605. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75606. })(BABYLON || (BABYLON = {}));
  75607. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75608. var BABYLON;
  75609. (function (BABYLON) {
  75610. /**
  75611. * The GrainPostProcess adds noise to the image at mid luminance levels
  75612. */
  75613. var GrainPostProcess = /** @class */ (function (_super) {
  75614. __extends(GrainPostProcess, _super);
  75615. /**
  75616. * Creates a new instance of @see GrainPostProcess
  75617. * @param name The name of the effect.
  75618. * @param options The required width/height ratio to downsize to before computing the render pass.
  75619. * @param camera The camera to apply the render pass to.
  75620. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75621. * @param engine The engine which the post process will be applied. (default: current engine)
  75622. * @param reusable If the post process can be reused on the same frame. (default: false)
  75623. * @param textureType Type of textures used when performing the post process. (default: 0)
  75624. * @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)
  75625. */
  75626. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75627. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75628. if (blockCompilation === void 0) { blockCompilation = false; }
  75629. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75630. /**
  75631. * The intensity of the grain added (default: 30)
  75632. */
  75633. _this.intensity = 30;
  75634. /**
  75635. * If the grain should be randomized on every frame
  75636. */
  75637. _this.animated = false;
  75638. _this.onApplyObservable.add(function (effect) {
  75639. effect.setFloat('intensity', _this.intensity);
  75640. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75641. });
  75642. return _this;
  75643. }
  75644. return GrainPostProcess;
  75645. }(BABYLON.PostProcess));
  75646. BABYLON.GrainPostProcess = GrainPostProcess;
  75647. })(BABYLON || (BABYLON = {}));
  75648. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75649. var BABYLON;
  75650. (function (BABYLON) {
  75651. /**
  75652. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75653. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75654. */
  75655. var SharpenPostProcess = /** @class */ (function (_super) {
  75656. __extends(SharpenPostProcess, _super);
  75657. /**
  75658. * Creates a new instance ConvolutionPostProcess
  75659. * @param name The name of the effect.
  75660. * @param options The required width/height ratio to downsize to before computing the render pass.
  75661. * @param camera The camera to apply the render pass to.
  75662. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75663. * @param engine The engine which the post process will be applied. (default: current engine)
  75664. * @param reusable If the post process can be reused on the same frame. (default: false)
  75665. * @param textureType Type of textures used when performing the post process. (default: 0)
  75666. * @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)
  75667. */
  75668. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75669. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75670. if (blockCompilation === void 0) { blockCompilation = false; }
  75671. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75672. /**
  75673. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75674. */
  75675. _this.colorAmount = 1.0;
  75676. /**
  75677. * How much sharpness should be applied (default: 0.3)
  75678. */
  75679. _this.edgeAmount = 0.3;
  75680. _this.onApply = function (effect) {
  75681. effect.setFloat2("screenSize", _this.width, _this.height);
  75682. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75683. };
  75684. return _this;
  75685. }
  75686. return SharpenPostProcess;
  75687. }(BABYLON.PostProcess));
  75688. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75689. })(BABYLON || (BABYLON = {}));
  75690. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75691. var BABYLON;
  75692. (function (BABYLON) {
  75693. /**
  75694. * The Blur Post Process which blurs an image based on a kernel and direction.
  75695. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75696. */
  75697. var BlurPostProcess = /** @class */ (function (_super) {
  75698. __extends(BlurPostProcess, _super);
  75699. /**
  75700. * Creates a new instance BlurPostProcess
  75701. * @param name The name of the effect.
  75702. * @param direction The direction in which to blur the image.
  75703. * @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.
  75704. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75705. * @param camera The camera to apply the render pass to.
  75706. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75707. * @param engine The engine which the post process will be applied. (default: current engine)
  75708. * @param reusable If the post process can be reused on the same frame. (default: false)
  75709. * @param textureType Type of textures used when performing the post process. (default: 0)
  75710. * @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)
  75711. */
  75712. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75714. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75715. if (defines === void 0) { defines = ""; }
  75716. if (blockCompilation === void 0) { blockCompilation = false; }
  75717. 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;
  75718. _this.direction = direction;
  75719. _this.blockCompilation = blockCompilation;
  75720. _this._packedFloat = false;
  75721. _this._staticDefines = "";
  75722. _this._staticDefines = defines;
  75723. _this.onApplyObservable.add(function (effect) {
  75724. if (_this._outputTexture) {
  75725. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75726. }
  75727. else {
  75728. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75729. }
  75730. });
  75731. _this.kernel = kernel;
  75732. return _this;
  75733. }
  75734. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75735. /**
  75736. * Gets the length in pixels of the blur sample region
  75737. */
  75738. get: function () {
  75739. return this._idealKernel;
  75740. },
  75741. /**
  75742. * Sets the length in pixels of the blur sample region
  75743. */
  75744. set: function (v) {
  75745. if (this._idealKernel === v) {
  75746. return;
  75747. }
  75748. v = Math.max(v, 1);
  75749. this._idealKernel = v;
  75750. this._kernel = this._nearestBestKernel(v);
  75751. if (!this.blockCompilation) {
  75752. this._updateParameters();
  75753. }
  75754. },
  75755. enumerable: true,
  75756. configurable: true
  75757. });
  75758. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75759. /**
  75760. * Gets wether or not the blur is unpacking/repacking floats
  75761. */
  75762. get: function () {
  75763. return this._packedFloat;
  75764. },
  75765. /**
  75766. * Sets wether or not the blur needs to unpack/repack floats
  75767. */
  75768. set: function (v) {
  75769. if (this._packedFloat === v) {
  75770. return;
  75771. }
  75772. this._packedFloat = v;
  75773. if (!this.blockCompilation) {
  75774. this._updateParameters();
  75775. }
  75776. },
  75777. enumerable: true,
  75778. configurable: true
  75779. });
  75780. /**
  75781. * Updates the effect with the current post process compile time values and recompiles the shader.
  75782. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75783. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75784. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75785. * @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
  75786. * @param onCompiled Called when the shader has been compiled.
  75787. * @param onError Called if there is an error when compiling a shader.
  75788. */
  75789. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75790. if (defines === void 0) { defines = null; }
  75791. if (uniforms === void 0) { uniforms = null; }
  75792. if (samplers === void 0) { samplers = null; }
  75793. this._updateParameters(onCompiled, onError);
  75794. };
  75795. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75796. // Generate sampling offsets and weights
  75797. var N = this._kernel;
  75798. var centerIndex = (N - 1) / 2;
  75799. // Generate Gaussian sampling weights over kernel
  75800. var offsets = [];
  75801. var weights = [];
  75802. var totalWeight = 0;
  75803. for (var i = 0; i < N; i++) {
  75804. var u = i / (N - 1);
  75805. var w = this._gaussianWeight(u * 2.0 - 1);
  75806. offsets[i] = (i - centerIndex);
  75807. weights[i] = w;
  75808. totalWeight += w;
  75809. }
  75810. // Normalize weights
  75811. for (var i = 0; i < weights.length; i++) {
  75812. weights[i] /= totalWeight;
  75813. }
  75814. // Optimize: combine samples to take advantage of hardware linear sampling
  75815. // Walk from left to center, combining pairs (symmetrically)
  75816. var linearSamplingWeights = [];
  75817. var linearSamplingOffsets = [];
  75818. var linearSamplingMap = [];
  75819. for (var i = 0; i <= centerIndex; i += 2) {
  75820. var j = Math.min(i + 1, Math.floor(centerIndex));
  75821. var singleCenterSample = i === j;
  75822. if (singleCenterSample) {
  75823. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75824. }
  75825. else {
  75826. var sharedCell = j === centerIndex;
  75827. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75828. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75829. if (offsetLinear === 0) {
  75830. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75831. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75832. }
  75833. else {
  75834. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75835. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75836. }
  75837. }
  75838. }
  75839. for (var i = 0; i < linearSamplingMap.length; i++) {
  75840. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75841. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75842. }
  75843. // Replace with optimized
  75844. offsets = linearSamplingOffsets;
  75845. weights = linearSamplingWeights;
  75846. // Generate shaders
  75847. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75848. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75849. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75850. var defines = "";
  75851. defines += this._staticDefines;
  75852. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75853. if (this._staticDefines.indexOf("DOF") != -1) {
  75854. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75855. varyingCount--;
  75856. }
  75857. for (var i = 0; i < varyingCount; i++) {
  75858. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75859. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75860. }
  75861. var depCount = 0;
  75862. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75863. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75864. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75865. depCount++;
  75866. }
  75867. if (this.packedFloat) {
  75868. defines += "#define PACKEDFLOAT 1";
  75869. }
  75870. this.blockCompilation = false;
  75871. _super.prototype.updateEffect.call(this, defines, null, null, {
  75872. varyingCount: varyingCount,
  75873. depCount: depCount
  75874. }, onCompiled, onError);
  75875. };
  75876. /**
  75877. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75878. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75879. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75880. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75881. * The gaps between physical kernels are compensated for in the weighting of the samples
  75882. * @param idealKernel Ideal blur kernel.
  75883. * @return Nearest best kernel.
  75884. */
  75885. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75886. var v = Math.round(idealKernel);
  75887. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75888. var k = _a[_i];
  75889. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75890. return Math.max(k, 3);
  75891. }
  75892. }
  75893. return Math.max(v, 3);
  75894. };
  75895. /**
  75896. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75897. * @param x The point on the Gaussian distribution to sample.
  75898. * @return the value of the Gaussian function at x.
  75899. */
  75900. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75901. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75902. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75903. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75904. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75905. // truncated at around 1.3% of peak strength.
  75906. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75907. var sigma = (1 / 3);
  75908. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75909. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75910. var weight = (1.0 / denominator) * Math.exp(exponent);
  75911. return weight;
  75912. };
  75913. /**
  75914. * Generates a string that can be used as a floating point number in GLSL.
  75915. * @param x Value to print.
  75916. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75917. * @return GLSL float string.
  75918. */
  75919. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75920. if (decimalFigures === void 0) { decimalFigures = 8; }
  75921. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75922. };
  75923. return BlurPostProcess;
  75924. }(BABYLON.PostProcess));
  75925. BABYLON.BlurPostProcess = BlurPostProcess;
  75926. })(BABYLON || (BABYLON = {}));
  75927. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75928. var BABYLON;
  75929. (function (BABYLON) {
  75930. /**
  75931. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75932. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75933. * based on samples that have a large difference in distance than the center pixel.
  75934. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75935. */
  75936. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75937. __extends(DepthOfFieldBlurPostProcess, _super);
  75938. /**
  75939. * Creates a new instance CircleOfConfusionPostProcess
  75940. * @param name The name of the effect.
  75941. * @param scene The scene the effect belongs to.
  75942. * @param direction The direction the blur should be applied.
  75943. * @param kernel The size of the kernel used to blur.
  75944. * @param options The required width/height ratio to downsize to before computing the render pass.
  75945. * @param camera The camera to apply the render pass to.
  75946. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75947. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75948. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75949. * @param engine The engine which the post process will be applied. (default: current engine)
  75950. * @param reusable If the post process can be reused on the same frame. (default: false)
  75951. * @param textureType Type of textures used when performing the post process. (default: 0)
  75952. * @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)
  75953. */
  75954. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75955. if (imageToBlur === void 0) { imageToBlur = null; }
  75956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75957. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75958. if (blockCompilation === void 0) { blockCompilation = false; }
  75959. 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;
  75960. _this.direction = direction;
  75961. _this.onApplyObservable.add(function (effect) {
  75962. if (imageToBlur != null) {
  75963. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75964. }
  75965. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75966. if (scene.activeCamera) {
  75967. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75968. }
  75969. });
  75970. return _this;
  75971. }
  75972. return DepthOfFieldBlurPostProcess;
  75973. }(BABYLON.BlurPostProcess));
  75974. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75975. })(BABYLON || (BABYLON = {}));
  75976. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75977. var BABYLON;
  75978. (function (BABYLON) {
  75979. /**
  75980. * Options to be set when merging outputs from the default pipeline.
  75981. */
  75982. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75983. function DepthOfFieldMergePostProcessOptions() {
  75984. }
  75985. return DepthOfFieldMergePostProcessOptions;
  75986. }());
  75987. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75988. /**
  75989. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75990. */
  75991. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75992. __extends(DepthOfFieldMergePostProcess, _super);
  75993. /**
  75994. * Creates a new instance of DepthOfFieldMergePostProcess
  75995. * @param name The name of the effect.
  75996. * @param originalFromInput Post process which's input will be used for the merge.
  75997. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75998. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75999. * @param options The required width/height ratio to downsize to before computing the render pass.
  76000. * @param camera The camera to apply the render pass to.
  76001. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76002. * @param engine The engine which the post process will be applied. (default: current engine)
  76003. * @param reusable If the post process can be reused on the same frame. (default: false)
  76004. * @param textureType Type of textures used when performing the post process. (default: 0)
  76005. * @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)
  76006. */
  76007. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76008. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76009. if (blockCompilation === void 0) { blockCompilation = false; }
  76010. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76011. _this.blurSteps = blurSteps;
  76012. _this.onApplyObservable.add(function (effect) {
  76013. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76014. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  76015. blurSteps.forEach(function (step, index) {
  76016. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  76017. });
  76018. });
  76019. if (!blockCompilation) {
  76020. _this.updateEffect();
  76021. }
  76022. return _this;
  76023. }
  76024. /**
  76025. * Updates the effect with the current post process compile time values and recompiles the shader.
  76026. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76027. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76028. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76029. * @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
  76030. * @param onCompiled Called when the shader has been compiled.
  76031. * @param onError Called if there is an error when compiling a shader.
  76032. */
  76033. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76034. if (defines === void 0) { defines = null; }
  76035. if (uniforms === void 0) { uniforms = null; }
  76036. if (samplers === void 0) { samplers = null; }
  76037. if (!defines) {
  76038. defines = "";
  76039. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  76040. }
  76041. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  76042. };
  76043. return DepthOfFieldMergePostProcess;
  76044. }(BABYLON.PostProcess));
  76045. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  76046. })(BABYLON || (BABYLON = {}));
  76047. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  76048. var BABYLON;
  76049. (function (BABYLON) {
  76050. /**
  76051. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  76052. */
  76053. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  76054. __extends(CircleOfConfusionPostProcess, _super);
  76055. /**
  76056. * Creates a new instance CircleOfConfusionPostProcess
  76057. * @param name The name of the effect.
  76058. * @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.
  76059. * @param options The required width/height ratio to downsize to before computing the render pass.
  76060. * @param camera The camera to apply the render pass to.
  76061. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76062. * @param engine The engine which the post process will be applied. (default: current engine)
  76063. * @param reusable If the post process can be reused on the same frame. (default: false)
  76064. * @param textureType Type of textures used when performing the post process. (default: 0)
  76065. * @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)
  76066. */
  76067. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76068. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76069. if (blockCompilation === void 0) { blockCompilation = false; }
  76070. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76071. /**
  76072. * 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.
  76073. */
  76074. _this.lensSize = 50;
  76075. /**
  76076. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76077. */
  76078. _this.fStop = 1.4;
  76079. /**
  76080. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76081. */
  76082. _this.focusDistance = 2000;
  76083. /**
  76084. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  76085. */
  76086. _this.focalLength = 50;
  76087. _this._depthTexture = null;
  76088. _this._depthTexture = depthTexture;
  76089. _this.onApplyObservable.add(function (effect) {
  76090. if (!_this._depthTexture) {
  76091. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  76092. return;
  76093. }
  76094. effect.setTexture("depthSampler", _this._depthTexture);
  76095. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  76096. var aperture = _this.lensSize / _this.fStop;
  76097. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  76098. effect.setFloat('focusDistance', _this.focusDistance);
  76099. effect.setFloat('cocPrecalculation', cocPrecalculation);
  76100. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  76101. });
  76102. return _this;
  76103. }
  76104. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  76105. /**
  76106. * 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.
  76107. */
  76108. set: function (value) {
  76109. this._depthTexture = value;
  76110. },
  76111. enumerable: true,
  76112. configurable: true
  76113. });
  76114. return CircleOfConfusionPostProcess;
  76115. }(BABYLON.PostProcess));
  76116. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  76117. })(BABYLON || (BABYLON = {}));
  76118. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  76119. var BABYLON;
  76120. (function (BABYLON) {
  76121. /**
  76122. * Specifies the level of max blur that should be applied when using the depth of field effect
  76123. */
  76124. var DepthOfFieldEffectBlurLevel;
  76125. (function (DepthOfFieldEffectBlurLevel) {
  76126. /**
  76127. * Subtle blur
  76128. */
  76129. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  76130. /**
  76131. * Medium blur
  76132. */
  76133. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  76134. /**
  76135. * Large blur
  76136. */
  76137. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  76138. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  76139. ;
  76140. /**
  76141. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  76142. */
  76143. var DepthOfFieldEffect = /** @class */ (function (_super) {
  76144. __extends(DepthOfFieldEffect, _super);
  76145. /**
  76146. * Creates a new instance DepthOfFieldEffect
  76147. * @param scene The scene the effect belongs to.
  76148. * @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.
  76149. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76150. * @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)
  76151. */
  76152. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  76153. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  76154. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76155. if (blockCompilation === void 0) { blockCompilation = false; }
  76156. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  76157. return _this._effects;
  76158. }, true) || this;
  76159. /**
  76160. * Internal post processes in depth of field effect
  76161. */
  76162. _this._effects = [];
  76163. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  76164. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76165. // 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)
  76166. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  76167. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76168. _this._depthOfFieldBlurY = [];
  76169. _this._depthOfFieldBlurX = [];
  76170. var blurCount = 1;
  76171. var kernelSize = 15;
  76172. switch (blurLevel) {
  76173. case DepthOfFieldEffectBlurLevel.High: {
  76174. blurCount = 3;
  76175. kernelSize = 51;
  76176. break;
  76177. }
  76178. case DepthOfFieldEffectBlurLevel.Medium: {
  76179. blurCount = 2;
  76180. kernelSize = 31;
  76181. break;
  76182. }
  76183. default: {
  76184. kernelSize = 15;
  76185. blurCount = 1;
  76186. break;
  76187. }
  76188. }
  76189. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  76190. var ratio = 1.0;
  76191. for (var i = 0; i < blurCount; i++) {
  76192. 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);
  76193. blurY.autoClear = false;
  76194. ratio = 0.75 / Math.pow(2, i);
  76195. 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);
  76196. blurX.autoClear = false;
  76197. _this._depthOfFieldBlurY.push(blurY);
  76198. _this._depthOfFieldBlurX.push(blurX);
  76199. }
  76200. // Set all post processes on the effect.
  76201. _this._effects = [_this._circleOfConfusion];
  76202. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76203. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76204. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76205. }
  76206. // Merge blurred images with original image based on circleOfConfusion
  76207. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76208. _this._dofMerge.autoClear = false;
  76209. _this._effects.push(_this._dofMerge);
  76210. return _this;
  76211. }
  76212. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76213. get: function () {
  76214. return this._circleOfConfusion.focalLength;
  76215. },
  76216. /**
  76217. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76218. */
  76219. set: function (value) {
  76220. this._circleOfConfusion.focalLength = value;
  76221. },
  76222. enumerable: true,
  76223. configurable: true
  76224. });
  76225. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76226. get: function () {
  76227. return this._circleOfConfusion.fStop;
  76228. },
  76229. /**
  76230. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76231. */
  76232. set: function (value) {
  76233. this._circleOfConfusion.fStop = value;
  76234. },
  76235. enumerable: true,
  76236. configurable: true
  76237. });
  76238. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76239. get: function () {
  76240. return this._circleOfConfusion.focusDistance;
  76241. },
  76242. /**
  76243. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76244. */
  76245. set: function (value) {
  76246. this._circleOfConfusion.focusDistance = value;
  76247. },
  76248. enumerable: true,
  76249. configurable: true
  76250. });
  76251. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76252. get: function () {
  76253. return this._circleOfConfusion.lensSize;
  76254. },
  76255. /**
  76256. * 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.
  76257. */
  76258. set: function (value) {
  76259. this._circleOfConfusion.lensSize = value;
  76260. },
  76261. enumerable: true,
  76262. configurable: true
  76263. });
  76264. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76265. /**
  76266. * 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.
  76267. */
  76268. set: function (value) {
  76269. this._circleOfConfusion.depthTexture = value;
  76270. },
  76271. enumerable: true,
  76272. configurable: true
  76273. });
  76274. /**
  76275. * Disposes each of the internal effects for a given camera.
  76276. * @param camera The camera to dispose the effect on.
  76277. */
  76278. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76279. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76280. this._effects[effectIndex].dispose(camera);
  76281. }
  76282. };
  76283. /**
  76284. * Internal
  76285. */
  76286. DepthOfFieldEffect.prototype._updateEffects = function () {
  76287. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76288. this._effects[effectIndex].updateEffect();
  76289. }
  76290. };
  76291. /**
  76292. * Internal
  76293. * @returns if all the contained post processes are ready.
  76294. */
  76295. DepthOfFieldEffect.prototype._isReady = function () {
  76296. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76297. if (!this._effects[effectIndex].isReady()) {
  76298. return false;
  76299. }
  76300. }
  76301. return true;
  76302. };
  76303. return DepthOfFieldEffect;
  76304. }(BABYLON.PostProcessRenderEffect));
  76305. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76306. })(BABYLON || (BABYLON = {}));
  76307. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76308. var BABYLON;
  76309. (function (BABYLON) {
  76310. /**
  76311. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76312. */
  76313. var BloomMergePostProcess = /** @class */ (function (_super) {
  76314. __extends(BloomMergePostProcess, _super);
  76315. /**
  76316. * Creates a new instance of @see BloomMergePostProcess
  76317. * @param name The name of the effect.
  76318. * @param originalFromInput Post process which's input will be used for the merge.
  76319. * @param blurred Blurred highlights post process which's output will be used.
  76320. * @param weight Weight of the bloom to be added to the original input.
  76321. * @param options The required width/height ratio to downsize to before computing the render pass.
  76322. * @param camera The camera to apply the render pass to.
  76323. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76324. * @param engine The engine which the post process will be applied. (default: current engine)
  76325. * @param reusable If the post process can be reused on the same frame. (default: false)
  76326. * @param textureType Type of textures used when performing the post process. (default: 0)
  76327. * @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)
  76328. */
  76329. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76330. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76331. if (blockCompilation === void 0) { blockCompilation = false; }
  76332. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76333. _this.weight = weight;
  76334. _this.onApplyObservable.add(function (effect) {
  76335. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76336. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76337. effect.setFloat("bloomWeight", _this.weight);
  76338. });
  76339. if (!blockCompilation) {
  76340. _this.updateEffect();
  76341. }
  76342. return _this;
  76343. }
  76344. return BloomMergePostProcess;
  76345. }(BABYLON.PostProcess));
  76346. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76347. })(BABYLON || (BABYLON = {}));
  76348. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76349. var BABYLON;
  76350. (function (BABYLON) {
  76351. /**
  76352. * 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.
  76353. */
  76354. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76355. __extends(ExtractHighlightsPostProcess, _super);
  76356. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76357. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76358. if (blockCompilation === void 0) { blockCompilation = false; }
  76359. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76360. /**
  76361. * The luminance threshold, pixels below this value will be set to black.
  76362. */
  76363. _this.threshold = 0.9;
  76364. /**
  76365. * Internal
  76366. */
  76367. _this._exposure = 1;
  76368. /**
  76369. * Post process which has the input texture to be used when performing highlight extraction
  76370. */
  76371. _this._inputPostProcess = null;
  76372. _this.onApplyObservable.add(function (effect) {
  76373. if (_this._inputPostProcess) {
  76374. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76375. }
  76376. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76377. effect.setFloat('exposure', _this._exposure);
  76378. });
  76379. return _this;
  76380. }
  76381. return ExtractHighlightsPostProcess;
  76382. }(BABYLON.PostProcess));
  76383. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76384. })(BABYLON || (BABYLON = {}));
  76385. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76386. var BABYLON;
  76387. (function (BABYLON) {
  76388. /**
  76389. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76390. */
  76391. var BloomEffect = /** @class */ (function (_super) {
  76392. __extends(BloomEffect, _super);
  76393. /**
  76394. * Creates a new instance of @see BloomEffect
  76395. * @param scene The scene the effect belongs to.
  76396. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76397. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76398. * @param bloomWeight The the strength of bloom.
  76399. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76400. * @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)
  76401. */
  76402. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76403. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76404. if (blockCompilation === void 0) { blockCompilation = false; }
  76405. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76406. return _this._effects;
  76407. }, true) || this;
  76408. _this.bloomScale = bloomScale;
  76409. /**
  76410. * Internal
  76411. */
  76412. _this._effects = [];
  76413. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76414. _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);
  76415. _this._blurX.alwaysForcePOT = true;
  76416. _this._blurX.autoClear = false;
  76417. _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);
  76418. _this._blurY.alwaysForcePOT = true;
  76419. _this._blurY.autoClear = false;
  76420. _this.kernel = bloomKernel;
  76421. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76422. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76423. _this._merge.autoClear = false;
  76424. _this._effects.push(_this._merge);
  76425. return _this;
  76426. }
  76427. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76428. /**
  76429. * The luminance threshold to find bright areas of the image to bloom.
  76430. */
  76431. get: function () {
  76432. return this._downscale.threshold;
  76433. },
  76434. set: function (value) {
  76435. this._downscale.threshold = value;
  76436. },
  76437. enumerable: true,
  76438. configurable: true
  76439. });
  76440. Object.defineProperty(BloomEffect.prototype, "weight", {
  76441. /**
  76442. * The strength of the bloom.
  76443. */
  76444. get: function () {
  76445. return this._merge.weight;
  76446. },
  76447. set: function (value) {
  76448. this._merge.weight = value;
  76449. },
  76450. enumerable: true,
  76451. configurable: true
  76452. });
  76453. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76454. /**
  76455. * Specifies the size of the bloom blur kernel, relative to the final output size
  76456. */
  76457. get: function () {
  76458. return this._blurX.kernel / this.bloomScale;
  76459. },
  76460. set: function (value) {
  76461. this._blurX.kernel = value * this.bloomScale;
  76462. this._blurY.kernel = value * this.bloomScale;
  76463. },
  76464. enumerable: true,
  76465. configurable: true
  76466. });
  76467. /**
  76468. * Disposes each of the internal effects for a given camera.
  76469. * @param camera The camera to dispose the effect on.
  76470. */
  76471. BloomEffect.prototype.disposeEffects = function (camera) {
  76472. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76473. this._effects[effectIndex].dispose(camera);
  76474. }
  76475. };
  76476. /**
  76477. * Internal
  76478. */
  76479. BloomEffect.prototype._updateEffects = function () {
  76480. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76481. this._effects[effectIndex].updateEffect();
  76482. }
  76483. };
  76484. /**
  76485. * Internal
  76486. * @returns if all the contained post processes are ready.
  76487. */
  76488. BloomEffect.prototype._isReady = function () {
  76489. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76490. if (!this._effects[effectIndex].isReady()) {
  76491. return false;
  76492. }
  76493. }
  76494. return true;
  76495. };
  76496. return BloomEffect;
  76497. }(BABYLON.PostProcessRenderEffect));
  76498. BABYLON.BloomEffect = BloomEffect;
  76499. })(BABYLON || (BABYLON = {}));
  76500. //# sourceMappingURL=babylon.bloomEffect.js.map
  76501. var BABYLON;
  76502. (function (BABYLON) {
  76503. /**
  76504. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76505. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76506. */
  76507. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76508. __extends(DefaultRenderingPipeline, _super);
  76509. /**
  76510. * @constructor
  76511. * @param {string} name - The rendering pipeline name (default: "")
  76512. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76513. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76514. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76515. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76516. */
  76517. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76518. if (name === void 0) { name = ""; }
  76519. if (hdr === void 0) { hdr = true; }
  76520. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76521. if (automaticBuild === void 0) { automaticBuild = true; }
  76522. var _this = _super.call(this, scene.getEngine(), name) || this;
  76523. _this._camerasToBeAttached = [];
  76524. /**
  76525. * ID of the sharpen post process,
  76526. */
  76527. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76528. /**
  76529. * ID of the image processing post process;
  76530. */
  76531. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76532. /**
  76533. * ID of the Fast Approximate Anti-Aliasing post process;
  76534. */
  76535. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76536. /**
  76537. * ID of the chromatic aberration post process,
  76538. */
  76539. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76540. /**
  76541. * ID of the grain post process
  76542. */
  76543. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76544. /**
  76545. * Glow post process which adds a glow to emmisive areas of the image
  76546. */
  76547. _this._glowLayer = null;
  76548. /**
  76549. * Animations which can be used to tweak settings over a period of time
  76550. */
  76551. _this.animations = [];
  76552. _this._imageProcessingConfigurationObserver = null;
  76553. // Values
  76554. _this._sharpenEnabled = false;
  76555. _this._bloomEnabled = false;
  76556. _this._depthOfFieldEnabled = false;
  76557. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76558. _this._fxaaEnabled = false;
  76559. _this._imageProcessingEnabled = true;
  76560. _this._bloomScale = 0.5;
  76561. _this._chromaticAberrationEnabled = false;
  76562. _this._grainEnabled = false;
  76563. _this._buildAllowed = true;
  76564. _this._resizeObserver = null;
  76565. _this._hardwareScaleLevel = 1.0;
  76566. _this._bloomKernel = 64;
  76567. /**
  76568. * Specifies the weight of the bloom in the final rendering
  76569. */
  76570. _this._bloomWeight = 0.15;
  76571. /**
  76572. * Specifies the luma threshold for the area that will be blurred by the bloom
  76573. */
  76574. _this._bloomThreshold = 0.9;
  76575. _this._samples = 1;
  76576. _this._hasCleared = false;
  76577. _this._prevPostProcess = null;
  76578. _this._prevPrevPostProcess = null;
  76579. _this._cameras = cameras || scene.cameras;
  76580. _this._camerasToBeAttached = _this._cameras.slice();
  76581. _this._buildAllowed = automaticBuild;
  76582. // Initialize
  76583. _this._scene = scene;
  76584. var caps = _this._scene.getEngine().getCaps();
  76585. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76586. // Misc
  76587. if (_this._hdr) {
  76588. if (caps.textureHalfFloatRender) {
  76589. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76590. }
  76591. else if (caps.textureFloatRender) {
  76592. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76593. }
  76594. }
  76595. else {
  76596. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76597. }
  76598. // Attach
  76599. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76600. var engine = _this._scene.getEngine();
  76601. // Create post processes before hand so they can be modified before enabled.
  76602. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76603. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76604. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76605. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76606. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76607. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76608. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76609. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76610. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76611. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76612. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76613. _this.bloomKernel = _this.bloomKernel;
  76614. });
  76615. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76616. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76617. });
  76618. _this._buildPipeline();
  76619. return _this;
  76620. }
  76621. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76622. get: function () {
  76623. return this._sharpenEnabled;
  76624. },
  76625. /**
  76626. * Enable or disable the sharpen process from the pipeline
  76627. */
  76628. set: function (enabled) {
  76629. if (this._sharpenEnabled === enabled) {
  76630. return;
  76631. }
  76632. this._sharpenEnabled = enabled;
  76633. this._buildPipeline();
  76634. },
  76635. enumerable: true,
  76636. configurable: true
  76637. });
  76638. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76639. /**
  76640. * Specifies the size of the bloom blur kernel, relative to the final output size
  76641. */
  76642. get: function () {
  76643. return this._bloomKernel;
  76644. },
  76645. set: function (value) {
  76646. this._bloomKernel = value;
  76647. this.bloom.kernel = value / this._hardwareScaleLevel;
  76648. },
  76649. enumerable: true,
  76650. configurable: true
  76651. });
  76652. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76653. get: function () {
  76654. return this._bloomWeight;
  76655. },
  76656. /**
  76657. * The strength of the bloom.
  76658. */
  76659. set: function (value) {
  76660. if (this._bloomWeight === value) {
  76661. return;
  76662. }
  76663. this.bloom.weight = value;
  76664. this._bloomWeight = value;
  76665. },
  76666. enumerable: true,
  76667. configurable: true
  76668. });
  76669. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76670. get: function () {
  76671. return this._bloomThreshold;
  76672. },
  76673. /**
  76674. * The strength of the bloom.
  76675. */
  76676. set: function (value) {
  76677. if (this._bloomThreshold === value) {
  76678. return;
  76679. }
  76680. this.bloom.threshold = value;
  76681. this._bloomThreshold = value;
  76682. },
  76683. enumerable: true,
  76684. configurable: true
  76685. });
  76686. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76687. get: function () {
  76688. return this._bloomScale;
  76689. },
  76690. /**
  76691. * The scale of the bloom, lower value will provide better performance.
  76692. */
  76693. set: function (value) {
  76694. if (this._bloomScale === value) {
  76695. return;
  76696. }
  76697. this._bloomScale = value;
  76698. // recreate bloom and dispose old as this setting is not dynamic
  76699. this._rebuildBloom();
  76700. this._buildPipeline();
  76701. },
  76702. enumerable: true,
  76703. configurable: true
  76704. });
  76705. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76706. get: function () {
  76707. return this._bloomEnabled;
  76708. },
  76709. /**
  76710. * Enable or disable the bloom from the pipeline
  76711. */
  76712. set: function (enabled) {
  76713. if (this._bloomEnabled === enabled) {
  76714. return;
  76715. }
  76716. this._bloomEnabled = enabled;
  76717. this._buildPipeline();
  76718. },
  76719. enumerable: true,
  76720. configurable: true
  76721. });
  76722. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76723. // recreate bloom and dispose old as this setting is not dynamic
  76724. var oldBloom = this.bloom;
  76725. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76726. this.bloom.threshold = oldBloom.threshold;
  76727. for (var i = 0; i < this._cameras.length; i++) {
  76728. oldBloom.disposeEffects(this._cameras[i]);
  76729. }
  76730. };
  76731. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76732. /**
  76733. * If the depth of field is enabled.
  76734. */
  76735. get: function () {
  76736. return this._depthOfFieldEnabled;
  76737. },
  76738. set: function (enabled) {
  76739. if (this._depthOfFieldEnabled === enabled) {
  76740. return;
  76741. }
  76742. this._depthOfFieldEnabled = enabled;
  76743. this._buildPipeline();
  76744. },
  76745. enumerable: true,
  76746. configurable: true
  76747. });
  76748. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76749. /**
  76750. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76751. */
  76752. get: function () {
  76753. return this._depthOfFieldBlurLevel;
  76754. },
  76755. set: function (value) {
  76756. if (this._depthOfFieldBlurLevel === value) {
  76757. return;
  76758. }
  76759. this._depthOfFieldBlurLevel = value;
  76760. // recreate dof and dispose old as this setting is not dynamic
  76761. var oldDof = this.depthOfField;
  76762. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76763. this.depthOfField.focalLength = oldDof.focalLength;
  76764. this.depthOfField.focusDistance = oldDof.focusDistance;
  76765. this.depthOfField.fStop = oldDof.fStop;
  76766. this.depthOfField.lensSize = oldDof.lensSize;
  76767. for (var i = 0; i < this._cameras.length; i++) {
  76768. oldDof.disposeEffects(this._cameras[i]);
  76769. }
  76770. this._buildPipeline();
  76771. },
  76772. enumerable: true,
  76773. configurable: true
  76774. });
  76775. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76776. get: function () {
  76777. return this._fxaaEnabled;
  76778. },
  76779. /**
  76780. * If the anti aliasing is enabled.
  76781. */
  76782. set: function (enabled) {
  76783. if (this._fxaaEnabled === enabled) {
  76784. return;
  76785. }
  76786. this._fxaaEnabled = enabled;
  76787. this._buildPipeline();
  76788. },
  76789. enumerable: true,
  76790. configurable: true
  76791. });
  76792. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76793. get: function () {
  76794. return this._samples;
  76795. },
  76796. /**
  76797. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76798. */
  76799. set: function (sampleCount) {
  76800. if (this._samples === sampleCount) {
  76801. return;
  76802. }
  76803. this._samples = sampleCount;
  76804. this._buildPipeline();
  76805. },
  76806. enumerable: true,
  76807. configurable: true
  76808. });
  76809. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76810. get: function () {
  76811. return this._imageProcessingEnabled;
  76812. },
  76813. /**
  76814. * If image processing is enabled.
  76815. */
  76816. set: function (enabled) {
  76817. if (this._imageProcessingEnabled === enabled) {
  76818. return;
  76819. }
  76820. this._imageProcessingEnabled = enabled;
  76821. this._buildPipeline();
  76822. },
  76823. enumerable: true,
  76824. configurable: true
  76825. });
  76826. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76827. get: function () {
  76828. return this._glowLayer == null;
  76829. },
  76830. /**
  76831. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76832. */
  76833. set: function (enabled) {
  76834. if (enabled && !this._glowLayer) {
  76835. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76836. }
  76837. else if (!enabled && this._glowLayer) {
  76838. this._glowLayer.dispose();
  76839. this._glowLayer = null;
  76840. }
  76841. },
  76842. enumerable: true,
  76843. configurable: true
  76844. });
  76845. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76846. get: function () {
  76847. return this._chromaticAberrationEnabled;
  76848. },
  76849. /**
  76850. * Enable or disable the chromaticAberration process from the pipeline
  76851. */
  76852. set: function (enabled) {
  76853. if (this._chromaticAberrationEnabled === enabled) {
  76854. return;
  76855. }
  76856. this._chromaticAberrationEnabled = enabled;
  76857. this._buildPipeline();
  76858. },
  76859. enumerable: true,
  76860. configurable: true
  76861. });
  76862. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76863. get: function () {
  76864. return this._grainEnabled;
  76865. },
  76866. /**
  76867. * Enable or disable the grain process from the pipeline
  76868. */
  76869. set: function (enabled) {
  76870. if (this._grainEnabled === enabled) {
  76871. return;
  76872. }
  76873. this._grainEnabled = enabled;
  76874. this._buildPipeline();
  76875. },
  76876. enumerable: true,
  76877. configurable: true
  76878. });
  76879. /**
  76880. * Force the compilation of the entire pipeline.
  76881. */
  76882. DefaultRenderingPipeline.prototype.prepare = function () {
  76883. var previousState = this._buildAllowed;
  76884. this._buildAllowed = true;
  76885. this._buildPipeline();
  76886. this._buildAllowed = previousState;
  76887. };
  76888. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76889. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76890. if (this._hasCleared) {
  76891. postProcess.autoClear = false;
  76892. }
  76893. else {
  76894. postProcess.autoClear = true;
  76895. this._scene.autoClear = false;
  76896. this._hasCleared = true;
  76897. }
  76898. if (!skipTextureSharing) {
  76899. if (this._prevPrevPostProcess) {
  76900. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76901. }
  76902. else {
  76903. postProcess.useOwnOutput();
  76904. }
  76905. if (this._prevPostProcess) {
  76906. this._prevPrevPostProcess = this._prevPostProcess;
  76907. }
  76908. this._prevPostProcess = postProcess;
  76909. }
  76910. };
  76911. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76912. var _this = this;
  76913. if (!this._buildAllowed) {
  76914. return;
  76915. }
  76916. this._scene.autoClear = true;
  76917. var engine = this._scene.getEngine();
  76918. this._disposePostProcesses();
  76919. if (this._cameras !== null) {
  76920. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76921. // get back cameras to be used to reattach pipeline
  76922. this._cameras = this._camerasToBeAttached.slice();
  76923. }
  76924. this._reset();
  76925. this._prevPostProcess = null;
  76926. this._prevPrevPostProcess = null;
  76927. this._hasCleared = false;
  76928. if (this.depthOfFieldEnabled) {
  76929. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76930. this.depthOfField.depthTexture = depthTexture;
  76931. if (!this.depthOfField._isReady()) {
  76932. this.depthOfField._updateEffects();
  76933. }
  76934. this.addEffect(this.depthOfField);
  76935. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76936. }
  76937. if (this.bloomEnabled) {
  76938. if (!this.bloom._isReady()) {
  76939. this.bloom._updateEffects();
  76940. }
  76941. this.addEffect(this.bloom);
  76942. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76943. }
  76944. if (this._imageProcessingEnabled) {
  76945. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76946. if (this._hdr) {
  76947. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76948. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76949. }
  76950. else {
  76951. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76952. }
  76953. }
  76954. if (this.sharpenEnabled) {
  76955. if (!this.sharpen.isReady()) {
  76956. this.sharpen.updateEffect();
  76957. }
  76958. this.addEffect(this._sharpenEffect);
  76959. this._setAutoClearAndTextureSharing(this.sharpen);
  76960. }
  76961. if (this.grainEnabled) {
  76962. if (!this.grain.isReady()) {
  76963. this.grain.updateEffect();
  76964. }
  76965. this.addEffect(this._grainEffect);
  76966. this._setAutoClearAndTextureSharing(this.grain);
  76967. }
  76968. if (this.chromaticAberrationEnabled) {
  76969. if (!this.chromaticAberration.isReady()) {
  76970. this.chromaticAberration.updateEffect();
  76971. }
  76972. this.addEffect(this._chromaticAberrationEffect);
  76973. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76974. }
  76975. if (this.fxaaEnabled) {
  76976. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76977. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76978. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76979. }
  76980. if (this._cameras !== null) {
  76981. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76982. }
  76983. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76984. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76985. }
  76986. };
  76987. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76988. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76989. for (var i = 0; i < this._cameras.length; i++) {
  76990. var camera = this._cameras[i];
  76991. if (this.imageProcessing) {
  76992. this.imageProcessing.dispose(camera);
  76993. }
  76994. if (this.fxaa) {
  76995. this.fxaa.dispose(camera);
  76996. }
  76997. // These are created in the constructor and should not be disposed on every pipeline change
  76998. if (disposeNonRecreated) {
  76999. if (this.sharpen) {
  77000. this.sharpen.dispose(camera);
  77001. }
  77002. if (this.depthOfField) {
  77003. this.depthOfField.disposeEffects(camera);
  77004. }
  77005. if (this.bloom) {
  77006. this.bloom.disposeEffects(camera);
  77007. }
  77008. if (this.chromaticAberration) {
  77009. this.chromaticAberration.dispose(camera);
  77010. }
  77011. if (this.grain) {
  77012. this.grain.dispose(camera);
  77013. }
  77014. if (this._glowLayer) {
  77015. this._glowLayer.dispose();
  77016. }
  77017. }
  77018. }
  77019. this.imageProcessing = null;
  77020. this.fxaa = null;
  77021. if (disposeNonRecreated) {
  77022. this.sharpen = null;
  77023. this._sharpenEffect = null;
  77024. this.depthOfField = null;
  77025. this.bloom = null;
  77026. this.chromaticAberration = null;
  77027. this._chromaticAberrationEffect = null;
  77028. this.grain = null;
  77029. this._grainEffect = null;
  77030. this._glowLayer = null;
  77031. }
  77032. };
  77033. /**
  77034. * Adds a camera to the pipeline
  77035. * @param camera the camera to be added
  77036. */
  77037. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  77038. this._camerasToBeAttached.push(camera);
  77039. this._buildPipeline();
  77040. };
  77041. /**
  77042. * Removes a camera from the pipeline
  77043. * @param camera the camera to remove
  77044. */
  77045. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  77046. var index = this._camerasToBeAttached.indexOf(camera);
  77047. this._camerasToBeAttached.splice(index, 1);
  77048. this._buildPipeline();
  77049. };
  77050. /**
  77051. * Dispose of the pipeline and stop all post processes
  77052. */
  77053. DefaultRenderingPipeline.prototype.dispose = function () {
  77054. this._disposePostProcesses(true);
  77055. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77056. this._scene.autoClear = true;
  77057. if (this._resizeObserver) {
  77058. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  77059. this._resizeObserver = null;
  77060. }
  77061. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  77062. _super.prototype.dispose.call(this);
  77063. };
  77064. /**
  77065. * Serialize the rendering pipeline (Used when exporting)
  77066. * @returns the serialized object
  77067. */
  77068. DefaultRenderingPipeline.prototype.serialize = function () {
  77069. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77070. serializationObject.customType = "DefaultRenderingPipeline";
  77071. return serializationObject;
  77072. };
  77073. /**
  77074. * Parse the serialized pipeline
  77075. * @param source Source pipeline.
  77076. * @param scene The scene to load the pipeline to.
  77077. * @param rootUrl The URL of the serialized pipeline.
  77078. * @returns An instantiated pipeline from the serialized object.
  77079. */
  77080. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77081. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  77082. };
  77083. __decorate([
  77084. BABYLON.serialize()
  77085. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  77086. __decorate([
  77087. BABYLON.serialize()
  77088. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  77089. __decorate([
  77090. BABYLON.serialize()
  77091. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  77092. __decorate([
  77093. BABYLON.serialize()
  77094. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  77095. __decorate([
  77096. BABYLON.serialize()
  77097. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  77098. __decorate([
  77099. BABYLON.serialize()
  77100. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  77101. __decorate([
  77102. BABYLON.serialize()
  77103. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  77104. __decorate([
  77105. BABYLON.serialize()
  77106. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  77107. __decorate([
  77108. BABYLON.serialize()
  77109. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  77110. __decorate([
  77111. BABYLON.serialize()
  77112. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  77113. __decorate([
  77114. BABYLON.serialize()
  77115. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  77116. __decorate([
  77117. BABYLON.serialize()
  77118. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  77119. __decorate([
  77120. BABYLON.serialize()
  77121. ], DefaultRenderingPipeline.prototype, "samples", null);
  77122. __decorate([
  77123. BABYLON.serialize()
  77124. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  77125. __decorate([
  77126. BABYLON.serialize()
  77127. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  77128. __decorate([
  77129. BABYLON.serialize()
  77130. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  77131. __decorate([
  77132. BABYLON.serialize()
  77133. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  77134. return DefaultRenderingPipeline;
  77135. }(BABYLON.PostProcessRenderPipeline));
  77136. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  77137. })(BABYLON || (BABYLON = {}));
  77138. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  77139. var BABYLON;
  77140. (function (BABYLON) {
  77141. /**
  77142. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77143. */
  77144. var GeometryBufferRenderer = /** @class */ (function () {
  77145. /**
  77146. * Creates a new G Buffer for the scene
  77147. * @param scene The scene the buffer belongs to
  77148. * @param ratio How big is the buffer related to the main canvas.
  77149. */
  77150. function GeometryBufferRenderer(scene, ratio) {
  77151. if (ratio === void 0) { ratio = 1; }
  77152. this._enablePosition = false;
  77153. this._scene = scene;
  77154. this._ratio = ratio;
  77155. // Render target
  77156. this._createRenderTargets();
  77157. }
  77158. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77159. /**
  77160. * Set the render list (meshes to be rendered) used in the G buffer.
  77161. */
  77162. set: function (meshes) {
  77163. this._multiRenderTarget.renderList = meshes;
  77164. },
  77165. enumerable: true,
  77166. configurable: true
  77167. });
  77168. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77169. /**
  77170. * Gets wether or not G buffer are supported by the running hardware.
  77171. * This requires draw buffer supports
  77172. */
  77173. get: function () {
  77174. return this._multiRenderTarget.isSupported;
  77175. },
  77176. enumerable: true,
  77177. configurable: true
  77178. });
  77179. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77180. /**
  77181. * Gets wether or not position are enabled for the G buffer.
  77182. */
  77183. get: function () {
  77184. return this._enablePosition;
  77185. },
  77186. /**
  77187. * Sets wether or not position are enabled for the G buffer.
  77188. */
  77189. set: function (enable) {
  77190. this._enablePosition = enable;
  77191. this.dispose();
  77192. this._createRenderTargets();
  77193. },
  77194. enumerable: true,
  77195. configurable: true
  77196. });
  77197. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77198. /**
  77199. * Gets the scene associated with the buffer.
  77200. */
  77201. get: function () {
  77202. return this._scene;
  77203. },
  77204. enumerable: true,
  77205. configurable: true
  77206. });
  77207. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77208. /**
  77209. * Gets the ratio used by the buffer during its creation.
  77210. * How big is the buffer related to the main canvas.
  77211. */
  77212. get: function () {
  77213. return this._ratio;
  77214. },
  77215. enumerable: true,
  77216. configurable: true
  77217. });
  77218. /**
  77219. * Checks wether everything is ready to render a submesh to the G buffer.
  77220. * @param subMesh the submesh to check readiness for
  77221. * @param useInstances is the mesh drawn using instance or not
  77222. * @returns true if ready otherwise false
  77223. */
  77224. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77225. var material = subMesh.getMaterial();
  77226. if (material && material.disableDepthWrite) {
  77227. return false;
  77228. }
  77229. var defines = [];
  77230. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77231. var mesh = subMesh.getMesh();
  77232. // Alpha test
  77233. if (material && material.needAlphaTesting()) {
  77234. defines.push("#define ALPHATEST");
  77235. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77236. attribs.push(BABYLON.VertexBuffer.UVKind);
  77237. defines.push("#define UV1");
  77238. }
  77239. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77240. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77241. defines.push("#define UV2");
  77242. }
  77243. }
  77244. // Buffers
  77245. if (this._enablePosition) {
  77246. defines.push("#define POSITION");
  77247. }
  77248. // Bones
  77249. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77250. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77251. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77252. if (mesh.numBoneInfluencers > 4) {
  77253. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77254. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77255. }
  77256. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77257. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77258. }
  77259. else {
  77260. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77261. }
  77262. // Instances
  77263. if (useInstances) {
  77264. defines.push("#define INSTANCES");
  77265. attribs.push("world0");
  77266. attribs.push("world1");
  77267. attribs.push("world2");
  77268. attribs.push("world3");
  77269. }
  77270. // Get correct effect
  77271. var join = defines.join("\n");
  77272. if (this._cachedDefines !== join) {
  77273. this._cachedDefines = join;
  77274. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77275. }
  77276. return this._effect.isReady();
  77277. };
  77278. /**
  77279. * Gets the current underlying G Buffer.
  77280. * @returns the buffer
  77281. */
  77282. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77283. return this._multiRenderTarget;
  77284. };
  77285. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77286. /**
  77287. * Gets the number of samples used to render the buffer (anti aliasing).
  77288. */
  77289. get: function () {
  77290. return this._multiRenderTarget.samples;
  77291. },
  77292. /**
  77293. * Sets the number of samples used to render the buffer (anti aliasing).
  77294. */
  77295. set: function (value) {
  77296. this._multiRenderTarget.samples = value;
  77297. },
  77298. enumerable: true,
  77299. configurable: true
  77300. });
  77301. /**
  77302. * Disposes the renderer and frees up associated resources.
  77303. */
  77304. GeometryBufferRenderer.prototype.dispose = function () {
  77305. this.getGBuffer().dispose();
  77306. };
  77307. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77308. var _this = this;
  77309. var engine = this._scene.getEngine();
  77310. var count = this._enablePosition ? 3 : 2;
  77311. 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 });
  77312. if (!this.isSupported) {
  77313. return;
  77314. }
  77315. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77316. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77317. this._multiRenderTarget.refreshRate = 1;
  77318. this._multiRenderTarget.renderParticles = false;
  77319. this._multiRenderTarget.renderList = null;
  77320. // set default depth value to 1.0 (far away)
  77321. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77322. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77323. });
  77324. // Custom render function
  77325. var renderSubMesh = function (subMesh) {
  77326. var mesh = subMesh.getRenderingMesh();
  77327. var scene = _this._scene;
  77328. var engine = scene.getEngine();
  77329. var material = subMesh.getMaterial();
  77330. if (!material) {
  77331. return;
  77332. }
  77333. // Culling
  77334. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77335. // Managing instances
  77336. var batch = mesh._getInstancesRenderList(subMesh._id);
  77337. if (batch.mustReturn) {
  77338. return;
  77339. }
  77340. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77341. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77342. engine.enableEffect(_this._effect);
  77343. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77344. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77345. _this._effect.setMatrix("view", scene.getViewMatrix());
  77346. // Alpha test
  77347. if (material && material.needAlphaTesting()) {
  77348. var alphaTexture = material.getAlphaTestTexture();
  77349. if (alphaTexture) {
  77350. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77351. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77352. }
  77353. }
  77354. // Bones
  77355. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77356. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77357. }
  77358. // Draw
  77359. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77360. }
  77361. };
  77362. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77363. var index;
  77364. if (depthOnlySubMeshes.length) {
  77365. engine.setColorWrite(false);
  77366. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77367. renderSubMesh(depthOnlySubMeshes.data[index]);
  77368. }
  77369. engine.setColorWrite(true);
  77370. }
  77371. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77372. renderSubMesh(opaqueSubMeshes.data[index]);
  77373. }
  77374. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77375. renderSubMesh(alphaTestSubMeshes.data[index]);
  77376. }
  77377. };
  77378. };
  77379. return GeometryBufferRenderer;
  77380. }());
  77381. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77382. })(BABYLON || (BABYLON = {}));
  77383. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77384. var BABYLON;
  77385. (function (BABYLON) {
  77386. /**
  77387. * This groups together the common properties used for image processing either in direct forward pass
  77388. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77389. * or not.
  77390. */
  77391. var ImageProcessingConfiguration = /** @class */ (function () {
  77392. function ImageProcessingConfiguration() {
  77393. /**
  77394. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77395. */
  77396. this.colorCurves = new BABYLON.ColorCurves();
  77397. this._colorCurvesEnabled = false;
  77398. this._colorGradingEnabled = false;
  77399. this._colorGradingWithGreenDepth = true;
  77400. this._colorGradingBGR = true;
  77401. this._exposure = 1.0;
  77402. this._toneMappingEnabled = false;
  77403. this._contrast = 1.0;
  77404. /**
  77405. * Vignette stretch size.
  77406. */
  77407. this.vignetteStretch = 0;
  77408. /**
  77409. * Vignette centre X Offset.
  77410. */
  77411. this.vignetteCentreX = 0;
  77412. /**
  77413. * Vignette centre Y Offset.
  77414. */
  77415. this.vignetteCentreY = 0;
  77416. /**
  77417. * Vignette weight or intensity of the vignette effect.
  77418. */
  77419. this.vignetteWeight = 1.5;
  77420. /**
  77421. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77422. * if vignetteEnabled is set to true.
  77423. */
  77424. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77425. /**
  77426. * Camera field of view used by the Vignette effect.
  77427. */
  77428. this.vignetteCameraFov = 0.5;
  77429. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77430. this._vignetteEnabled = false;
  77431. this._applyByPostProcess = false;
  77432. this._isEnabled = true;
  77433. /**
  77434. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77435. */
  77436. this.onUpdateParameters = new BABYLON.Observable();
  77437. }
  77438. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77439. /**
  77440. * Gets wether the color curves effect is enabled.
  77441. */
  77442. get: function () {
  77443. return this._colorCurvesEnabled;
  77444. },
  77445. /**
  77446. * Sets wether the color curves effect is enabled.
  77447. */
  77448. set: function (value) {
  77449. if (this._colorCurvesEnabled === value) {
  77450. return;
  77451. }
  77452. this._colorCurvesEnabled = value;
  77453. this._updateParameters();
  77454. },
  77455. enumerable: true,
  77456. configurable: true
  77457. });
  77458. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77459. /**
  77460. * Gets wether the color grading effect is enabled.
  77461. */
  77462. get: function () {
  77463. return this._colorGradingEnabled;
  77464. },
  77465. /**
  77466. * Sets wether the color grading effect is enabled.
  77467. */
  77468. set: function (value) {
  77469. if (this._colorGradingEnabled === value) {
  77470. return;
  77471. }
  77472. this._colorGradingEnabled = value;
  77473. this._updateParameters();
  77474. },
  77475. enumerable: true,
  77476. configurable: true
  77477. });
  77478. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77479. /**
  77480. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77481. */
  77482. get: function () {
  77483. return this._colorGradingWithGreenDepth;
  77484. },
  77485. /**
  77486. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77487. */
  77488. set: function (value) {
  77489. if (this._colorGradingWithGreenDepth === value) {
  77490. return;
  77491. }
  77492. this._colorGradingWithGreenDepth = value;
  77493. this._updateParameters();
  77494. },
  77495. enumerable: true,
  77496. configurable: true
  77497. });
  77498. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77499. /**
  77500. * Gets wether the color grading texture contains BGR values.
  77501. */
  77502. get: function () {
  77503. return this._colorGradingBGR;
  77504. },
  77505. /**
  77506. * Sets wether the color grading texture contains BGR values.
  77507. */
  77508. set: function (value) {
  77509. if (this._colorGradingBGR === value) {
  77510. return;
  77511. }
  77512. this._colorGradingBGR = value;
  77513. this._updateParameters();
  77514. },
  77515. enumerable: true,
  77516. configurable: true
  77517. });
  77518. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77519. /**
  77520. * Gets the Exposure used in the effect.
  77521. */
  77522. get: function () {
  77523. return this._exposure;
  77524. },
  77525. /**
  77526. * Sets the Exposure used in the effect.
  77527. */
  77528. set: function (value) {
  77529. if (this._exposure === value) {
  77530. return;
  77531. }
  77532. this._exposure = value;
  77533. this._updateParameters();
  77534. },
  77535. enumerable: true,
  77536. configurable: true
  77537. });
  77538. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77539. /**
  77540. * Gets wether the tone mapping effect is enabled.
  77541. */
  77542. get: function () {
  77543. return this._toneMappingEnabled;
  77544. },
  77545. /**
  77546. * Sets wether the tone mapping effect is enabled.
  77547. */
  77548. set: function (value) {
  77549. if (this._toneMappingEnabled === value) {
  77550. return;
  77551. }
  77552. this._toneMappingEnabled = value;
  77553. this._updateParameters();
  77554. },
  77555. enumerable: true,
  77556. configurable: true
  77557. });
  77558. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77559. /**
  77560. * Gets the contrast used in the effect.
  77561. */
  77562. get: function () {
  77563. return this._contrast;
  77564. },
  77565. /**
  77566. * Sets the contrast used in the effect.
  77567. */
  77568. set: function (value) {
  77569. if (this._contrast === value) {
  77570. return;
  77571. }
  77572. this._contrast = value;
  77573. this._updateParameters();
  77574. },
  77575. enumerable: true,
  77576. configurable: true
  77577. });
  77578. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77579. /**
  77580. * Gets the vignette blend mode allowing different kind of effect.
  77581. */
  77582. get: function () {
  77583. return this._vignetteBlendMode;
  77584. },
  77585. /**
  77586. * Sets the vignette blend mode allowing different kind of effect.
  77587. */
  77588. set: function (value) {
  77589. if (this._vignetteBlendMode === value) {
  77590. return;
  77591. }
  77592. this._vignetteBlendMode = value;
  77593. this._updateParameters();
  77594. },
  77595. enumerable: true,
  77596. configurable: true
  77597. });
  77598. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77599. /**
  77600. * Gets wether the vignette effect is enabled.
  77601. */
  77602. get: function () {
  77603. return this._vignetteEnabled;
  77604. },
  77605. /**
  77606. * Sets wether the vignette effect is enabled.
  77607. */
  77608. set: function (value) {
  77609. if (this._vignetteEnabled === value) {
  77610. return;
  77611. }
  77612. this._vignetteEnabled = value;
  77613. this._updateParameters();
  77614. },
  77615. enumerable: true,
  77616. configurable: true
  77617. });
  77618. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77619. /**
  77620. * Gets wether the image processing is applied through a post process or not.
  77621. */
  77622. get: function () {
  77623. return this._applyByPostProcess;
  77624. },
  77625. /**
  77626. * Sets wether the image processing is applied through a post process or not.
  77627. */
  77628. set: function (value) {
  77629. if (this._applyByPostProcess === value) {
  77630. return;
  77631. }
  77632. this._applyByPostProcess = value;
  77633. this._updateParameters();
  77634. },
  77635. enumerable: true,
  77636. configurable: true
  77637. });
  77638. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77639. /**
  77640. * Gets wether the image processing is enabled or not.
  77641. */
  77642. get: function () {
  77643. return this._isEnabled;
  77644. },
  77645. /**
  77646. * Sets wether the image processing is enabled or not.
  77647. */
  77648. set: function (value) {
  77649. if (this._isEnabled === value) {
  77650. return;
  77651. }
  77652. this._isEnabled = value;
  77653. this._updateParameters();
  77654. },
  77655. enumerable: true,
  77656. configurable: true
  77657. });
  77658. /**
  77659. * Method called each time the image processing information changes requires to recompile the effect.
  77660. */
  77661. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77662. this.onUpdateParameters.notifyObservers(this);
  77663. };
  77664. ImageProcessingConfiguration.prototype.getClassName = function () {
  77665. return "ImageProcessingConfiguration";
  77666. };
  77667. /**
  77668. * Prepare the list of uniforms associated with the Image Processing effects.
  77669. * @param uniformsList The list of uniforms used in the effect
  77670. * @param defines the list of defines currently in use
  77671. */
  77672. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77673. if (defines.EXPOSURE) {
  77674. uniforms.push("exposureLinear");
  77675. }
  77676. if (defines.CONTRAST) {
  77677. uniforms.push("contrast");
  77678. }
  77679. if (defines.COLORGRADING) {
  77680. uniforms.push("colorTransformSettings");
  77681. }
  77682. if (defines.VIGNETTE) {
  77683. uniforms.push("vInverseScreenSize");
  77684. uniforms.push("vignetteSettings1");
  77685. uniforms.push("vignetteSettings2");
  77686. }
  77687. if (defines.COLORCURVES) {
  77688. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77689. }
  77690. };
  77691. /**
  77692. * Prepare the list of samplers associated with the Image Processing effects.
  77693. * @param uniformsList The list of uniforms used in the effect
  77694. * @param defines the list of defines currently in use
  77695. */
  77696. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77697. if (defines.COLORGRADING) {
  77698. samplersList.push("txColorTransform");
  77699. }
  77700. };
  77701. /**
  77702. * Prepare the list of defines associated to the shader.
  77703. * @param defines the list of defines to complete
  77704. */
  77705. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77706. if (forPostProcess === void 0) { forPostProcess = false; }
  77707. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77708. defines.VIGNETTE = false;
  77709. defines.TONEMAPPING = false;
  77710. defines.CONTRAST = false;
  77711. defines.EXPOSURE = false;
  77712. defines.COLORCURVES = false;
  77713. defines.COLORGRADING = false;
  77714. defines.COLORGRADING3D = false;
  77715. defines.IMAGEPROCESSING = false;
  77716. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77717. return;
  77718. }
  77719. defines.VIGNETTE = this.vignetteEnabled;
  77720. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77721. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77722. defines.TONEMAPPING = this.toneMappingEnabled;
  77723. defines.CONTRAST = (this.contrast !== 1.0);
  77724. defines.EXPOSURE = (this.exposure !== 1.0);
  77725. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77726. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77727. if (defines.COLORGRADING) {
  77728. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77729. }
  77730. else {
  77731. defines.COLORGRADING3D = false;
  77732. }
  77733. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77734. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77735. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77736. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77737. };
  77738. /**
  77739. * Returns true if all the image processing information are ready.
  77740. */
  77741. ImageProcessingConfiguration.prototype.isReady = function () {
  77742. // Color Grading texure can not be none blocking.
  77743. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77744. };
  77745. /**
  77746. * Binds the image processing to the shader.
  77747. * @param effect The effect to bind to
  77748. */
  77749. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77750. if (aspectRatio === void 0) { aspectRatio = 1; }
  77751. // Color Curves
  77752. if (this._colorCurvesEnabled && this.colorCurves) {
  77753. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77754. }
  77755. // Vignette
  77756. if (this._vignetteEnabled) {
  77757. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77758. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77759. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77760. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77761. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77762. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77763. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77764. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77765. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77766. var vignettePower = -2.0 * this.vignetteWeight;
  77767. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77768. }
  77769. // Exposure
  77770. effect.setFloat("exposureLinear", this.exposure);
  77771. // Contrast
  77772. effect.setFloat("contrast", this.contrast);
  77773. // Color transform settings
  77774. if (this.colorGradingTexture) {
  77775. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77776. var textureSize = this.colorGradingTexture.getSize().height;
  77777. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77778. 0.5 / textureSize, // textureOffset
  77779. textureSize, // textureSize
  77780. this.colorGradingTexture.level // weight
  77781. );
  77782. }
  77783. };
  77784. /**
  77785. * Clones the current image processing instance.
  77786. * @return The cloned image processing
  77787. */
  77788. ImageProcessingConfiguration.prototype.clone = function () {
  77789. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77790. };
  77791. /**
  77792. * Serializes the current image processing instance to a json representation.
  77793. * @return a JSON representation
  77794. */
  77795. ImageProcessingConfiguration.prototype.serialize = function () {
  77796. return BABYLON.SerializationHelper.Serialize(this);
  77797. };
  77798. /**
  77799. * Parses the image processing from a json representation.
  77800. * @param source the JSON source to parse
  77801. * @return The parsed image processing
  77802. */
  77803. ImageProcessingConfiguration.Parse = function (source) {
  77804. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77805. };
  77806. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77807. /**
  77808. * Used to apply the vignette as a mix with the pixel color.
  77809. */
  77810. get: function () {
  77811. return this._VIGNETTEMODE_MULTIPLY;
  77812. },
  77813. enumerable: true,
  77814. configurable: true
  77815. });
  77816. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77817. /**
  77818. * Used to apply the vignette as a replacement of the pixel color.
  77819. */
  77820. get: function () {
  77821. return this._VIGNETTEMODE_OPAQUE;
  77822. },
  77823. enumerable: true,
  77824. configurable: true
  77825. });
  77826. // Static constants associated to the image processing.
  77827. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77828. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77829. __decorate([
  77830. BABYLON.serializeAsColorCurves()
  77831. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77832. __decorate([
  77833. BABYLON.serialize()
  77834. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77835. __decorate([
  77836. BABYLON.serializeAsTexture()
  77837. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77838. __decorate([
  77839. BABYLON.serialize()
  77840. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77841. __decorate([
  77842. BABYLON.serialize()
  77843. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77844. __decorate([
  77845. BABYLON.serialize()
  77846. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77847. __decorate([
  77848. BABYLON.serialize()
  77849. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77850. __decorate([
  77851. BABYLON.serialize()
  77852. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77853. __decorate([
  77854. BABYLON.serialize()
  77855. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77856. __decorate([
  77857. BABYLON.serialize()
  77858. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77859. __decorate([
  77860. BABYLON.serialize()
  77861. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77862. __decorate([
  77863. BABYLON.serialize()
  77864. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77865. __decorate([
  77866. BABYLON.serialize()
  77867. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77868. __decorate([
  77869. BABYLON.serializeAsColor4()
  77870. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77871. __decorate([
  77872. BABYLON.serialize()
  77873. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77874. __decorate([
  77875. BABYLON.serialize()
  77876. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77877. __decorate([
  77878. BABYLON.serialize()
  77879. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77880. __decorate([
  77881. BABYLON.serialize()
  77882. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77883. __decorate([
  77884. BABYLON.serialize()
  77885. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77886. return ImageProcessingConfiguration;
  77887. }());
  77888. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77889. })(BABYLON || (BABYLON = {}));
  77890. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77891. var BABYLON;
  77892. (function (BABYLON) {
  77893. /**
  77894. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77895. * It can help converting any input color in a desired output one. This can then be used to create effects
  77896. * from sepia, black and white to sixties or futuristic rendering...
  77897. *
  77898. * The only supported format is currently 3dl.
  77899. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77900. */
  77901. var ColorGradingTexture = /** @class */ (function (_super) {
  77902. __extends(ColorGradingTexture, _super);
  77903. /**
  77904. * Instantiates a ColorGradingTexture from the following parameters.
  77905. *
  77906. * @param url The location of the color gradind data (currently only supporting 3dl)
  77907. * @param scene The scene the texture will be used in
  77908. */
  77909. function ColorGradingTexture(url, scene) {
  77910. var _this = _super.call(this, scene) || this;
  77911. if (!url) {
  77912. return _this;
  77913. }
  77914. _this._engine = scene.getEngine();
  77915. _this._textureMatrix = BABYLON.Matrix.Identity();
  77916. _this.name = url;
  77917. _this.url = url;
  77918. _this.hasAlpha = false;
  77919. _this.isCube = false;
  77920. _this.is3D = _this._engine.webGLVersion > 1;
  77921. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77922. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77923. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77924. _this.anisotropicFilteringLevel = 1;
  77925. _this._texture = _this._getFromCache(url, true);
  77926. if (!_this._texture) {
  77927. if (!scene.useDelayedTextureLoading) {
  77928. _this.loadTexture();
  77929. }
  77930. else {
  77931. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77932. }
  77933. }
  77934. return _this;
  77935. }
  77936. /**
  77937. * Returns the texture matrix used in most of the material.
  77938. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77939. */
  77940. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77941. return this._textureMatrix;
  77942. };
  77943. /**
  77944. * Occurs when the file being loaded is a .3dl LUT file.
  77945. */
  77946. ColorGradingTexture.prototype.load3dlTexture = function () {
  77947. var engine = this._engine;
  77948. var texture;
  77949. if (engine.webGLVersion === 1) {
  77950. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77951. }
  77952. else {
  77953. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77954. }
  77955. this._texture = texture;
  77956. var callback = function (text) {
  77957. if (typeof text !== "string") {
  77958. return;
  77959. }
  77960. var data = null;
  77961. var tempData = null;
  77962. var line;
  77963. var lines = text.split('\n');
  77964. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77965. var maxColor = 0;
  77966. for (var i = 0; i < lines.length; i++) {
  77967. line = lines[i];
  77968. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77969. continue;
  77970. if (line.indexOf('#') === 0)
  77971. continue;
  77972. var words = line.split(" ");
  77973. if (size === 0) {
  77974. // Number of space + one
  77975. size = words.length;
  77976. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77977. tempData = new Float32Array(size * size * size * 4);
  77978. continue;
  77979. }
  77980. if (size != 0) {
  77981. var r = Math.max(parseInt(words[0]), 0);
  77982. var g = Math.max(parseInt(words[1]), 0);
  77983. var b = Math.max(parseInt(words[2]), 0);
  77984. maxColor = Math.max(r, maxColor);
  77985. maxColor = Math.max(g, maxColor);
  77986. maxColor = Math.max(b, maxColor);
  77987. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77988. if (tempData) {
  77989. tempData[pixelStorageIndex + 0] = r;
  77990. tempData[pixelStorageIndex + 1] = g;
  77991. tempData[pixelStorageIndex + 2] = b;
  77992. }
  77993. pixelIndexSlice++;
  77994. if (pixelIndexSlice % size == 0) {
  77995. pixelIndexH++;
  77996. pixelIndexSlice = 0;
  77997. if (pixelIndexH % size == 0) {
  77998. pixelIndexW++;
  77999. pixelIndexH = 0;
  78000. }
  78001. }
  78002. }
  78003. }
  78004. if (tempData && data) {
  78005. for (var i = 0; i < tempData.length; i++) {
  78006. if (i > 0 && (i + 1) % 4 === 0) {
  78007. data[i] = 255;
  78008. }
  78009. else {
  78010. var value = tempData[i];
  78011. data[i] = (value / maxColor * 255);
  78012. }
  78013. }
  78014. }
  78015. if (texture.is3D) {
  78016. texture.updateSize(size, size, size);
  78017. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78018. }
  78019. else {
  78020. texture.updateSize(size * size, size);
  78021. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78022. }
  78023. };
  78024. var scene = this.getScene();
  78025. if (scene) {
  78026. scene._loadFile(this.url, callback);
  78027. }
  78028. else {
  78029. this._engine._loadFile(this.url, callback);
  78030. }
  78031. return this._texture;
  78032. };
  78033. /**
  78034. * Starts the loading process of the texture.
  78035. */
  78036. ColorGradingTexture.prototype.loadTexture = function () {
  78037. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  78038. this.load3dlTexture();
  78039. }
  78040. };
  78041. /**
  78042. * Clones the color gradind texture.
  78043. */
  78044. ColorGradingTexture.prototype.clone = function () {
  78045. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  78046. // Base texture
  78047. newTexture.level = this.level;
  78048. return newTexture;
  78049. };
  78050. /**
  78051. * Called during delayed load for textures.
  78052. */
  78053. ColorGradingTexture.prototype.delayLoad = function () {
  78054. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78055. return;
  78056. }
  78057. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78058. this._texture = this._getFromCache(this.url, true);
  78059. if (!this._texture) {
  78060. this.loadTexture();
  78061. }
  78062. };
  78063. /**
  78064. * Parses a color grading texture serialized by Babylon.
  78065. * @param parsedTexture The texture information being parsedTexture
  78066. * @param scene The scene to load the texture in
  78067. * @param rootUrl The root url of the data assets to load
  78068. * @return A color gradind texture
  78069. */
  78070. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78071. var texture = null;
  78072. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78073. texture = new ColorGradingTexture(parsedTexture.name, scene);
  78074. texture.name = parsedTexture.name;
  78075. texture.level = parsedTexture.level;
  78076. }
  78077. return texture;
  78078. };
  78079. /**
  78080. * Serializes the LUT texture to json format.
  78081. */
  78082. ColorGradingTexture.prototype.serialize = function () {
  78083. if (!this.name) {
  78084. return null;
  78085. }
  78086. var serializationObject = {};
  78087. serializationObject.name = this.name;
  78088. serializationObject.level = this.level;
  78089. serializationObject.customType = "BABYLON.ColorGradingTexture";
  78090. return serializationObject;
  78091. };
  78092. /**
  78093. * Empty line regex stored for GC.
  78094. */
  78095. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  78096. return ColorGradingTexture;
  78097. }(BABYLON.BaseTexture));
  78098. BABYLON.ColorGradingTexture = ColorGradingTexture;
  78099. })(BABYLON || (BABYLON = {}));
  78100. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  78101. var BABYLON;
  78102. (function (BABYLON) {
  78103. /**
  78104. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78105. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78106. * 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;
  78107. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78108. */
  78109. var ColorCurves = /** @class */ (function () {
  78110. function ColorCurves() {
  78111. this._dirty = true;
  78112. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  78113. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  78114. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78115. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  78116. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78117. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  78118. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  78119. this._globalHue = 30;
  78120. this._globalDensity = 0;
  78121. this._globalSaturation = 0;
  78122. this._globalExposure = 0;
  78123. this._highlightsHue = 30;
  78124. this._highlightsDensity = 0;
  78125. this._highlightsSaturation = 0;
  78126. this._highlightsExposure = 0;
  78127. this._midtonesHue = 30;
  78128. this._midtonesDensity = 0;
  78129. this._midtonesSaturation = 0;
  78130. this._midtonesExposure = 0;
  78131. this._shadowsHue = 30;
  78132. this._shadowsDensity = 0;
  78133. this._shadowsSaturation = 0;
  78134. this._shadowsExposure = 0;
  78135. }
  78136. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  78137. /**
  78138. * Gets the global Hue value.
  78139. * 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).
  78140. */
  78141. get: function () {
  78142. return this._globalHue;
  78143. },
  78144. /**
  78145. * Sets the global Hue value.
  78146. * 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).
  78147. */
  78148. set: function (value) {
  78149. this._globalHue = value;
  78150. this._dirty = true;
  78151. },
  78152. enumerable: true,
  78153. configurable: true
  78154. });
  78155. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  78156. /**
  78157. * Gets the global Density value.
  78158. * 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.
  78159. * Values less than zero provide a filter of opposite hue.
  78160. */
  78161. get: function () {
  78162. return this._globalDensity;
  78163. },
  78164. /**
  78165. * Sets the global Density value.
  78166. * 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.
  78167. * Values less than zero provide a filter of opposite hue.
  78168. */
  78169. set: function (value) {
  78170. this._globalDensity = value;
  78171. this._dirty = true;
  78172. },
  78173. enumerable: true,
  78174. configurable: true
  78175. });
  78176. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  78177. /**
  78178. * Gets the global Saturation value.
  78179. * 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.
  78180. */
  78181. get: function () {
  78182. return this._globalSaturation;
  78183. },
  78184. /**
  78185. * Sets the global Saturation value.
  78186. * 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.
  78187. */
  78188. set: function (value) {
  78189. this._globalSaturation = value;
  78190. this._dirty = true;
  78191. },
  78192. enumerable: true,
  78193. configurable: true
  78194. });
  78195. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  78196. /**
  78197. * Gets the global Exposure value.
  78198. * 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.
  78199. */
  78200. get: function () {
  78201. return this._globalExposure;
  78202. },
  78203. /**
  78204. * Sets the global Exposure value.
  78205. * 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.
  78206. */
  78207. set: function (value) {
  78208. this._globalExposure = value;
  78209. this._dirty = true;
  78210. },
  78211. enumerable: true,
  78212. configurable: true
  78213. });
  78214. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  78215. /**
  78216. * Gets the highlights Hue value.
  78217. * 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).
  78218. */
  78219. get: function () {
  78220. return this._highlightsHue;
  78221. },
  78222. /**
  78223. * Sets the highlights Hue value.
  78224. * 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).
  78225. */
  78226. set: function (value) {
  78227. this._highlightsHue = value;
  78228. this._dirty = true;
  78229. },
  78230. enumerable: true,
  78231. configurable: true
  78232. });
  78233. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  78234. /**
  78235. * Gets the highlights Density value.
  78236. * 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.
  78237. * Values less than zero provide a filter of opposite hue.
  78238. */
  78239. get: function () {
  78240. return this._highlightsDensity;
  78241. },
  78242. /**
  78243. * Sets the highlights Density value.
  78244. * 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.
  78245. * Values less than zero provide a filter of opposite hue.
  78246. */
  78247. set: function (value) {
  78248. this._highlightsDensity = value;
  78249. this._dirty = true;
  78250. },
  78251. enumerable: true,
  78252. configurable: true
  78253. });
  78254. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  78255. /**
  78256. * Gets the highlights Saturation value.
  78257. * 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.
  78258. */
  78259. get: function () {
  78260. return this._highlightsSaturation;
  78261. },
  78262. /**
  78263. * Sets the highlights Saturation value.
  78264. * 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.
  78265. */
  78266. set: function (value) {
  78267. this._highlightsSaturation = value;
  78268. this._dirty = true;
  78269. },
  78270. enumerable: true,
  78271. configurable: true
  78272. });
  78273. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78274. /**
  78275. * Gets the highlights Exposure value.
  78276. * 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.
  78277. */
  78278. get: function () {
  78279. return this._highlightsExposure;
  78280. },
  78281. /**
  78282. * Sets the highlights Exposure value.
  78283. * 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.
  78284. */
  78285. set: function (value) {
  78286. this._highlightsExposure = value;
  78287. this._dirty = true;
  78288. },
  78289. enumerable: true,
  78290. configurable: true
  78291. });
  78292. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78293. /**
  78294. * Gets the midtones Hue value.
  78295. * 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).
  78296. */
  78297. get: function () {
  78298. return this._midtonesHue;
  78299. },
  78300. /**
  78301. * Sets the midtones Hue value.
  78302. * 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).
  78303. */
  78304. set: function (value) {
  78305. this._midtonesHue = value;
  78306. this._dirty = true;
  78307. },
  78308. enumerable: true,
  78309. configurable: true
  78310. });
  78311. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78312. /**
  78313. * Gets the midtones Density value.
  78314. * 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.
  78315. * Values less than zero provide a filter of opposite hue.
  78316. */
  78317. get: function () {
  78318. return this._midtonesDensity;
  78319. },
  78320. /**
  78321. * Sets the midtones Density value.
  78322. * 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.
  78323. * Values less than zero provide a filter of opposite hue.
  78324. */
  78325. set: function (value) {
  78326. this._midtonesDensity = value;
  78327. this._dirty = true;
  78328. },
  78329. enumerable: true,
  78330. configurable: true
  78331. });
  78332. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78333. /**
  78334. * Gets the midtones Saturation value.
  78335. * 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.
  78336. */
  78337. get: function () {
  78338. return this._midtonesSaturation;
  78339. },
  78340. /**
  78341. * Sets the midtones Saturation value.
  78342. * 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.
  78343. */
  78344. set: function (value) {
  78345. this._midtonesSaturation = value;
  78346. this._dirty = true;
  78347. },
  78348. enumerable: true,
  78349. configurable: true
  78350. });
  78351. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78352. /**
  78353. * Gets the midtones Exposure value.
  78354. * 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.
  78355. */
  78356. get: function () {
  78357. return this._midtonesExposure;
  78358. },
  78359. /**
  78360. * Sets the midtones Exposure value.
  78361. * 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.
  78362. */
  78363. set: function (value) {
  78364. this._midtonesExposure = value;
  78365. this._dirty = true;
  78366. },
  78367. enumerable: true,
  78368. configurable: true
  78369. });
  78370. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78371. /**
  78372. * Gets the shadows Hue value.
  78373. * 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).
  78374. */
  78375. get: function () {
  78376. return this._shadowsHue;
  78377. },
  78378. /**
  78379. * Sets the shadows Hue value.
  78380. * 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).
  78381. */
  78382. set: function (value) {
  78383. this._shadowsHue = value;
  78384. this._dirty = true;
  78385. },
  78386. enumerable: true,
  78387. configurable: true
  78388. });
  78389. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78390. /**
  78391. * Gets the shadows Density value.
  78392. * 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.
  78393. * Values less than zero provide a filter of opposite hue.
  78394. */
  78395. get: function () {
  78396. return this._shadowsDensity;
  78397. },
  78398. /**
  78399. * Sets the shadows Density value.
  78400. * 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.
  78401. * Values less than zero provide a filter of opposite hue.
  78402. */
  78403. set: function (value) {
  78404. this._shadowsDensity = value;
  78405. this._dirty = true;
  78406. },
  78407. enumerable: true,
  78408. configurable: true
  78409. });
  78410. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78411. /**
  78412. * Gets the shadows Saturation value.
  78413. * 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.
  78414. */
  78415. get: function () {
  78416. return this._shadowsSaturation;
  78417. },
  78418. /**
  78419. * Sets the shadows Saturation value.
  78420. * 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.
  78421. */
  78422. set: function (value) {
  78423. this._shadowsSaturation = value;
  78424. this._dirty = true;
  78425. },
  78426. enumerable: true,
  78427. configurable: true
  78428. });
  78429. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78430. /**
  78431. * Gets the shadows Exposure value.
  78432. * 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.
  78433. */
  78434. get: function () {
  78435. return this._shadowsExposure;
  78436. },
  78437. /**
  78438. * Sets the shadows Exposure value.
  78439. * 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.
  78440. */
  78441. set: function (value) {
  78442. this._shadowsExposure = value;
  78443. this._dirty = true;
  78444. },
  78445. enumerable: true,
  78446. configurable: true
  78447. });
  78448. ColorCurves.prototype.getClassName = function () {
  78449. return "ColorCurves";
  78450. };
  78451. /**
  78452. * Binds the color curves to the shader.
  78453. * @param colorCurves The color curve to bind
  78454. * @param effect The effect to bind to
  78455. */
  78456. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78457. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78458. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78459. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78460. if (colorCurves._dirty) {
  78461. colorCurves._dirty = false;
  78462. // Fill in global info.
  78463. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78464. // Compute highlights info.
  78465. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78466. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78467. // Compute midtones info.
  78468. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78469. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78470. // Compute shadows info.
  78471. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78472. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78473. // Compute deltas (neutral is midtones).
  78474. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78475. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78476. }
  78477. if (effect) {
  78478. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78479. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78480. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78481. }
  78482. };
  78483. /**
  78484. * Prepare the list of uniforms associated with the ColorCurves effects.
  78485. * @param uniformsList The list of uniforms used in the effect
  78486. */
  78487. ColorCurves.PrepareUniforms = function (uniformsList) {
  78488. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78489. };
  78490. /**
  78491. * Returns color grading data based on a hue, density, saturation and exposure value.
  78492. * @param filterHue The hue of the color filter.
  78493. * @param filterDensity The density of the color filter.
  78494. * @param saturation The saturation.
  78495. * @param exposure The exposure.
  78496. * @param result The result data container.
  78497. */
  78498. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78499. if (hue == null) {
  78500. return;
  78501. }
  78502. hue = ColorCurves.clamp(hue, 0, 360);
  78503. density = ColorCurves.clamp(density, -100, 100);
  78504. saturation = ColorCurves.clamp(saturation, -100, 100);
  78505. exposure = ColorCurves.clamp(exposure, -100, 100);
  78506. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78507. // so that the maximum filter density is only 50% control. This provides fine control
  78508. // for small values and reasonable range.
  78509. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78510. density *= 0.5;
  78511. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78512. if (density < 0) {
  78513. density *= -1;
  78514. hue = (hue + 180) % 360;
  78515. }
  78516. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78517. result.scaleToRef(2, result);
  78518. result.a = 1 + 0.01 * saturation;
  78519. };
  78520. /**
  78521. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78522. * @param value The input slider value in range [-100,100].
  78523. * @returns Adjusted value.
  78524. */
  78525. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78526. value /= 100;
  78527. var x = Math.abs(value);
  78528. x = Math.pow(x, 2);
  78529. if (value < 0) {
  78530. x *= -1;
  78531. }
  78532. x *= 100;
  78533. return x;
  78534. };
  78535. /**
  78536. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78537. * @param hue The hue (H) input.
  78538. * @param saturation The saturation (S) input.
  78539. * @param brightness The brightness (B) input.
  78540. * @result An RGBA color represented as Vector4.
  78541. */
  78542. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78543. var h = ColorCurves.clamp(hue, 0, 360);
  78544. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78545. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78546. if (s === 0) {
  78547. result.r = v;
  78548. result.g = v;
  78549. result.b = v;
  78550. }
  78551. else {
  78552. // sector 0 to 5
  78553. h /= 60;
  78554. var i = Math.floor(h);
  78555. // fractional part of h
  78556. var f = h - i;
  78557. var p = v * (1 - s);
  78558. var q = v * (1 - s * f);
  78559. var t = v * (1 - s * (1 - f));
  78560. switch (i) {
  78561. case 0:
  78562. result.r = v;
  78563. result.g = t;
  78564. result.b = p;
  78565. break;
  78566. case 1:
  78567. result.r = q;
  78568. result.g = v;
  78569. result.b = p;
  78570. break;
  78571. case 2:
  78572. result.r = p;
  78573. result.g = v;
  78574. result.b = t;
  78575. break;
  78576. case 3:
  78577. result.r = p;
  78578. result.g = q;
  78579. result.b = v;
  78580. break;
  78581. case 4:
  78582. result.r = t;
  78583. result.g = p;
  78584. result.b = v;
  78585. break;
  78586. default: // case 5:
  78587. result.r = v;
  78588. result.g = p;
  78589. result.b = q;
  78590. break;
  78591. }
  78592. }
  78593. result.a = 1;
  78594. };
  78595. /**
  78596. * Returns a value clamped between min and max
  78597. * @param value The value to clamp
  78598. * @param min The minimum of value
  78599. * @param max The maximum of value
  78600. * @returns The clamped value.
  78601. */
  78602. ColorCurves.clamp = function (value, min, max) {
  78603. return Math.min(Math.max(value, min), max);
  78604. };
  78605. /**
  78606. * Clones the current color curve instance.
  78607. * @return The cloned curves
  78608. */
  78609. ColorCurves.prototype.clone = function () {
  78610. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78611. };
  78612. /**
  78613. * Serializes the current color curve instance to a json representation.
  78614. * @return a JSON representation
  78615. */
  78616. ColorCurves.prototype.serialize = function () {
  78617. return BABYLON.SerializationHelper.Serialize(this);
  78618. };
  78619. /**
  78620. * Parses the color curve from a json representation.
  78621. * @param source the JSON source to parse
  78622. * @return The parsed curves
  78623. */
  78624. ColorCurves.Parse = function (source) {
  78625. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78626. };
  78627. __decorate([
  78628. BABYLON.serialize()
  78629. ], ColorCurves.prototype, "_globalHue", void 0);
  78630. __decorate([
  78631. BABYLON.serialize()
  78632. ], ColorCurves.prototype, "_globalDensity", void 0);
  78633. __decorate([
  78634. BABYLON.serialize()
  78635. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78636. __decorate([
  78637. BABYLON.serialize()
  78638. ], ColorCurves.prototype, "_globalExposure", void 0);
  78639. __decorate([
  78640. BABYLON.serialize()
  78641. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78642. __decorate([
  78643. BABYLON.serialize()
  78644. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78645. __decorate([
  78646. BABYLON.serialize()
  78647. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78648. __decorate([
  78649. BABYLON.serialize()
  78650. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78651. __decorate([
  78652. BABYLON.serialize()
  78653. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78654. __decorate([
  78655. BABYLON.serialize()
  78656. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78657. __decorate([
  78658. BABYLON.serialize()
  78659. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78660. __decorate([
  78661. BABYLON.serialize()
  78662. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78663. return ColorCurves;
  78664. }());
  78665. BABYLON.ColorCurves = ColorCurves;
  78666. })(BABYLON || (BABYLON = {}));
  78667. //# sourceMappingURL=babylon.colorCurves.js.map
  78668. var BABYLON;
  78669. (function (BABYLON) {
  78670. var RefractionPostProcess = /** @class */ (function (_super) {
  78671. __extends(RefractionPostProcess, _super);
  78672. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78673. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78674. _this.color = color;
  78675. _this.depth = depth;
  78676. _this.colorLevel = colorLevel;
  78677. _this._ownRefractionTexture = true;
  78678. _this.onActivateObservable.add(function (cam) {
  78679. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78680. });
  78681. _this.onApplyObservable.add(function (effect) {
  78682. effect.setColor3("baseColor", _this.color);
  78683. effect.setFloat("depth", _this.depth);
  78684. effect.setFloat("colorLevel", _this.colorLevel);
  78685. effect.setTexture("refractionSampler", _this._refTexture);
  78686. });
  78687. return _this;
  78688. }
  78689. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78690. /**
  78691. * Gets or sets the refraction texture
  78692. * Please note that you are responsible for disposing the texture if you set it manually
  78693. */
  78694. get: function () {
  78695. return this._refTexture;
  78696. },
  78697. set: function (value) {
  78698. if (this._refTexture && this._ownRefractionTexture) {
  78699. this._refTexture.dispose();
  78700. }
  78701. this._refTexture = value;
  78702. this._ownRefractionTexture = false;
  78703. },
  78704. enumerable: true,
  78705. configurable: true
  78706. });
  78707. // Methods
  78708. RefractionPostProcess.prototype.dispose = function (camera) {
  78709. if (this._refTexture && this._ownRefractionTexture) {
  78710. this._refTexture.dispose();
  78711. this._refTexture = null;
  78712. }
  78713. _super.prototype.dispose.call(this, camera);
  78714. };
  78715. return RefractionPostProcess;
  78716. }(BABYLON.PostProcess));
  78717. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78718. })(BABYLON || (BABYLON = {}));
  78719. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78720. var BABYLON;
  78721. (function (BABYLON) {
  78722. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78723. __extends(BlackAndWhitePostProcess, _super);
  78724. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78725. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78726. _this.degree = 1;
  78727. _this.onApplyObservable.add(function (effect) {
  78728. effect.setFloat("degree", _this.degree);
  78729. });
  78730. return _this;
  78731. }
  78732. return BlackAndWhitePostProcess;
  78733. }(BABYLON.PostProcess));
  78734. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78735. })(BABYLON || (BABYLON = {}));
  78736. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78737. var BABYLON;
  78738. (function (BABYLON) {
  78739. /**
  78740. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78741. * input texture to perform effects such as edge detection or sharpening
  78742. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78743. */
  78744. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78745. __extends(ConvolutionPostProcess, _super);
  78746. /**
  78747. * Creates a new instance ConvolutionPostProcess
  78748. * @param name The name of the effect.
  78749. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78750. * @param options The required width/height ratio to downsize to before computing the render pass.
  78751. * @param camera The camera to apply the render pass to.
  78752. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78753. * @param engine The engine which the post process will be applied. (default: current engine)
  78754. * @param reusable If the post process can be reused on the same frame. (default: false)
  78755. * @param textureType Type of textures used when performing the post process. (default: 0)
  78756. */
  78757. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78758. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78759. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78760. _this.kernel = kernel;
  78761. _this.onApply = function (effect) {
  78762. effect.setFloat2("screenSize", _this.width, _this.height);
  78763. effect.setArray("kernel", _this.kernel);
  78764. };
  78765. return _this;
  78766. }
  78767. // Statics
  78768. /**
  78769. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78770. */
  78771. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78772. /**
  78773. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78774. */
  78775. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78776. /**
  78777. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78778. */
  78779. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78780. /**
  78781. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78782. */
  78783. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78784. /**
  78785. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78786. */
  78787. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78788. /**
  78789. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78790. */
  78791. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78792. return ConvolutionPostProcess;
  78793. }(BABYLON.PostProcess));
  78794. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78795. })(BABYLON || (BABYLON = {}));
  78796. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78797. var BABYLON;
  78798. (function (BABYLON) {
  78799. var FilterPostProcess = /** @class */ (function (_super) {
  78800. __extends(FilterPostProcess, _super);
  78801. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78802. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78803. _this.kernelMatrix = kernelMatrix;
  78804. _this.onApply = function (effect) {
  78805. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78806. };
  78807. return _this;
  78808. }
  78809. return FilterPostProcess;
  78810. }(BABYLON.PostProcess));
  78811. BABYLON.FilterPostProcess = FilterPostProcess;
  78812. })(BABYLON || (BABYLON = {}));
  78813. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78814. var BABYLON;
  78815. (function (BABYLON) {
  78816. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78817. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78818. __extends(VolumetricLightScatteringPostProcess, _super);
  78819. /**
  78820. * @constructor
  78821. * @param {string} name - The post-process name
  78822. * @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)
  78823. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78824. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78825. * @param {number} samples - The post-process quality, default 100
  78826. * @param {number} samplingMode - The post-process filtering mode
  78827. * @param {BABYLON.Engine} engine - The babylon engine
  78828. * @param {boolean} reusable - If the post-process is reusable
  78829. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78830. */
  78831. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78832. if (samples === void 0) { samples = 100; }
  78833. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78834. 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;
  78835. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78836. /**
  78837. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78838. */
  78839. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78840. /**
  78841. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78842. */
  78843. _this.useCustomMeshPosition = false;
  78844. /**
  78845. * If the post-process should inverse the light scattering direction
  78846. */
  78847. _this.invert = true;
  78848. /**
  78849. * Array containing the excluded meshes not rendered in the internal pass
  78850. */
  78851. _this.excludedMeshes = new Array();
  78852. /**
  78853. * Controls the overall intensity of the post-process
  78854. */
  78855. _this.exposure = 0.3;
  78856. /**
  78857. * Dissipates each sample's contribution in range [0, 1]
  78858. */
  78859. _this.decay = 0.96815;
  78860. /**
  78861. * Controls the overall intensity of each sample
  78862. */
  78863. _this.weight = 0.58767;
  78864. /**
  78865. * Controls the density of each sample
  78866. */
  78867. _this.density = 0.926;
  78868. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78869. engine = scene.getEngine();
  78870. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78871. // Configure mesh
  78872. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78873. // Configure
  78874. _this._createPass(scene, ratio.passRatio || ratio);
  78875. _this.onActivate = function (camera) {
  78876. if (!_this.isSupported) {
  78877. _this.dispose(camera);
  78878. }
  78879. _this.onActivate = null;
  78880. };
  78881. _this.onApplyObservable.add(function (effect) {
  78882. _this._updateMeshScreenCoordinates(scene);
  78883. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78884. effect.setFloat("exposure", _this.exposure);
  78885. effect.setFloat("decay", _this.decay);
  78886. effect.setFloat("weight", _this.weight);
  78887. effect.setFloat("density", _this.density);
  78888. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78889. });
  78890. return _this;
  78891. }
  78892. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78893. get: function () {
  78894. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78895. return false;
  78896. },
  78897. set: function (useDiffuseColor) {
  78898. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78899. },
  78900. enumerable: true,
  78901. configurable: true
  78902. });
  78903. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78904. return "VolumetricLightScatteringPostProcess";
  78905. };
  78906. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78907. var mesh = subMesh.getMesh();
  78908. // Render this.mesh as default
  78909. if (mesh === this.mesh && mesh.material) {
  78910. return mesh.material.isReady(mesh);
  78911. }
  78912. var defines = [];
  78913. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78914. var material = subMesh.getMaterial();
  78915. // Alpha test
  78916. if (material) {
  78917. if (material.needAlphaTesting()) {
  78918. defines.push("#define ALPHATEST");
  78919. }
  78920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78921. attribs.push(BABYLON.VertexBuffer.UVKind);
  78922. defines.push("#define UV1");
  78923. }
  78924. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78925. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78926. defines.push("#define UV2");
  78927. }
  78928. }
  78929. // Bones
  78930. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78931. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78932. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78933. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78934. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78935. }
  78936. else {
  78937. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78938. }
  78939. // Instances
  78940. if (useInstances) {
  78941. defines.push("#define INSTANCES");
  78942. attribs.push("world0");
  78943. attribs.push("world1");
  78944. attribs.push("world2");
  78945. attribs.push("world3");
  78946. }
  78947. // Get correct effect
  78948. var join = defines.join("\n");
  78949. if (this._cachedDefines !== join) {
  78950. this._cachedDefines = join;
  78951. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78952. }
  78953. return this._volumetricLightScatteringPass.isReady();
  78954. };
  78955. /**
  78956. * Sets the new light position for light scattering effect
  78957. * @param {BABYLON.Vector3} The new custom light position
  78958. */
  78959. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78960. this.customMeshPosition = position;
  78961. };
  78962. /**
  78963. * Returns the light position for light scattering effect
  78964. * @return {BABYLON.Vector3} The custom light position
  78965. */
  78966. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78967. return this.customMeshPosition;
  78968. };
  78969. /**
  78970. * Disposes the internal assets and detaches the post-process from the camera
  78971. */
  78972. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78973. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78974. if (rttIndex !== -1) {
  78975. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78976. }
  78977. this._volumetricLightScatteringRTT.dispose();
  78978. _super.prototype.dispose.call(this, camera);
  78979. };
  78980. /**
  78981. * Returns the render target texture used by the post-process
  78982. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78983. */
  78984. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78985. return this._volumetricLightScatteringRTT;
  78986. };
  78987. // Private methods
  78988. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78989. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78990. return true;
  78991. }
  78992. return false;
  78993. };
  78994. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78995. var _this = this;
  78996. var engine = scene.getEngine();
  78997. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78998. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78999. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79000. this._volumetricLightScatteringRTT.renderList = null;
  79001. this._volumetricLightScatteringRTT.renderParticles = false;
  79002. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  79003. var camera = this.getCamera();
  79004. if (camera) {
  79005. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  79006. }
  79007. else {
  79008. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  79009. }
  79010. // Custom render function for submeshes
  79011. var renderSubMesh = function (subMesh) {
  79012. var mesh = subMesh.getRenderingMesh();
  79013. if (_this._meshExcluded(mesh)) {
  79014. return;
  79015. }
  79016. var material = subMesh.getMaterial();
  79017. if (!material) {
  79018. return;
  79019. }
  79020. var scene = mesh.getScene();
  79021. var engine = scene.getEngine();
  79022. // Culling
  79023. engine.setState(material.backFaceCulling);
  79024. // Managing instances
  79025. var batch = mesh._getInstancesRenderList(subMesh._id);
  79026. if (batch.mustReturn) {
  79027. return;
  79028. }
  79029. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79030. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  79031. var effect = _this._volumetricLightScatteringPass;
  79032. if (mesh === _this.mesh) {
  79033. if (subMesh.effect) {
  79034. effect = subMesh.effect;
  79035. }
  79036. else {
  79037. effect = material.getEffect();
  79038. }
  79039. }
  79040. engine.enableEffect(effect);
  79041. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  79042. if (mesh === _this.mesh) {
  79043. material.bind(mesh.getWorldMatrix(), mesh);
  79044. }
  79045. else {
  79046. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  79047. // Alpha test
  79048. if (material && material.needAlphaTesting()) {
  79049. var alphaTexture = material.getAlphaTestTexture();
  79050. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  79051. if (alphaTexture) {
  79052. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79053. }
  79054. }
  79055. // Bones
  79056. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79057. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79058. }
  79059. }
  79060. // Draw
  79061. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  79062. }
  79063. };
  79064. // Render target texture callbacks
  79065. var savedSceneClearColor;
  79066. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  79067. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  79068. savedSceneClearColor = scene.clearColor;
  79069. scene.clearColor = sceneClearColor;
  79070. });
  79071. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  79072. scene.clearColor = savedSceneClearColor;
  79073. });
  79074. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79075. var engine = scene.getEngine();
  79076. var index;
  79077. if (depthOnlySubMeshes.length) {
  79078. engine.setColorWrite(false);
  79079. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79080. renderSubMesh(depthOnlySubMeshes.data[index]);
  79081. }
  79082. engine.setColorWrite(true);
  79083. }
  79084. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79085. renderSubMesh(opaqueSubMeshes.data[index]);
  79086. }
  79087. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79088. renderSubMesh(alphaTestSubMeshes.data[index]);
  79089. }
  79090. if (transparentSubMeshes.length) {
  79091. // Sort sub meshes
  79092. for (index = 0; index < transparentSubMeshes.length; index++) {
  79093. var submesh = transparentSubMeshes.data[index];
  79094. var boundingInfo = submesh.getBoundingInfo();
  79095. if (boundingInfo && scene.activeCamera) {
  79096. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  79097. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  79098. }
  79099. }
  79100. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  79101. sortedArray.sort(function (a, b) {
  79102. // Alpha index first
  79103. if (a._alphaIndex > b._alphaIndex) {
  79104. return 1;
  79105. }
  79106. if (a._alphaIndex < b._alphaIndex) {
  79107. return -1;
  79108. }
  79109. // Then distance to camera
  79110. if (a._distanceToCamera < b._distanceToCamera) {
  79111. return 1;
  79112. }
  79113. if (a._distanceToCamera > b._distanceToCamera) {
  79114. return -1;
  79115. }
  79116. return 0;
  79117. });
  79118. // Render sub meshes
  79119. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  79120. for (index = 0; index < sortedArray.length; index++) {
  79121. renderSubMesh(sortedArray[index]);
  79122. }
  79123. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79124. }
  79125. };
  79126. };
  79127. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  79128. var transform = scene.getTransformMatrix();
  79129. var meshPosition;
  79130. if (this.useCustomMeshPosition) {
  79131. meshPosition = this.customMeshPosition;
  79132. }
  79133. else if (this.attachedNode) {
  79134. meshPosition = this.attachedNode.position;
  79135. }
  79136. else {
  79137. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  79138. }
  79139. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  79140. this._screenCoordinates.x = pos.x / this._viewPort.width;
  79141. this._screenCoordinates.y = pos.y / this._viewPort.height;
  79142. if (this.invert)
  79143. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  79144. };
  79145. // Static methods
  79146. /**
  79147. * Creates a default mesh for the Volumeric Light Scattering post-process
  79148. * @param {string} The mesh name
  79149. * @param {BABYLON.Scene} The scene where to create the mesh
  79150. * @return {BABYLON.Mesh} the default mesh
  79151. */
  79152. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  79153. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  79154. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  79155. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  79156. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  79157. mesh.material = material;
  79158. return mesh;
  79159. };
  79160. __decorate([
  79161. BABYLON.serializeAsVector3()
  79162. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  79163. __decorate([
  79164. BABYLON.serialize()
  79165. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  79166. __decorate([
  79167. BABYLON.serialize()
  79168. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  79169. __decorate([
  79170. BABYLON.serializeAsMeshReference()
  79171. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  79172. __decorate([
  79173. BABYLON.serialize()
  79174. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  79175. __decorate([
  79176. BABYLON.serialize()
  79177. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  79178. __decorate([
  79179. BABYLON.serialize()
  79180. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  79181. __decorate([
  79182. BABYLON.serialize()
  79183. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  79184. __decorate([
  79185. BABYLON.serialize()
  79186. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  79187. return VolumetricLightScatteringPostProcess;
  79188. }(BABYLON.PostProcess));
  79189. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  79190. })(BABYLON || (BABYLON = {}));
  79191. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  79192. //
  79193. // This post-process allows the modification of rendered colors by using
  79194. // a 'look-up table' (LUT). This effect is also called Color Grading.
  79195. //
  79196. // The object needs to be provided an url to a texture containing the color
  79197. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  79198. // Use an image editing software to tweak the LUT to match your needs.
  79199. //
  79200. // For an example of a color LUT, see here:
  79201. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  79202. // For explanations on color grading, see here:
  79203. // http://udn.epicgames.com/Three/ColorGrading.html
  79204. //
  79205. var BABYLON;
  79206. (function (BABYLON) {
  79207. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  79208. __extends(ColorCorrectionPostProcess, _super);
  79209. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  79210. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  79211. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79212. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  79213. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79214. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79215. _this.onApply = function (effect) {
  79216. effect.setTexture("colorTable", _this._colorTableTexture);
  79217. };
  79218. return _this;
  79219. }
  79220. return ColorCorrectionPostProcess;
  79221. }(BABYLON.PostProcess));
  79222. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  79223. })(BABYLON || (BABYLON = {}));
  79224. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  79225. var BABYLON;
  79226. (function (BABYLON) {
  79227. /** Defines operator used for tonemapping */
  79228. var TonemappingOperator;
  79229. (function (TonemappingOperator) {
  79230. /** Hable */
  79231. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  79232. /** Reinhard */
  79233. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  79234. /** HejiDawson */
  79235. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  79236. /** Photographic */
  79237. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  79238. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  79239. ;
  79240. /**
  79241. * Defines a post process to apply tone mapping
  79242. */
  79243. var TonemapPostProcess = /** @class */ (function (_super) {
  79244. __extends(TonemapPostProcess, _super);
  79245. /**
  79246. * Creates a new TonemapPostProcess
  79247. * @param name defines the name of the postprocess
  79248. * @param _operator defines the operator to use
  79249. * @param exposureAdjustment defines the required exposure adjustement
  79250. * @param camera defines the camera to use (can be null)
  79251. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  79252. * @param engine defines the hosting engine (can be ignore if camera is set)
  79253. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  79254. */
  79255. function TonemapPostProcess(name, _operator,
  79256. /** Defines the required exposure adjustement */
  79257. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  79258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79259. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79260. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  79261. _this._operator = _operator;
  79262. _this.exposureAdjustment = exposureAdjustment;
  79263. var defines = "#define ";
  79264. if (_this._operator === TonemappingOperator.Hable)
  79265. defines += "HABLE_TONEMAPPING";
  79266. else if (_this._operator === TonemappingOperator.Reinhard)
  79267. defines += "REINHARD_TONEMAPPING";
  79268. else if (_this._operator === TonemappingOperator.HejiDawson)
  79269. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79270. else if (_this._operator === TonemappingOperator.Photographic)
  79271. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79272. //sadly a second call to create the effect.
  79273. _this.updateEffect(defines);
  79274. _this.onApply = function (effect) {
  79275. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79276. };
  79277. return _this;
  79278. }
  79279. return TonemapPostProcess;
  79280. }(BABYLON.PostProcess));
  79281. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79282. })(BABYLON || (BABYLON = {}));
  79283. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79284. var BABYLON;
  79285. (function (BABYLON) {
  79286. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79287. __extends(DisplayPassPostProcess, _super);
  79288. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79289. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79290. }
  79291. return DisplayPassPostProcess;
  79292. }(BABYLON.PostProcess));
  79293. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79294. })(BABYLON || (BABYLON = {}));
  79295. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79296. var BABYLON;
  79297. (function (BABYLON) {
  79298. var HighlightsPostProcess = /** @class */ (function (_super) {
  79299. __extends(HighlightsPostProcess, _super);
  79300. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79301. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79302. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79303. }
  79304. return HighlightsPostProcess;
  79305. }(BABYLON.PostProcess));
  79306. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79307. })(BABYLON || (BABYLON = {}));
  79308. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79309. var BABYLON;
  79310. (function (BABYLON) {
  79311. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79312. __extends(ImageProcessingPostProcess, _super);
  79313. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79314. if (camera === void 0) { camera = null; }
  79315. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79316. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79317. _this._fromLinearSpace = true;
  79318. /**
  79319. * Defines cache preventing GC.
  79320. */
  79321. _this._defines = {
  79322. IMAGEPROCESSING: false,
  79323. VIGNETTE: false,
  79324. VIGNETTEBLENDMODEMULTIPLY: false,
  79325. VIGNETTEBLENDMODEOPAQUE: false,
  79326. TONEMAPPING: false,
  79327. CONTRAST: false,
  79328. COLORCURVES: false,
  79329. COLORGRADING: false,
  79330. COLORGRADING3D: false,
  79331. FROMLINEARSPACE: false,
  79332. SAMPLER3DGREENDEPTH: false,
  79333. SAMPLER3DBGRMAP: false,
  79334. IMAGEPROCESSINGPOSTPROCESS: false,
  79335. EXPOSURE: false,
  79336. };
  79337. // Setup the configuration as forced by the constructor. This would then not force the
  79338. // scene materials output in linear space and let untouched the default forward pass.
  79339. if (imageProcessingConfiguration) {
  79340. imageProcessingConfiguration.applyByPostProcess = true;
  79341. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79342. // This will cause the shader to be compiled
  79343. _this.fromLinearSpace = false;
  79344. }
  79345. // Setup the default processing configuration to the scene.
  79346. else {
  79347. _this._attachImageProcessingConfiguration(null, true);
  79348. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79349. }
  79350. _this.onApply = function (effect) {
  79351. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79352. };
  79353. return _this;
  79354. }
  79355. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79356. /**
  79357. * Gets the image processing configuration used either in this material.
  79358. */
  79359. get: function () {
  79360. return this._imageProcessingConfiguration;
  79361. },
  79362. /**
  79363. * Sets the Default image processing configuration used either in the this material.
  79364. *
  79365. * If sets to null, the scene one is in use.
  79366. */
  79367. set: function (value) {
  79368. this._attachImageProcessingConfiguration(value);
  79369. },
  79370. enumerable: true,
  79371. configurable: true
  79372. });
  79373. /**
  79374. * Attaches a new image processing configuration to the PBR Material.
  79375. * @param configuration
  79376. */
  79377. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79378. var _this = this;
  79379. if (doNotBuild === void 0) { doNotBuild = false; }
  79380. if (configuration === this._imageProcessingConfiguration) {
  79381. return;
  79382. }
  79383. // Detaches observer.
  79384. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79385. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79386. }
  79387. // Pick the scene configuration if needed.
  79388. if (!configuration) {
  79389. var scene = null;
  79390. var engine = this.getEngine();
  79391. var camera = this.getCamera();
  79392. if (camera) {
  79393. scene = camera.getScene();
  79394. }
  79395. else if (engine && engine.scenes) {
  79396. var scenes = engine.scenes;
  79397. scene = scenes[scenes.length - 1];
  79398. }
  79399. else {
  79400. scene = BABYLON.Engine.LastCreatedScene;
  79401. }
  79402. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79403. }
  79404. else {
  79405. this._imageProcessingConfiguration = configuration;
  79406. }
  79407. // Attaches observer.
  79408. if (this._imageProcessingConfiguration) {
  79409. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79410. _this._updateParameters();
  79411. });
  79412. }
  79413. // Ensure the effect will be rebuilt.
  79414. if (!doNotBuild) {
  79415. this._updateParameters();
  79416. }
  79417. };
  79418. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79419. /**
  79420. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79421. */
  79422. get: function () {
  79423. return this.imageProcessingConfiguration.colorCurves;
  79424. },
  79425. /**
  79426. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79427. */
  79428. set: function (value) {
  79429. this.imageProcessingConfiguration.colorCurves = value;
  79430. },
  79431. enumerable: true,
  79432. configurable: true
  79433. });
  79434. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79435. /**
  79436. * Gets wether the color curves effect is enabled.
  79437. */
  79438. get: function () {
  79439. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79440. },
  79441. /**
  79442. * Sets wether the color curves effect is enabled.
  79443. */
  79444. set: function (value) {
  79445. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79446. },
  79447. enumerable: true,
  79448. configurable: true
  79449. });
  79450. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79451. /**
  79452. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79453. */
  79454. get: function () {
  79455. return this.imageProcessingConfiguration.colorGradingTexture;
  79456. },
  79457. /**
  79458. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79459. */
  79460. set: function (value) {
  79461. this.imageProcessingConfiguration.colorGradingTexture = value;
  79462. },
  79463. enumerable: true,
  79464. configurable: true
  79465. });
  79466. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79467. /**
  79468. * Gets wether the color grading effect is enabled.
  79469. */
  79470. get: function () {
  79471. return this.imageProcessingConfiguration.colorGradingEnabled;
  79472. },
  79473. /**
  79474. * Gets wether the color grading effect is enabled.
  79475. */
  79476. set: function (value) {
  79477. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79478. },
  79479. enumerable: true,
  79480. configurable: true
  79481. });
  79482. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79483. /**
  79484. * Gets exposure used in the effect.
  79485. */
  79486. get: function () {
  79487. return this.imageProcessingConfiguration.exposure;
  79488. },
  79489. /**
  79490. * Sets exposure used in the effect.
  79491. */
  79492. set: function (value) {
  79493. this.imageProcessingConfiguration.exposure = value;
  79494. },
  79495. enumerable: true,
  79496. configurable: true
  79497. });
  79498. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79499. /**
  79500. * Gets wether tonemapping is enabled or not.
  79501. */
  79502. get: function () {
  79503. return this._imageProcessingConfiguration.toneMappingEnabled;
  79504. },
  79505. /**
  79506. * Sets wether tonemapping is enabled or not
  79507. */
  79508. set: function (value) {
  79509. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79510. },
  79511. enumerable: true,
  79512. configurable: true
  79513. });
  79514. ;
  79515. ;
  79516. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79517. /**
  79518. * Gets contrast used in the effect.
  79519. */
  79520. get: function () {
  79521. return this.imageProcessingConfiguration.contrast;
  79522. },
  79523. /**
  79524. * Sets contrast used in the effect.
  79525. */
  79526. set: function (value) {
  79527. this.imageProcessingConfiguration.contrast = value;
  79528. },
  79529. enumerable: true,
  79530. configurable: true
  79531. });
  79532. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79533. /**
  79534. * Gets Vignette stretch size.
  79535. */
  79536. get: function () {
  79537. return this.imageProcessingConfiguration.vignetteStretch;
  79538. },
  79539. /**
  79540. * Sets Vignette stretch size.
  79541. */
  79542. set: function (value) {
  79543. this.imageProcessingConfiguration.vignetteStretch = value;
  79544. },
  79545. enumerable: true,
  79546. configurable: true
  79547. });
  79548. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79549. /**
  79550. * Gets Vignette centre X Offset.
  79551. */
  79552. get: function () {
  79553. return this.imageProcessingConfiguration.vignetteCentreX;
  79554. },
  79555. /**
  79556. * Sets Vignette centre X Offset.
  79557. */
  79558. set: function (value) {
  79559. this.imageProcessingConfiguration.vignetteCentreX = value;
  79560. },
  79561. enumerable: true,
  79562. configurable: true
  79563. });
  79564. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79565. /**
  79566. * Gets Vignette centre Y Offset.
  79567. */
  79568. get: function () {
  79569. return this.imageProcessingConfiguration.vignetteCentreY;
  79570. },
  79571. /**
  79572. * Sets Vignette centre Y Offset.
  79573. */
  79574. set: function (value) {
  79575. this.imageProcessingConfiguration.vignetteCentreY = value;
  79576. },
  79577. enumerable: true,
  79578. configurable: true
  79579. });
  79580. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79581. /**
  79582. * Gets Vignette weight or intensity of the vignette effect.
  79583. */
  79584. get: function () {
  79585. return this.imageProcessingConfiguration.vignetteWeight;
  79586. },
  79587. /**
  79588. * Sets Vignette weight or intensity of the vignette effect.
  79589. */
  79590. set: function (value) {
  79591. this.imageProcessingConfiguration.vignetteWeight = value;
  79592. },
  79593. enumerable: true,
  79594. configurable: true
  79595. });
  79596. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79597. /**
  79598. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79599. * if vignetteEnabled is set to true.
  79600. */
  79601. get: function () {
  79602. return this.imageProcessingConfiguration.vignetteColor;
  79603. },
  79604. /**
  79605. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79606. * if vignetteEnabled is set to true.
  79607. */
  79608. set: function (value) {
  79609. this.imageProcessingConfiguration.vignetteColor = value;
  79610. },
  79611. enumerable: true,
  79612. configurable: true
  79613. });
  79614. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79615. /**
  79616. * Gets Camera field of view used by the Vignette effect.
  79617. */
  79618. get: function () {
  79619. return this.imageProcessingConfiguration.vignetteCameraFov;
  79620. },
  79621. /**
  79622. * Sets Camera field of view used by the Vignette effect.
  79623. */
  79624. set: function (value) {
  79625. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79626. },
  79627. enumerable: true,
  79628. configurable: true
  79629. });
  79630. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79631. /**
  79632. * Gets the vignette blend mode allowing different kind of effect.
  79633. */
  79634. get: function () {
  79635. return this.imageProcessingConfiguration.vignetteBlendMode;
  79636. },
  79637. /**
  79638. * Sets the vignette blend mode allowing different kind of effect.
  79639. */
  79640. set: function (value) {
  79641. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79642. },
  79643. enumerable: true,
  79644. configurable: true
  79645. });
  79646. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79647. /**
  79648. * Gets wether the vignette effect is enabled.
  79649. */
  79650. get: function () {
  79651. return this.imageProcessingConfiguration.vignetteEnabled;
  79652. },
  79653. /**
  79654. * Sets wether the vignette effect is enabled.
  79655. */
  79656. set: function (value) {
  79657. this.imageProcessingConfiguration.vignetteEnabled = value;
  79658. },
  79659. enumerable: true,
  79660. configurable: true
  79661. });
  79662. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79663. /**
  79664. * Gets wether the input of the processing is in Gamma or Linear Space.
  79665. */
  79666. get: function () {
  79667. return this._fromLinearSpace;
  79668. },
  79669. /**
  79670. * Sets wether the input of the processing is in Gamma or Linear Space.
  79671. */
  79672. set: function (value) {
  79673. if (this._fromLinearSpace === value) {
  79674. return;
  79675. }
  79676. this._fromLinearSpace = value;
  79677. this._updateParameters();
  79678. },
  79679. enumerable: true,
  79680. configurable: true
  79681. });
  79682. ImageProcessingPostProcess.prototype.getClassName = function () {
  79683. return "ImageProcessingPostProcess";
  79684. };
  79685. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79686. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79687. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79688. var defines = "";
  79689. for (var define in this._defines) {
  79690. if (this._defines[define]) {
  79691. defines += "#define " + define + ";\r\n";
  79692. }
  79693. }
  79694. var samplers = ["textureSampler"];
  79695. var uniforms = ["scale"];
  79696. if (BABYLON.ImageProcessingConfiguration) {
  79697. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79698. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79699. }
  79700. this.updateEffect(defines, uniforms, samplers);
  79701. };
  79702. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79703. _super.prototype.dispose.call(this, camera);
  79704. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79705. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79706. }
  79707. if (this._imageProcessingConfiguration) {
  79708. this.imageProcessingConfiguration.applyByPostProcess = false;
  79709. }
  79710. };
  79711. __decorate([
  79712. BABYLON.serialize()
  79713. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79714. return ImageProcessingPostProcess;
  79715. }(BABYLON.PostProcess));
  79716. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79717. })(BABYLON || (BABYLON = {}));
  79718. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79719. var BABYLON;
  79720. (function (BABYLON) {
  79721. /**
  79722. * Class used to store bone information
  79723. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79724. */
  79725. var Bone = /** @class */ (function (_super) {
  79726. __extends(Bone, _super);
  79727. /**
  79728. * Create a new bone
  79729. * @param name defines the bone name
  79730. * @param skeleton defines the parent skeleton
  79731. * @param parentBone defines the parent (can be null if the bone is the root)
  79732. * @param localMatrix defines the local matrix
  79733. * @param restPose defines the rest pose matrix
  79734. * @param baseMatrix defines the base matrix
  79735. * @param index defines index of the bone in the hiearchy
  79736. */
  79737. function Bone(
  79738. /**
  79739. * defines the bone name
  79740. */
  79741. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79742. if (parentBone === void 0) { parentBone = null; }
  79743. if (localMatrix === void 0) { localMatrix = null; }
  79744. if (restPose === void 0) { restPose = null; }
  79745. if (baseMatrix === void 0) { baseMatrix = null; }
  79746. if (index === void 0) { index = null; }
  79747. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79748. _this.name = name;
  79749. /**
  79750. * Gets the list of child bones
  79751. */
  79752. _this.children = new Array();
  79753. /** Gets the animations associated with this bone */
  79754. _this.animations = new Array();
  79755. /**
  79756. * @hidden Internal only
  79757. * Set this value to map this bone to a different index in the transform matrices
  79758. * Set this value to -1 to exclude the bone from the transform matrices
  79759. */
  79760. _this._index = null;
  79761. _this._absoluteTransform = new BABYLON.Matrix();
  79762. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79763. _this._scalingDeterminant = 1;
  79764. _this._worldTransform = new BABYLON.Matrix();
  79765. _this._needToDecompose = true;
  79766. _this._needToCompose = false;
  79767. _this._skeleton = skeleton;
  79768. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79769. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79770. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79771. _this._index = index;
  79772. skeleton.bones.push(_this);
  79773. _this.setParent(parentBone, false);
  79774. if (baseMatrix || localMatrix) {
  79775. _this._updateDifferenceMatrix();
  79776. }
  79777. return _this;
  79778. }
  79779. Object.defineProperty(Bone.prototype, "_matrix", {
  79780. /** @hidden */
  79781. get: function () {
  79782. this._compose();
  79783. return this._localMatrix;
  79784. },
  79785. /** @hidden */
  79786. set: function (value) {
  79787. this._localMatrix.copyFrom(value);
  79788. this._needToDecompose = true;
  79789. },
  79790. enumerable: true,
  79791. configurable: true
  79792. });
  79793. // Members
  79794. /**
  79795. * Gets the parent skeleton
  79796. * @returns a skeleton
  79797. */
  79798. Bone.prototype.getSkeleton = function () {
  79799. return this._skeleton;
  79800. };
  79801. /**
  79802. * Gets parent bone
  79803. * @returns a bone or null if the bone is the root of the bone hierarchy
  79804. */
  79805. Bone.prototype.getParent = function () {
  79806. return this._parent;
  79807. };
  79808. /**
  79809. * Sets the parent bone
  79810. * @param parent defines the parent (can be null if the bone is the root)
  79811. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79812. */
  79813. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79814. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79815. if (this._parent === parent) {
  79816. return;
  79817. }
  79818. if (this._parent) {
  79819. var index = this._parent.children.indexOf(this);
  79820. if (index !== -1) {
  79821. this._parent.children.splice(index, 1);
  79822. }
  79823. }
  79824. this._parent = parent;
  79825. if (this._parent) {
  79826. this._parent.children.push(this);
  79827. }
  79828. if (updateDifferenceMatrix) {
  79829. this._updateDifferenceMatrix();
  79830. }
  79831. this.markAsDirty();
  79832. };
  79833. /**
  79834. * Gets the local matrix
  79835. * @returns a matrix
  79836. */
  79837. Bone.prototype.getLocalMatrix = function () {
  79838. this._compose();
  79839. return this._localMatrix;
  79840. };
  79841. /**
  79842. * Gets the base matrix (initial matrix which remains unchanged)
  79843. * @returns a matrix
  79844. */
  79845. Bone.prototype.getBaseMatrix = function () {
  79846. return this._baseMatrix;
  79847. };
  79848. /**
  79849. * Gets the rest pose matrix
  79850. * @returns a matrix
  79851. */
  79852. Bone.prototype.getRestPose = function () {
  79853. return this._restPose;
  79854. };
  79855. /**
  79856. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79857. */
  79858. Bone.prototype.getWorldMatrix = function () {
  79859. return this._worldTransform;
  79860. };
  79861. /**
  79862. * Sets the local matrix to rest pose matrix
  79863. */
  79864. Bone.prototype.returnToRest = function () {
  79865. this.updateMatrix(this._restPose.clone());
  79866. };
  79867. /**
  79868. * Gets the inverse of the absolute transform matrix.
  79869. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79870. * @returns a matrix
  79871. */
  79872. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79873. return this._invertedAbsoluteTransform;
  79874. };
  79875. /**
  79876. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79877. * @returns a matrix
  79878. */
  79879. Bone.prototype.getAbsoluteTransform = function () {
  79880. return this._absoluteTransform;
  79881. };
  79882. Object.defineProperty(Bone.prototype, "position", {
  79883. // Properties (matches AbstractMesh properties)
  79884. /** Gets or sets current position (in local space) */
  79885. get: function () {
  79886. this._decompose();
  79887. return this._localPosition;
  79888. },
  79889. set: function (newPosition) {
  79890. this._decompose();
  79891. this._localPosition.copyFrom(newPosition);
  79892. this._markAsDirtyAndCompose();
  79893. },
  79894. enumerable: true,
  79895. configurable: true
  79896. });
  79897. Object.defineProperty(Bone.prototype, "rotation", {
  79898. /** Gets or sets current rotation (in local space) */
  79899. get: function () {
  79900. return this.getRotation();
  79901. },
  79902. set: function (newRotation) {
  79903. this.setRotation(newRotation);
  79904. },
  79905. enumerable: true,
  79906. configurable: true
  79907. });
  79908. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79909. /** Gets or sets current rotation quaternion (in local space) */
  79910. get: function () {
  79911. this._decompose();
  79912. return this._localRotation;
  79913. },
  79914. set: function (newRotation) {
  79915. this.setRotationQuaternion(newRotation);
  79916. },
  79917. enumerable: true,
  79918. configurable: true
  79919. });
  79920. Object.defineProperty(Bone.prototype, "scaling", {
  79921. /** Gets or sets current scaling (in local space) */
  79922. get: function () {
  79923. return this.getScale();
  79924. },
  79925. set: function (newScaling) {
  79926. this.setScale(newScaling);
  79927. },
  79928. enumerable: true,
  79929. configurable: true
  79930. });
  79931. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79932. /**
  79933. * Gets the animation properties override
  79934. */
  79935. get: function () {
  79936. return this._skeleton.animationPropertiesOverride;
  79937. },
  79938. enumerable: true,
  79939. configurable: true
  79940. });
  79941. // Methods
  79942. Bone.prototype._decompose = function () {
  79943. if (!this._needToDecompose) {
  79944. return;
  79945. }
  79946. this._needToDecompose = false;
  79947. if (!this._localScaling) {
  79948. this._localScaling = BABYLON.Vector3.Zero();
  79949. this._localRotation = BABYLON.Quaternion.Zero();
  79950. this._localPosition = BABYLON.Vector3.Zero();
  79951. }
  79952. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79953. };
  79954. Bone.prototype._compose = function () {
  79955. if (!this._needToCompose) {
  79956. return;
  79957. }
  79958. this._needToCompose = false;
  79959. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79960. };
  79961. /**
  79962. * Update the base and local matrices
  79963. * @param matrix defines the new base or local matrix
  79964. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79965. * @param updateLocalMatrix defines if the local matrix should be updated
  79966. */
  79967. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79968. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79969. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79970. this._baseMatrix.copyFrom(matrix);
  79971. if (updateDifferenceMatrix) {
  79972. this._updateDifferenceMatrix();
  79973. }
  79974. if (updateLocalMatrix) {
  79975. this._localMatrix.copyFrom(matrix);
  79976. this._markAsDirtyAndDecompose();
  79977. }
  79978. else {
  79979. this.markAsDirty();
  79980. }
  79981. };
  79982. /** @hidden */
  79983. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79984. if (updateChildren === void 0) { updateChildren = true; }
  79985. if (!rootMatrix) {
  79986. rootMatrix = this._baseMatrix;
  79987. }
  79988. if (this._parent) {
  79989. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79990. }
  79991. else {
  79992. this._absoluteTransform.copyFrom(rootMatrix);
  79993. }
  79994. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79995. if (updateChildren) {
  79996. for (var index = 0; index < this.children.length; index++) {
  79997. this.children[index]._updateDifferenceMatrix();
  79998. }
  79999. }
  80000. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  80001. };
  80002. /**
  80003. * Flag the bone as dirty (Forcing it to update everything)
  80004. */
  80005. Bone.prototype.markAsDirty = function () {
  80006. this._currentRenderId++;
  80007. this._childRenderId++;
  80008. this._skeleton._markAsDirty();
  80009. };
  80010. Bone.prototype._markAsDirtyAndCompose = function () {
  80011. this.markAsDirty();
  80012. this._needToCompose = true;
  80013. };
  80014. Bone.prototype._markAsDirtyAndDecompose = function () {
  80015. this.markAsDirty();
  80016. this._needToDecompose = true;
  80017. };
  80018. /**
  80019. * Copy an animation range from another bone
  80020. * @param source defines the source bone
  80021. * @param rangeName defines the range name to copy
  80022. * @param frameOffset defines the frame offset
  80023. * @param rescaleAsRequired defines if rescaling must be applied if required
  80024. * @param skelDimensionsRatio defines the scaling ratio
  80025. * @returns true if operation was successful
  80026. */
  80027. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  80028. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80029. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  80030. // all animation may be coming from a library skeleton, so may need to create animation
  80031. if (this.animations.length === 0) {
  80032. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  80033. this.animations[0].setKeys([]);
  80034. }
  80035. // get animation info / verify there is such a range from the source bone
  80036. var sourceRange = source.animations[0].getRange(rangeName);
  80037. if (!sourceRange) {
  80038. return false;
  80039. }
  80040. var from = sourceRange.from;
  80041. var to = sourceRange.to;
  80042. var sourceKeys = source.animations[0].getKeys();
  80043. // rescaling prep
  80044. var sourceBoneLength = source.length;
  80045. var sourceParent = source.getParent();
  80046. var parent = this.getParent();
  80047. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  80048. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  80049. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  80050. var destKeys = this.animations[0].getKeys();
  80051. // loop vars declaration
  80052. var orig;
  80053. var origTranslation;
  80054. var mat;
  80055. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  80056. orig = sourceKeys[key];
  80057. if (orig.frame >= from && orig.frame <= to) {
  80058. if (rescaleAsRequired) {
  80059. mat = orig.value.clone();
  80060. // scale based on parent ratio, when bone has parent
  80061. if (parentScalingReqd) {
  80062. origTranslation = mat.getTranslation();
  80063. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  80064. // scale based on skeleton dimension ratio when root bone, and value is passed
  80065. }
  80066. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  80067. origTranslation = mat.getTranslation();
  80068. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  80069. // use original when root bone, and no data for skelDimensionsRatio
  80070. }
  80071. else {
  80072. mat = orig.value;
  80073. }
  80074. }
  80075. else {
  80076. mat = orig.value;
  80077. }
  80078. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  80079. }
  80080. }
  80081. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  80082. return true;
  80083. };
  80084. /**
  80085. * Translate the bone in local or world space
  80086. * @param vec The amount to translate the bone
  80087. * @param space The space that the translation is in
  80088. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80089. */
  80090. Bone.prototype.translate = function (vec, space, mesh) {
  80091. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80092. var lm = this.getLocalMatrix();
  80093. if (space == BABYLON.Space.LOCAL) {
  80094. lm.m[12] += vec.x;
  80095. lm.m[13] += vec.y;
  80096. lm.m[14] += vec.z;
  80097. }
  80098. else {
  80099. var wm = null;
  80100. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80101. if (mesh) {
  80102. wm = mesh.getWorldMatrix();
  80103. }
  80104. this._skeleton.computeAbsoluteTransforms();
  80105. var tmat = Bone._tmpMats[0];
  80106. var tvec = Bone._tmpVecs[0];
  80107. if (this._parent) {
  80108. if (mesh && wm) {
  80109. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80110. tmat.multiplyToRef(wm, tmat);
  80111. }
  80112. else {
  80113. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80114. }
  80115. }
  80116. tmat.m[12] = 0;
  80117. tmat.m[13] = 0;
  80118. tmat.m[14] = 0;
  80119. tmat.invert();
  80120. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  80121. lm.m[12] += tvec.x;
  80122. lm.m[13] += tvec.y;
  80123. lm.m[14] += tvec.z;
  80124. }
  80125. this._markAsDirtyAndDecompose();
  80126. };
  80127. /**
  80128. * Set the postion of the bone in local or world space
  80129. * @param position The position to set the bone
  80130. * @param space The space that the position is in
  80131. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80132. */
  80133. Bone.prototype.setPosition = function (position, space, mesh) {
  80134. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80135. var lm = this.getLocalMatrix();
  80136. if (space == BABYLON.Space.LOCAL) {
  80137. lm.m[12] = position.x;
  80138. lm.m[13] = position.y;
  80139. lm.m[14] = position.z;
  80140. }
  80141. else {
  80142. var wm = null;
  80143. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80144. if (mesh) {
  80145. wm = mesh.getWorldMatrix();
  80146. }
  80147. this._skeleton.computeAbsoluteTransforms();
  80148. var tmat = Bone._tmpMats[0];
  80149. var vec = Bone._tmpVecs[0];
  80150. if (this._parent) {
  80151. if (mesh && wm) {
  80152. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80153. tmat.multiplyToRef(wm, tmat);
  80154. }
  80155. else {
  80156. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80157. }
  80158. }
  80159. tmat.invert();
  80160. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  80161. lm.m[12] = vec.x;
  80162. lm.m[13] = vec.y;
  80163. lm.m[14] = vec.z;
  80164. }
  80165. this._markAsDirtyAndDecompose();
  80166. };
  80167. /**
  80168. * Set the absolute position of the bone (world space)
  80169. * @param position The position to set the bone
  80170. * @param mesh The mesh that this bone is attached to
  80171. */
  80172. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  80173. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  80174. };
  80175. /**
  80176. * Scale the bone on the x, y and z axes (in local space)
  80177. * @param x The amount to scale the bone on the x axis
  80178. * @param y The amount to scale the bone on the y axis
  80179. * @param z The amount to scale the bone on the z axis
  80180. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  80181. */
  80182. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  80183. if (scaleChildren === void 0) { scaleChildren = false; }
  80184. var locMat = this.getLocalMatrix();
  80185. // Apply new scaling on top of current local matrix
  80186. var scaleMat = Bone._tmpMats[0];
  80187. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  80188. scaleMat.multiplyToRef(locMat, locMat);
  80189. // Invert scaling matrix and apply the inverse to all children
  80190. scaleMat.invert();
  80191. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  80192. var child = _a[_i];
  80193. var cm = child.getLocalMatrix();
  80194. cm.multiplyToRef(scaleMat, cm);
  80195. cm.m[12] *= x;
  80196. cm.m[13] *= y;
  80197. cm.m[14] *= z;
  80198. child._markAsDirtyAndDecompose();
  80199. }
  80200. this._markAsDirtyAndDecompose();
  80201. if (scaleChildren) {
  80202. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  80203. var child = _c[_b];
  80204. child.scale(x, y, z, scaleChildren);
  80205. }
  80206. }
  80207. };
  80208. /**
  80209. * Set the bone scaling in local space
  80210. * @param scale defines the scaling vector
  80211. */
  80212. Bone.prototype.setScale = function (scale) {
  80213. this._decompose();
  80214. this._localScaling.copyFrom(scale);
  80215. this._markAsDirtyAndCompose();
  80216. };
  80217. /**
  80218. * Gets the current scaling in local space
  80219. * @returns the current scaling vector
  80220. */
  80221. Bone.prototype.getScale = function () {
  80222. this._decompose();
  80223. return this._localScaling;
  80224. };
  80225. /**
  80226. * Gets the current scaling in local space and stores it in a target vector
  80227. * @param result defines the target vector
  80228. */
  80229. Bone.prototype.getScaleToRef = function (result) {
  80230. this._decompose();
  80231. result.copyFrom(this._localScaling);
  80232. };
  80233. /**
  80234. * Set the yaw, pitch, and roll of the bone in local or world space
  80235. * @param yaw The rotation of the bone on the y axis
  80236. * @param pitch The rotation of the bone on the x axis
  80237. * @param roll The rotation of the bone on the z axis
  80238. * @param space The space that the axes of rotation are in
  80239. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80240. */
  80241. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  80242. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80243. if (space === BABYLON.Space.LOCAL) {
  80244. var quat = Bone._tmpQuat;
  80245. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  80246. this.setRotationQuaternion(quat, space, mesh);
  80247. return;
  80248. }
  80249. var rotMatInv = Bone._tmpMats[0];
  80250. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80251. return;
  80252. }
  80253. var rotMat = Bone._tmpMats[1];
  80254. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  80255. rotMatInv.multiplyToRef(rotMat, rotMat);
  80256. this._rotateWithMatrix(rotMat, space, mesh);
  80257. };
  80258. /**
  80259. * Add a rotation to the bone on an axis in local or world space
  80260. * @param axis The axis to rotate the bone on
  80261. * @param amount The amount to rotate the bone
  80262. * @param space The space that the axis is in
  80263. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80264. */
  80265. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80266. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80267. var rmat = Bone._tmpMats[0];
  80268. rmat.m[12] = 0;
  80269. rmat.m[13] = 0;
  80270. rmat.m[14] = 0;
  80271. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80272. this._rotateWithMatrix(rmat, space, mesh);
  80273. };
  80274. /**
  80275. * Set the rotation of the bone to a particular axis angle in local or world space
  80276. * @param axis The axis to rotate the bone on
  80277. * @param angle The angle that the bone should be rotated to
  80278. * @param space The space that the axis is in
  80279. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80280. */
  80281. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80282. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80283. if (space === BABYLON.Space.LOCAL) {
  80284. var quat = Bone._tmpQuat;
  80285. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80286. this.setRotationQuaternion(quat, space, mesh);
  80287. return;
  80288. }
  80289. var rotMatInv = Bone._tmpMats[0];
  80290. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80291. return;
  80292. }
  80293. var rotMat = Bone._tmpMats[1];
  80294. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80295. rotMatInv.multiplyToRef(rotMat, rotMat);
  80296. this._rotateWithMatrix(rotMat, space, mesh);
  80297. };
  80298. /**
  80299. * Set the euler rotation of the bone in local of world space
  80300. * @param rotation The euler rotation that the bone should be set to
  80301. * @param space The space that the rotation is in
  80302. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80303. */
  80304. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80305. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80306. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80307. };
  80308. /**
  80309. * Set the quaternion rotation of the bone in local of world space
  80310. * @param quat The quaternion rotation that the bone should be set to
  80311. * @param space The space that the rotation is in
  80312. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80313. */
  80314. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80315. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80316. if (space === BABYLON.Space.LOCAL) {
  80317. this._decompose();
  80318. this._localRotation.copyFrom(quat);
  80319. this._markAsDirtyAndCompose();
  80320. return;
  80321. }
  80322. var rotMatInv = Bone._tmpMats[0];
  80323. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80324. return;
  80325. }
  80326. var rotMat = Bone._tmpMats[1];
  80327. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80328. rotMatInv.multiplyToRef(rotMat, rotMat);
  80329. this._rotateWithMatrix(rotMat, space, mesh);
  80330. };
  80331. /**
  80332. * Set the rotation matrix of the bone in local of world space
  80333. * @param rotMat The rotation matrix that the bone should be set to
  80334. * @param space The space that the rotation is in
  80335. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80336. */
  80337. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80338. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80339. if (space === BABYLON.Space.LOCAL) {
  80340. var quat = Bone._tmpQuat;
  80341. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80342. this.setRotationQuaternion(quat, space, mesh);
  80343. return;
  80344. }
  80345. var rotMatInv = Bone._tmpMats[0];
  80346. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80347. return;
  80348. }
  80349. var rotMat2 = Bone._tmpMats[1];
  80350. rotMat2.copyFrom(rotMat);
  80351. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80352. this._rotateWithMatrix(rotMat2, space, mesh);
  80353. };
  80354. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80355. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80356. var lmat = this.getLocalMatrix();
  80357. var lx = lmat.m[12];
  80358. var ly = lmat.m[13];
  80359. var lz = lmat.m[14];
  80360. var parent = this.getParent();
  80361. var parentScale = Bone._tmpMats[3];
  80362. var parentScaleInv = Bone._tmpMats[4];
  80363. if (parent && space == BABYLON.Space.WORLD) {
  80364. if (mesh) {
  80365. parentScale.copyFrom(mesh.getWorldMatrix());
  80366. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80367. }
  80368. else {
  80369. parentScale.copyFrom(parent.getAbsoluteTransform());
  80370. }
  80371. parentScaleInv.copyFrom(parentScale);
  80372. parentScaleInv.invert();
  80373. lmat.multiplyToRef(parentScale, lmat);
  80374. lmat.multiplyToRef(rmat, lmat);
  80375. lmat.multiplyToRef(parentScaleInv, lmat);
  80376. }
  80377. else {
  80378. if (space == BABYLON.Space.WORLD && mesh) {
  80379. parentScale.copyFrom(mesh.getWorldMatrix());
  80380. parentScaleInv.copyFrom(parentScale);
  80381. parentScaleInv.invert();
  80382. lmat.multiplyToRef(parentScale, lmat);
  80383. lmat.multiplyToRef(rmat, lmat);
  80384. lmat.multiplyToRef(parentScaleInv, lmat);
  80385. }
  80386. else {
  80387. lmat.multiplyToRef(rmat, lmat);
  80388. }
  80389. }
  80390. lmat.m[12] = lx;
  80391. lmat.m[13] = ly;
  80392. lmat.m[14] = lz;
  80393. this.computeAbsoluteTransforms();
  80394. this._markAsDirtyAndDecompose();
  80395. };
  80396. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80397. var scaleMatrix = Bone._tmpMats[2];
  80398. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80399. if (mesh) {
  80400. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80401. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80402. }
  80403. rotMatInv.invert();
  80404. if (isNaN(rotMatInv.m[0])) {
  80405. // Matrix failed to invert.
  80406. // This can happen if scale is zero for example.
  80407. return false;
  80408. }
  80409. scaleMatrix.m[0] *= this._scalingDeterminant;
  80410. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80411. return true;
  80412. };
  80413. /**
  80414. * Get the position of the bone in local or world space
  80415. * @param space The space that the returned position is in
  80416. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80417. * @returns The position of the bone
  80418. */
  80419. Bone.prototype.getPosition = function (space, mesh) {
  80420. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80421. if (mesh === void 0) { mesh = null; }
  80422. var pos = BABYLON.Vector3.Zero();
  80423. this.getPositionToRef(space, mesh, pos);
  80424. return pos;
  80425. };
  80426. /**
  80427. * Copy the position of the bone to a vector3 in local or world space
  80428. * @param space The space that the returned position is in
  80429. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80430. * @param result The vector3 to copy the position to
  80431. */
  80432. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80434. if (space == BABYLON.Space.LOCAL) {
  80435. var lm = this.getLocalMatrix();
  80436. result.x = lm.m[12];
  80437. result.y = lm.m[13];
  80438. result.z = lm.m[14];
  80439. }
  80440. else {
  80441. var wm = null;
  80442. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80443. if (mesh) {
  80444. wm = mesh.getWorldMatrix();
  80445. }
  80446. this._skeleton.computeAbsoluteTransforms();
  80447. var tmat = Bone._tmpMats[0];
  80448. if (mesh && wm) {
  80449. tmat.copyFrom(this.getAbsoluteTransform());
  80450. tmat.multiplyToRef(wm, tmat);
  80451. }
  80452. else {
  80453. tmat = this.getAbsoluteTransform();
  80454. }
  80455. result.x = tmat.m[12];
  80456. result.y = tmat.m[13];
  80457. result.z = tmat.m[14];
  80458. }
  80459. };
  80460. /**
  80461. * Get the absolute position of the bone (world space)
  80462. * @param mesh The mesh that this bone is attached to
  80463. * @returns The absolute position of the bone
  80464. */
  80465. Bone.prototype.getAbsolutePosition = function (mesh) {
  80466. if (mesh === void 0) { mesh = null; }
  80467. var pos = BABYLON.Vector3.Zero();
  80468. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80469. return pos;
  80470. };
  80471. /**
  80472. * Copy the absolute position of the bone (world space) to the result param
  80473. * @param mesh The mesh that this bone is attached to
  80474. * @param result The vector3 to copy the absolute position to
  80475. */
  80476. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80477. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80478. };
  80479. /**
  80480. * Compute the absolute transforms of this bone and its children
  80481. */
  80482. Bone.prototype.computeAbsoluteTransforms = function () {
  80483. this._compose();
  80484. if (this._parent) {
  80485. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80486. }
  80487. else {
  80488. this._absoluteTransform.copyFrom(this._localMatrix);
  80489. var poseMatrix = this._skeleton.getPoseMatrix();
  80490. if (poseMatrix) {
  80491. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80492. }
  80493. }
  80494. var children = this.children;
  80495. var len = children.length;
  80496. for (var i = 0; i < len; i++) {
  80497. children[i].computeAbsoluteTransforms();
  80498. }
  80499. };
  80500. /**
  80501. * Get the world direction from an axis that is in the local space of the bone
  80502. * @param localAxis The local direction that is used to compute the world direction
  80503. * @param mesh The mesh that this bone is attached to
  80504. * @returns The world direction
  80505. */
  80506. Bone.prototype.getDirection = function (localAxis, mesh) {
  80507. if (mesh === void 0) { mesh = null; }
  80508. var result = BABYLON.Vector3.Zero();
  80509. this.getDirectionToRef(localAxis, mesh, result);
  80510. return result;
  80511. };
  80512. /**
  80513. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80514. * @param localAxis The local direction that is used to compute the world direction
  80515. * @param mesh The mesh that this bone is attached to
  80516. * @param result The vector3 that the world direction will be copied to
  80517. */
  80518. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80519. if (mesh === void 0) { mesh = null; }
  80520. var wm = null;
  80521. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80522. if (mesh) {
  80523. wm = mesh.getWorldMatrix();
  80524. }
  80525. this._skeleton.computeAbsoluteTransforms();
  80526. var mat = Bone._tmpMats[0];
  80527. mat.copyFrom(this.getAbsoluteTransform());
  80528. if (mesh && wm) {
  80529. mat.multiplyToRef(wm, mat);
  80530. }
  80531. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80532. result.normalize();
  80533. };
  80534. /**
  80535. * Get the euler rotation of the bone in local or world space
  80536. * @param space The space that the rotation should be in
  80537. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80538. * @returns The euler rotation
  80539. */
  80540. Bone.prototype.getRotation = function (space, mesh) {
  80541. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80542. if (mesh === void 0) { mesh = null; }
  80543. var result = BABYLON.Vector3.Zero();
  80544. this.getRotationToRef(space, mesh, result);
  80545. return result;
  80546. };
  80547. /**
  80548. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80549. * @param space The space that the rotation should be in
  80550. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80551. * @param result The vector3 that the rotation should be copied to
  80552. */
  80553. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80554. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80555. if (mesh === void 0) { mesh = null; }
  80556. var quat = Bone._tmpQuat;
  80557. this.getRotationQuaternionToRef(space, mesh, quat);
  80558. quat.toEulerAnglesToRef(result);
  80559. };
  80560. /**
  80561. * Get the quaternion rotation of the bone in either local or world space
  80562. * @param space The space that the rotation should be in
  80563. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80564. * @returns The quaternion rotation
  80565. */
  80566. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80567. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80568. if (mesh === void 0) { mesh = null; }
  80569. var result = BABYLON.Quaternion.Identity();
  80570. this.getRotationQuaternionToRef(space, mesh, result);
  80571. return result;
  80572. };
  80573. /**
  80574. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80575. * @param space The space that the rotation should be in
  80576. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80577. * @param result The quaternion that the rotation should be copied to
  80578. */
  80579. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80581. if (mesh === void 0) { mesh = null; }
  80582. if (space == BABYLON.Space.LOCAL) {
  80583. this._decompose();
  80584. result.copyFrom(this._localRotation);
  80585. }
  80586. else {
  80587. var mat = Bone._tmpMats[0];
  80588. var amat = this.getAbsoluteTransform();
  80589. if (mesh) {
  80590. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80591. }
  80592. else {
  80593. mat.copyFrom(amat);
  80594. }
  80595. mat.m[0] *= this._scalingDeterminant;
  80596. mat.m[1] *= this._scalingDeterminant;
  80597. mat.m[2] *= this._scalingDeterminant;
  80598. mat.decompose(undefined, result, undefined);
  80599. }
  80600. };
  80601. /**
  80602. * Get the rotation matrix of the bone in local or world space
  80603. * @param space The space that the rotation should be in
  80604. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80605. * @returns The rotation matrix
  80606. */
  80607. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80608. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80609. var result = BABYLON.Matrix.Identity();
  80610. this.getRotationMatrixToRef(space, mesh, result);
  80611. return result;
  80612. };
  80613. /**
  80614. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80615. * @param space The space that the rotation should be in
  80616. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80617. * @param result The quaternion that the rotation should be copied to
  80618. */
  80619. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80621. if (space == BABYLON.Space.LOCAL) {
  80622. this.getLocalMatrix().getRotationMatrixToRef(result);
  80623. }
  80624. else {
  80625. var mat = Bone._tmpMats[0];
  80626. var amat = this.getAbsoluteTransform();
  80627. if (mesh) {
  80628. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80629. }
  80630. else {
  80631. mat.copyFrom(amat);
  80632. }
  80633. mat.m[0] *= this._scalingDeterminant;
  80634. mat.m[1] *= this._scalingDeterminant;
  80635. mat.m[2] *= this._scalingDeterminant;
  80636. mat.getRotationMatrixToRef(result);
  80637. }
  80638. };
  80639. /**
  80640. * Get the world position of a point that is in the local space of the bone
  80641. * @param position The local position
  80642. * @param mesh The mesh that this bone is attached to
  80643. * @returns The world position
  80644. */
  80645. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80646. if (mesh === void 0) { mesh = null; }
  80647. var result = BABYLON.Vector3.Zero();
  80648. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80649. return result;
  80650. };
  80651. /**
  80652. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80653. * @param position The local position
  80654. * @param mesh The mesh that this bone is attached to
  80655. * @param result The vector3 that the world position should be copied to
  80656. */
  80657. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80658. if (mesh === void 0) { mesh = null; }
  80659. var wm = null;
  80660. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80661. if (mesh) {
  80662. wm = mesh.getWorldMatrix();
  80663. }
  80664. this._skeleton.computeAbsoluteTransforms();
  80665. var tmat = Bone._tmpMats[0];
  80666. if (mesh && wm) {
  80667. tmat.copyFrom(this.getAbsoluteTransform());
  80668. tmat.multiplyToRef(wm, tmat);
  80669. }
  80670. else {
  80671. tmat = this.getAbsoluteTransform();
  80672. }
  80673. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80674. };
  80675. /**
  80676. * Get the local position of a point that is in world space
  80677. * @param position The world position
  80678. * @param mesh The mesh that this bone is attached to
  80679. * @returns The local position
  80680. */
  80681. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80682. if (mesh === void 0) { mesh = null; }
  80683. var result = BABYLON.Vector3.Zero();
  80684. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80685. return result;
  80686. };
  80687. /**
  80688. * Get the local position of a point that is in world space and copy it to the result param
  80689. * @param position The world position
  80690. * @param mesh The mesh that this bone is attached to
  80691. * @param result The vector3 that the local position should be copied to
  80692. */
  80693. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80694. if (mesh === void 0) { mesh = null; }
  80695. var wm = null;
  80696. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80697. if (mesh) {
  80698. wm = mesh.getWorldMatrix();
  80699. }
  80700. this._skeleton.computeAbsoluteTransforms();
  80701. var tmat = Bone._tmpMats[0];
  80702. tmat.copyFrom(this.getAbsoluteTransform());
  80703. if (mesh && wm) {
  80704. tmat.multiplyToRef(wm, tmat);
  80705. }
  80706. tmat.invert();
  80707. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80708. };
  80709. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80710. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80711. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80712. return Bone;
  80713. }(BABYLON.Node));
  80714. BABYLON.Bone = Bone;
  80715. })(BABYLON || (BABYLON = {}));
  80716. //# sourceMappingURL=babylon.bone.js.map
  80717. var BABYLON;
  80718. (function (BABYLON) {
  80719. /**
  80720. * Class used to apply inverse kinematics to bones
  80721. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80722. */
  80723. var BoneIKController = /** @class */ (function () {
  80724. /**
  80725. * Creates a new BoneIKController
  80726. * @param mesh defines the mesh to control
  80727. * @param bone defines the bone to control
  80728. * @param options defines options to set up the controller
  80729. */
  80730. function BoneIKController(mesh, bone, options) {
  80731. /**
  80732. * Gets or sets the target position
  80733. */
  80734. this.targetPosition = BABYLON.Vector3.Zero();
  80735. /**
  80736. * Gets or sets the pole target position
  80737. */
  80738. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80739. /**
  80740. * Gets or sets the pole target local offset
  80741. */
  80742. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80743. /**
  80744. * Gets or sets the pole angle
  80745. */
  80746. this.poleAngle = 0;
  80747. /**
  80748. * 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)
  80749. */
  80750. this.slerpAmount = 1;
  80751. this._bone1Quat = BABYLON.Quaternion.Identity();
  80752. this._bone1Mat = BABYLON.Matrix.Identity();
  80753. this._bone2Ang = Math.PI;
  80754. this._maxAngle = Math.PI;
  80755. this._rightHandedSystem = false;
  80756. this._bendAxis = BABYLON.Vector3.Right();
  80757. this._slerping = false;
  80758. this._adjustRoll = 0;
  80759. this._bone2 = bone;
  80760. this._bone1 = bone.getParent();
  80761. if (!this._bone1) {
  80762. return;
  80763. }
  80764. this.mesh = mesh;
  80765. var bonePos = bone.getPosition();
  80766. if (bone.getAbsoluteTransform().determinant() > 0) {
  80767. this._rightHandedSystem = true;
  80768. this._bendAxis.x = 0;
  80769. this._bendAxis.y = 0;
  80770. this._bendAxis.z = -1;
  80771. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80772. this._adjustRoll = Math.PI * .5;
  80773. this._bendAxis.z = 1;
  80774. }
  80775. }
  80776. if (this._bone1.length) {
  80777. var boneScale1 = this._bone1.getScale();
  80778. var boneScale2 = this._bone2.getScale();
  80779. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80780. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80781. }
  80782. else if (this._bone1.children[0]) {
  80783. mesh.computeWorldMatrix(true);
  80784. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80785. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80786. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80787. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80788. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80789. }
  80790. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80791. this.maxAngle = Math.PI;
  80792. if (options) {
  80793. if (options.targetMesh) {
  80794. this.targetMesh = options.targetMesh;
  80795. this.targetMesh.computeWorldMatrix(true);
  80796. }
  80797. if (options.poleTargetMesh) {
  80798. this.poleTargetMesh = options.poleTargetMesh;
  80799. this.poleTargetMesh.computeWorldMatrix(true);
  80800. }
  80801. else if (options.poleTargetBone) {
  80802. this.poleTargetBone = options.poleTargetBone;
  80803. }
  80804. else if (this._bone1.getParent()) {
  80805. this.poleTargetBone = this._bone1.getParent();
  80806. }
  80807. if (options.poleTargetLocalOffset) {
  80808. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80809. }
  80810. if (options.poleAngle) {
  80811. this.poleAngle = options.poleAngle;
  80812. }
  80813. if (options.bendAxis) {
  80814. this._bendAxis.copyFrom(options.bendAxis);
  80815. }
  80816. if (options.maxAngle) {
  80817. this.maxAngle = options.maxAngle;
  80818. }
  80819. if (options.slerpAmount) {
  80820. this.slerpAmount = options.slerpAmount;
  80821. }
  80822. }
  80823. }
  80824. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80825. /**
  80826. * Gets or sets maximum allowed angle
  80827. */
  80828. get: function () {
  80829. return this._maxAngle;
  80830. },
  80831. set: function (value) {
  80832. this._setMaxAngle(value);
  80833. },
  80834. enumerable: true,
  80835. configurable: true
  80836. });
  80837. BoneIKController.prototype._setMaxAngle = function (ang) {
  80838. if (ang < 0) {
  80839. ang = 0;
  80840. }
  80841. if (ang > Math.PI || ang == undefined) {
  80842. ang = Math.PI;
  80843. }
  80844. this._maxAngle = ang;
  80845. var a = this._bone1Length;
  80846. var b = this._bone2Length;
  80847. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80848. };
  80849. /**
  80850. * Force the controller to update the bones
  80851. */
  80852. BoneIKController.prototype.update = function () {
  80853. var bone1 = this._bone1;
  80854. if (!bone1) {
  80855. return;
  80856. }
  80857. var target = this.targetPosition;
  80858. var poleTarget = this.poleTargetPosition;
  80859. var mat1 = BoneIKController._tmpMats[0];
  80860. var mat2 = BoneIKController._tmpMats[1];
  80861. if (this.targetMesh) {
  80862. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80863. }
  80864. if (this.poleTargetBone) {
  80865. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80866. }
  80867. else if (this.poleTargetMesh) {
  80868. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80869. }
  80870. var bonePos = BoneIKController._tmpVecs[0];
  80871. var zaxis = BoneIKController._tmpVecs[1];
  80872. var xaxis = BoneIKController._tmpVecs[2];
  80873. var yaxis = BoneIKController._tmpVecs[3];
  80874. var upAxis = BoneIKController._tmpVecs[4];
  80875. var _tmpQuat = BoneIKController._tmpQuat;
  80876. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80877. poleTarget.subtractToRef(bonePos, upAxis);
  80878. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80879. upAxis.y = 1;
  80880. }
  80881. else {
  80882. upAxis.normalize();
  80883. }
  80884. target.subtractToRef(bonePos, yaxis);
  80885. yaxis.normalize();
  80886. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80887. zaxis.normalize();
  80888. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80889. xaxis.normalize();
  80890. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80891. var a = this._bone1Length;
  80892. var b = this._bone2Length;
  80893. var c = BABYLON.Vector3.Distance(bonePos, target);
  80894. if (this._maxReach > 0) {
  80895. c = Math.min(this._maxReach, c);
  80896. }
  80897. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80898. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80899. if (acosa > 1) {
  80900. acosa = 1;
  80901. }
  80902. if (acosb > 1) {
  80903. acosb = 1;
  80904. }
  80905. if (acosa < -1) {
  80906. acosa = -1;
  80907. }
  80908. if (acosb < -1) {
  80909. acosb = -1;
  80910. }
  80911. var angA = Math.acos(acosa);
  80912. var angB = Math.acos(acosb);
  80913. var angC = -angA - angB;
  80914. if (this._rightHandedSystem) {
  80915. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80916. mat2.multiplyToRef(mat1, mat1);
  80917. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80918. mat2.multiplyToRef(mat1, mat1);
  80919. }
  80920. else {
  80921. var _tmpVec = BoneIKController._tmpVecs[5];
  80922. _tmpVec.copyFrom(this._bendAxis);
  80923. _tmpVec.x *= -1;
  80924. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80925. mat2.multiplyToRef(mat1, mat1);
  80926. }
  80927. if (this.poleAngle) {
  80928. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80929. mat1.multiplyToRef(mat2, mat1);
  80930. }
  80931. if (this._bone1) {
  80932. if (this.slerpAmount < 1) {
  80933. if (!this._slerping) {
  80934. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80935. }
  80936. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80937. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80938. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80939. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80940. this._slerping = true;
  80941. }
  80942. else {
  80943. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80944. this._bone1Mat.copyFrom(mat1);
  80945. this._slerping = false;
  80946. }
  80947. }
  80948. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80949. this._bone2Ang = angC;
  80950. };
  80951. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80952. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80953. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80954. return BoneIKController;
  80955. }());
  80956. BABYLON.BoneIKController = BoneIKController;
  80957. })(BABYLON || (BABYLON = {}));
  80958. //# sourceMappingURL=babylon.boneIKController.js.map
  80959. var BABYLON;
  80960. (function (BABYLON) {
  80961. /**
  80962. * Class used to make a bone look toward a point in space
  80963. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80964. */
  80965. var BoneLookController = /** @class */ (function () {
  80966. /**
  80967. * Create a BoneLookController
  80968. * @param mesh the mesh that the bone belongs to
  80969. * @param bone the bone that will be looking to the target
  80970. * @param target the target Vector3 to look at
  80971. * @param settings optional settings:
  80972. * * maxYaw: the maximum angle the bone will yaw to
  80973. * * minYaw: the minimum angle the bone will yaw to
  80974. * * maxPitch: the maximum angle the bone will pitch to
  80975. * * minPitch: the minimum angle the bone will yaw to
  80976. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80977. * * upAxis: the up axis of the coordinate system
  80978. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80979. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80980. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80981. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80982. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80983. * * adjustRoll: used to make an adjustment to the roll of the bone
  80984. **/
  80985. function BoneLookController(mesh, bone, target, options) {
  80986. /**
  80987. * The up axis of the coordinate system that is used when the bone is rotated
  80988. */
  80989. this.upAxis = BABYLON.Vector3.Up();
  80990. /**
  80991. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80992. */
  80993. this.upAxisSpace = BABYLON.Space.LOCAL;
  80994. /**
  80995. * Used to make an adjustment to the yaw of the bone
  80996. */
  80997. this.adjustYaw = 0;
  80998. /**
  80999. * Used to make an adjustment to the pitch of the bone
  81000. */
  81001. this.adjustPitch = 0;
  81002. /**
  81003. * Used to make an adjustment to the roll of the bone
  81004. */
  81005. this.adjustRoll = 0;
  81006. /**
  81007. * 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)
  81008. */
  81009. this.slerpAmount = 1;
  81010. this._boneQuat = BABYLON.Quaternion.Identity();
  81011. this._slerping = false;
  81012. this._firstFrameSkipped = false;
  81013. this._fowardAxis = BABYLON.Vector3.Forward();
  81014. this.mesh = mesh;
  81015. this.bone = bone;
  81016. this.target = target;
  81017. if (options) {
  81018. if (options.adjustYaw) {
  81019. this.adjustYaw = options.adjustYaw;
  81020. }
  81021. if (options.adjustPitch) {
  81022. this.adjustPitch = options.adjustPitch;
  81023. }
  81024. if (options.adjustRoll) {
  81025. this.adjustRoll = options.adjustRoll;
  81026. }
  81027. if (options.maxYaw != null) {
  81028. this.maxYaw = options.maxYaw;
  81029. }
  81030. else {
  81031. this.maxYaw = Math.PI;
  81032. }
  81033. if (options.minYaw != null) {
  81034. this.minYaw = options.minYaw;
  81035. }
  81036. else {
  81037. this.minYaw = -Math.PI;
  81038. }
  81039. if (options.maxPitch != null) {
  81040. this.maxPitch = options.maxPitch;
  81041. }
  81042. else {
  81043. this.maxPitch = Math.PI;
  81044. }
  81045. if (options.minPitch != null) {
  81046. this.minPitch = options.minPitch;
  81047. }
  81048. else {
  81049. this.minPitch = -Math.PI;
  81050. }
  81051. if (options.slerpAmount != null) {
  81052. this.slerpAmount = options.slerpAmount;
  81053. }
  81054. if (options.upAxis != null) {
  81055. this.upAxis = options.upAxis;
  81056. }
  81057. if (options.upAxisSpace != null) {
  81058. this.upAxisSpace = options.upAxisSpace;
  81059. }
  81060. if (options.yawAxis != null || options.pitchAxis != null) {
  81061. var newYawAxis = BABYLON.Axis.Y;
  81062. var newPitchAxis = BABYLON.Axis.X;
  81063. if (options.yawAxis != null) {
  81064. newYawAxis = options.yawAxis.clone();
  81065. newYawAxis.normalize();
  81066. }
  81067. if (options.pitchAxis != null) {
  81068. newPitchAxis = options.pitchAxis.clone();
  81069. newPitchAxis.normalize();
  81070. }
  81071. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  81072. this._transformYawPitch = BABYLON.Matrix.Identity();
  81073. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  81074. this._transformYawPitchInv = this._transformYawPitch.clone();
  81075. this._transformYawPitch.invert();
  81076. }
  81077. }
  81078. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  81079. this.upAxisSpace = BABYLON.Space.LOCAL;
  81080. }
  81081. }
  81082. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  81083. /**
  81084. * Gets or sets the minimum yaw angle that the bone can look to
  81085. */
  81086. get: function () {
  81087. return this._minYaw;
  81088. },
  81089. set: function (value) {
  81090. this._minYaw = value;
  81091. this._minYawSin = Math.sin(value);
  81092. this._minYawCos = Math.cos(value);
  81093. if (this._maxYaw != null) {
  81094. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81095. this._yawRange = this._maxYaw - this._minYaw;
  81096. }
  81097. },
  81098. enumerable: true,
  81099. configurable: true
  81100. });
  81101. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  81102. /**
  81103. * Gets or sets the maximum yaw angle that the bone can look to
  81104. */
  81105. get: function () {
  81106. return this._maxYaw;
  81107. },
  81108. set: function (value) {
  81109. this._maxYaw = value;
  81110. this._maxYawSin = Math.sin(value);
  81111. this._maxYawCos = Math.cos(value);
  81112. if (this._minYaw != null) {
  81113. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81114. this._yawRange = this._maxYaw - this._minYaw;
  81115. }
  81116. },
  81117. enumerable: true,
  81118. configurable: true
  81119. });
  81120. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  81121. /**
  81122. * Gets or sets the minimum pitch angle that the bone can look to
  81123. */
  81124. get: function () {
  81125. return this._minPitch;
  81126. },
  81127. set: function (value) {
  81128. this._minPitch = value;
  81129. this._minPitchTan = Math.tan(value);
  81130. },
  81131. enumerable: true,
  81132. configurable: true
  81133. });
  81134. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  81135. /**
  81136. * Gets or sets the maximum pitch angle that the bone can look to
  81137. */
  81138. get: function () {
  81139. return this._maxPitch;
  81140. },
  81141. set: function (value) {
  81142. this._maxPitch = value;
  81143. this._maxPitchTan = Math.tan(value);
  81144. },
  81145. enumerable: true,
  81146. configurable: true
  81147. });
  81148. /**
  81149. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  81150. */
  81151. BoneLookController.prototype.update = function () {
  81152. //skip the first frame when slerping so that the mesh rotation is correct
  81153. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  81154. this._firstFrameSkipped = true;
  81155. return;
  81156. }
  81157. var bone = this.bone;
  81158. var bonePos = BoneLookController._tmpVecs[0];
  81159. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  81160. var target = this.target;
  81161. var _tmpMat1 = BoneLookController._tmpMats[0];
  81162. var _tmpMat2 = BoneLookController._tmpMats[1];
  81163. var mesh = this.mesh;
  81164. var parentBone = bone.getParent();
  81165. var upAxis = BoneLookController._tmpVecs[1];
  81166. upAxis.copyFrom(this.upAxis);
  81167. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  81168. if (this._transformYawPitch) {
  81169. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  81170. }
  81171. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  81172. }
  81173. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  81174. mesh.getDirectionToRef(upAxis, upAxis);
  81175. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  81176. upAxis.normalize();
  81177. }
  81178. }
  81179. var checkYaw = false;
  81180. var checkPitch = false;
  81181. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  81182. checkYaw = true;
  81183. }
  81184. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  81185. checkPitch = true;
  81186. }
  81187. if (checkYaw || checkPitch) {
  81188. var spaceMat = BoneLookController._tmpMats[2];
  81189. var spaceMatInv = BoneLookController._tmpMats[3];
  81190. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  81191. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  81192. }
  81193. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  81194. spaceMat.copyFrom(mesh.getWorldMatrix());
  81195. }
  81196. else {
  81197. var forwardAxis = BoneLookController._tmpVecs[2];
  81198. forwardAxis.copyFrom(this._fowardAxis);
  81199. if (this._transformYawPitch) {
  81200. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  81201. }
  81202. if (parentBone) {
  81203. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  81204. }
  81205. else {
  81206. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  81207. }
  81208. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  81209. rightAxis.normalize();
  81210. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  81211. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  81212. }
  81213. spaceMat.invertToRef(spaceMatInv);
  81214. var xzlen = null;
  81215. if (checkPitch) {
  81216. var localTarget = BoneLookController._tmpVecs[3];
  81217. target.subtractToRef(bonePos, localTarget);
  81218. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81219. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81220. var pitch = Math.atan2(localTarget.y, xzlen);
  81221. var newPitch = pitch;
  81222. if (pitch > this._maxPitch) {
  81223. localTarget.y = this._maxPitchTan * xzlen;
  81224. newPitch = this._maxPitch;
  81225. }
  81226. else if (pitch < this._minPitch) {
  81227. localTarget.y = this._minPitchTan * xzlen;
  81228. newPitch = this._minPitch;
  81229. }
  81230. if (pitch != newPitch) {
  81231. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81232. localTarget.addInPlace(bonePos);
  81233. target = localTarget;
  81234. }
  81235. }
  81236. if (checkYaw) {
  81237. var localTarget = BoneLookController._tmpVecs[4];
  81238. target.subtractToRef(bonePos, localTarget);
  81239. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81240. var yaw = Math.atan2(localTarget.x, localTarget.z);
  81241. var newYaw = yaw;
  81242. if (yaw > this._maxYaw || yaw < this._minYaw) {
  81243. if (xzlen == null) {
  81244. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81245. }
  81246. if (this._yawRange > Math.PI) {
  81247. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  81248. localTarget.z = this._maxYawCos * xzlen;
  81249. localTarget.x = this._maxYawSin * xzlen;
  81250. newYaw = this._maxYaw;
  81251. }
  81252. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  81253. localTarget.z = this._minYawCos * xzlen;
  81254. localTarget.x = this._minYawSin * xzlen;
  81255. newYaw = this._minYaw;
  81256. }
  81257. }
  81258. else {
  81259. if (yaw > this._maxYaw) {
  81260. localTarget.z = this._maxYawCos * xzlen;
  81261. localTarget.x = this._maxYawSin * xzlen;
  81262. newYaw = this._maxYaw;
  81263. }
  81264. else if (yaw < this._minYaw) {
  81265. localTarget.z = this._minYawCos * xzlen;
  81266. localTarget.x = this._minYawSin * xzlen;
  81267. newYaw = this._minYaw;
  81268. }
  81269. }
  81270. }
  81271. if (this._slerping && this._yawRange > Math.PI) {
  81272. //are we going to be crossing into the min/max region?
  81273. var boneFwd = BoneLookController._tmpVecs[8];
  81274. boneFwd.copyFrom(BABYLON.Axis.Z);
  81275. if (this._transformYawPitch) {
  81276. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81277. }
  81278. var boneRotMat = BoneLookController._tmpMats[4];
  81279. this._boneQuat.toRotationMatrix(boneRotMat);
  81280. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81281. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81282. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81283. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81284. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81285. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81286. if (angBtwTar > angBtwMidYaw) {
  81287. if (xzlen == null) {
  81288. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81289. }
  81290. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81291. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81292. if (angBtwMin < angBtwMax) {
  81293. newYaw = boneYaw + Math.PI * .75;
  81294. localTarget.z = Math.cos(newYaw) * xzlen;
  81295. localTarget.x = Math.sin(newYaw) * xzlen;
  81296. }
  81297. else {
  81298. newYaw = boneYaw - Math.PI * .75;
  81299. localTarget.z = Math.cos(newYaw) * xzlen;
  81300. localTarget.x = Math.sin(newYaw) * xzlen;
  81301. }
  81302. }
  81303. }
  81304. if (yaw != newYaw) {
  81305. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81306. localTarget.addInPlace(bonePos);
  81307. target = localTarget;
  81308. }
  81309. }
  81310. }
  81311. var zaxis = BoneLookController._tmpVecs[5];
  81312. var xaxis = BoneLookController._tmpVecs[6];
  81313. var yaxis = BoneLookController._tmpVecs[7];
  81314. var _tmpQuat = BoneLookController._tmpQuat;
  81315. target.subtractToRef(bonePos, zaxis);
  81316. zaxis.normalize();
  81317. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81318. xaxis.normalize();
  81319. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81320. yaxis.normalize();
  81321. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81322. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81323. return;
  81324. }
  81325. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81326. return;
  81327. }
  81328. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81329. return;
  81330. }
  81331. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81332. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81333. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81334. }
  81335. if (this.slerpAmount < 1) {
  81336. if (!this._slerping) {
  81337. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81338. }
  81339. if (this._transformYawPitch) {
  81340. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81341. }
  81342. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81343. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81344. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81345. this._slerping = true;
  81346. }
  81347. else {
  81348. if (this._transformYawPitch) {
  81349. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81350. }
  81351. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81352. this._slerping = false;
  81353. }
  81354. };
  81355. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81356. var angDiff = ang2 - ang1;
  81357. angDiff %= Math.PI * 2;
  81358. if (angDiff > Math.PI) {
  81359. angDiff -= Math.PI * 2;
  81360. }
  81361. else if (angDiff < -Math.PI) {
  81362. angDiff += Math.PI * 2;
  81363. }
  81364. return angDiff;
  81365. };
  81366. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81367. ang1 %= (2 * Math.PI);
  81368. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81369. ang2 %= (2 * Math.PI);
  81370. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81371. var ab = 0;
  81372. if (ang1 < ang2) {
  81373. ab = ang2 - ang1;
  81374. }
  81375. else {
  81376. ab = ang1 - ang2;
  81377. }
  81378. if (ab > Math.PI) {
  81379. ab = Math.PI * 2 - ab;
  81380. }
  81381. return ab;
  81382. };
  81383. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81384. ang %= (2 * Math.PI);
  81385. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81386. ang1 %= (2 * Math.PI);
  81387. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81388. ang2 %= (2 * Math.PI);
  81389. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81390. if (ang1 < ang2) {
  81391. if (ang > ang1 && ang < ang2) {
  81392. return true;
  81393. }
  81394. }
  81395. else {
  81396. if (ang > ang2 && ang < ang1) {
  81397. return true;
  81398. }
  81399. }
  81400. return false;
  81401. };
  81402. 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()];
  81403. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81404. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81405. return BoneLookController;
  81406. }());
  81407. BABYLON.BoneLookController = BoneLookController;
  81408. })(BABYLON || (BABYLON = {}));
  81409. //# sourceMappingURL=babylon.boneLookController.js.map
  81410. var BABYLON;
  81411. (function (BABYLON) {
  81412. /**
  81413. * Class used to handle skinning animations
  81414. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81415. */
  81416. var Skeleton = /** @class */ (function () {
  81417. /**
  81418. * Creates a new skeleton
  81419. * @param name defines the skeleton name
  81420. * @param id defines the skeleton Id
  81421. * @param scene defines the hosting scene
  81422. */
  81423. function Skeleton(
  81424. /** defines the skeleton name */
  81425. name,
  81426. /** defines the skeleton Id */
  81427. id, scene) {
  81428. this.name = name;
  81429. this.id = id;
  81430. /**
  81431. * Gets the list of child bones
  81432. */
  81433. this.bones = new Array();
  81434. /**
  81435. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81436. */
  81437. this.needInitialSkinMatrix = false;
  81438. this._isDirty = true;
  81439. this._meshesWithPoseMatrix = new Array();
  81440. this._identity = BABYLON.Matrix.Identity();
  81441. this._ranges = {};
  81442. this._lastAbsoluteTransformsUpdateId = -1;
  81443. /**
  81444. * Specifies if the skeleton should be serialized
  81445. */
  81446. this.doNotSerialize = false;
  81447. this._animationPropertiesOverride = null;
  81448. // Events
  81449. /**
  81450. * An observable triggered before computing the skeleton's matrices
  81451. */
  81452. this.onBeforeComputeObservable = new BABYLON.Observable();
  81453. this.bones = [];
  81454. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81455. scene.skeletons.push(this);
  81456. //make sure it will recalculate the matrix next time prepare is called.
  81457. this._isDirty = true;
  81458. }
  81459. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81460. /**
  81461. * Gets or sets the animation properties override
  81462. */
  81463. get: function () {
  81464. if (!this._animationPropertiesOverride) {
  81465. return this._scene.animationPropertiesOverride;
  81466. }
  81467. return this._animationPropertiesOverride;
  81468. },
  81469. set: function (value) {
  81470. this._animationPropertiesOverride = value;
  81471. },
  81472. enumerable: true,
  81473. configurable: true
  81474. });
  81475. // Members
  81476. /**
  81477. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81478. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81479. * @returns a Float32Array containing matrices data
  81480. */
  81481. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81482. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81483. return mesh._bonesTransformMatrices;
  81484. }
  81485. if (!this._transformMatrices) {
  81486. this.prepare();
  81487. }
  81488. return this._transformMatrices;
  81489. };
  81490. /**
  81491. * Gets the current hosting scene
  81492. * @returns a scene object
  81493. */
  81494. Skeleton.prototype.getScene = function () {
  81495. return this._scene;
  81496. };
  81497. // Methods
  81498. /**
  81499. * Gets a string representing the current skeleton data
  81500. * @param fullDetails defines a boolean indicating if we want a verbose version
  81501. * @returns a string representing the current skeleton data
  81502. */
  81503. Skeleton.prototype.toString = function (fullDetails) {
  81504. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81505. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81506. if (fullDetails) {
  81507. ret += ", Ranges: {";
  81508. var first = true;
  81509. for (var name_1 in this._ranges) {
  81510. if (first) {
  81511. ret += ", ";
  81512. first = false;
  81513. }
  81514. ret += name_1;
  81515. }
  81516. ret += "}";
  81517. }
  81518. return ret;
  81519. };
  81520. /**
  81521. * Get bone's index searching by name
  81522. * @param name defines bone's name to search for
  81523. * @return the indice of the bone. Returns -1 if not found
  81524. */
  81525. Skeleton.prototype.getBoneIndexByName = function (name) {
  81526. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81527. if (this.bones[boneIndex].name === name) {
  81528. return boneIndex;
  81529. }
  81530. }
  81531. return -1;
  81532. };
  81533. /**
  81534. * Creater a new animation range
  81535. * @param name defines the name of the range
  81536. * @param from defines the start key
  81537. * @param to defines the end key
  81538. */
  81539. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81540. // check name not already in use
  81541. if (!this._ranges[name]) {
  81542. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81543. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81544. if (this.bones[i].animations[0]) {
  81545. this.bones[i].animations[0].createRange(name, from, to);
  81546. }
  81547. }
  81548. }
  81549. };
  81550. /**
  81551. * Delete a specific animation range
  81552. * @param name defines the name of the range
  81553. * @param deleteFrames defines if frames must be removed as well
  81554. */
  81555. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81556. if (deleteFrames === void 0) { deleteFrames = true; }
  81557. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81558. if (this.bones[i].animations[0]) {
  81559. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81560. }
  81561. }
  81562. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81563. };
  81564. /**
  81565. * Gets a specific animation range
  81566. * @param name defines the name of the range to look for
  81567. * @returns the requested animation range or null if not found
  81568. */
  81569. Skeleton.prototype.getAnimationRange = function (name) {
  81570. return this._ranges[name];
  81571. };
  81572. /**
  81573. * Gets the list of all animation ranges defined on this skeleton
  81574. * @returns an array
  81575. */
  81576. Skeleton.prototype.getAnimationRanges = function () {
  81577. var animationRanges = [];
  81578. var name;
  81579. var i = 0;
  81580. for (name in this._ranges) {
  81581. animationRanges[i] = this._ranges[name];
  81582. i++;
  81583. }
  81584. return animationRanges;
  81585. };
  81586. /**
  81587. * Copy animation range from a source skeleton.
  81588. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81589. * @param source defines the source skeleton
  81590. * @param name defines the name of the range to copy
  81591. * @param rescaleAsRequired defines if rescaling must be applied if required
  81592. * @returns true if operation was successful
  81593. */
  81594. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81595. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81596. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81597. return false;
  81598. }
  81599. var ret = true;
  81600. var frameOffset = this._getHighestAnimationFrame() + 1;
  81601. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81602. var boneDict = {};
  81603. var sourceBones = source.bones;
  81604. var nBones;
  81605. var i;
  81606. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81607. boneDict[sourceBones[i].name] = sourceBones[i];
  81608. }
  81609. if (this.bones.length !== sourceBones.length) {
  81610. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81611. ret = false;
  81612. }
  81613. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81614. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81615. var boneName = this.bones[i].name;
  81616. var sourceBone = boneDict[boneName];
  81617. if (sourceBone) {
  81618. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81619. }
  81620. else {
  81621. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81622. ret = false;
  81623. }
  81624. }
  81625. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81626. var range = source.getAnimationRange(name);
  81627. if (range) {
  81628. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81629. }
  81630. return ret;
  81631. };
  81632. /**
  81633. * Forces the skeleton to go to rest pose
  81634. */
  81635. Skeleton.prototype.returnToRest = function () {
  81636. for (var index = 0; index < this.bones.length; index++) {
  81637. this.bones[index].returnToRest();
  81638. }
  81639. };
  81640. Skeleton.prototype._getHighestAnimationFrame = function () {
  81641. var ret = 0;
  81642. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81643. if (this.bones[i].animations[0]) {
  81644. var highest = this.bones[i].animations[0].getHighestFrame();
  81645. if (ret < highest) {
  81646. ret = highest;
  81647. }
  81648. }
  81649. }
  81650. return ret;
  81651. };
  81652. /**
  81653. * Begin a specific animation range
  81654. * @param name defines the name of the range to start
  81655. * @param loop defines if looping must be turned on (false by default)
  81656. * @param speedRatio defines the speed ratio to apply (1 by default)
  81657. * @param onAnimationEnd defines a callback which will be called when animation will end
  81658. * @returns a new animatable
  81659. */
  81660. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81661. var range = this.getAnimationRange(name);
  81662. if (!range) {
  81663. return null;
  81664. }
  81665. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81666. };
  81667. /** @hidden */
  81668. Skeleton.prototype._markAsDirty = function () {
  81669. this._isDirty = true;
  81670. };
  81671. /** @hidden */
  81672. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81673. this._meshesWithPoseMatrix.push(mesh);
  81674. };
  81675. /** @hidden */
  81676. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81677. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81678. if (index > -1) {
  81679. this._meshesWithPoseMatrix.splice(index, 1);
  81680. }
  81681. };
  81682. /** @hidden */
  81683. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81684. this.onBeforeComputeObservable.notifyObservers(this);
  81685. for (var index = 0; index < this.bones.length; index++) {
  81686. var bone = this.bones[index];
  81687. var parentBone = bone.getParent();
  81688. if (parentBone) {
  81689. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81690. }
  81691. else {
  81692. if (initialSkinMatrix) {
  81693. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81694. }
  81695. else {
  81696. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81697. }
  81698. }
  81699. if (bone._index !== -1) {
  81700. var mappedIndex = bone._index === null ? index : bone._index;
  81701. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81702. }
  81703. }
  81704. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81705. };
  81706. /**
  81707. * Build all resources required to render a skeleton
  81708. */
  81709. Skeleton.prototype.prepare = function () {
  81710. if (!this._isDirty) {
  81711. return;
  81712. }
  81713. if (this.needInitialSkinMatrix) {
  81714. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81715. var mesh = this._meshesWithPoseMatrix[index];
  81716. var poseMatrix = mesh.getPoseMatrix();
  81717. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81718. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81719. }
  81720. if (this._synchronizedWithMesh !== mesh) {
  81721. this._synchronizedWithMesh = mesh;
  81722. // Prepare bones
  81723. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81724. var bone = this.bones[boneIndex];
  81725. if (!bone.getParent()) {
  81726. var matrix = bone.getBaseMatrix();
  81727. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81728. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81729. }
  81730. }
  81731. }
  81732. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81733. }
  81734. }
  81735. else {
  81736. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81737. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81738. }
  81739. this._computeTransformMatrices(this._transformMatrices, null);
  81740. }
  81741. this._isDirty = false;
  81742. this._scene._activeBones.addCount(this.bones.length, false);
  81743. };
  81744. /**
  81745. * Gets the list of animatables currently running for this skeleton
  81746. * @returns an array of animatables
  81747. */
  81748. Skeleton.prototype.getAnimatables = function () {
  81749. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81750. this._animatables = [];
  81751. for (var index = 0; index < this.bones.length; index++) {
  81752. this._animatables.push(this.bones[index]);
  81753. }
  81754. }
  81755. return this._animatables;
  81756. };
  81757. /**
  81758. * Clone the current skeleton
  81759. * @param name defines the name of the new skeleton
  81760. * @param id defines the id of the enw skeleton
  81761. * @returns the new skeleton
  81762. */
  81763. Skeleton.prototype.clone = function (name, id) {
  81764. var result = new Skeleton(name, id || name, this._scene);
  81765. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81766. for (var index = 0; index < this.bones.length; index++) {
  81767. var source = this.bones[index];
  81768. var parentBone = null;
  81769. var parent_1 = source.getParent();
  81770. if (parent_1) {
  81771. var parentIndex = this.bones.indexOf(parent_1);
  81772. parentBone = result.bones[parentIndex];
  81773. }
  81774. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81775. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81776. }
  81777. if (this._ranges) {
  81778. result._ranges = {};
  81779. for (var rangeName in this._ranges) {
  81780. var range = this._ranges[rangeName];
  81781. if (range) {
  81782. result._ranges[rangeName] = range.clone();
  81783. }
  81784. }
  81785. }
  81786. this._isDirty = true;
  81787. return result;
  81788. };
  81789. /**
  81790. * Enable animation blending for this skeleton
  81791. * @param blendingSpeed defines the blending speed to apply
  81792. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81793. */
  81794. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81795. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81796. this.bones.forEach(function (bone) {
  81797. bone.animations.forEach(function (animation) {
  81798. animation.enableBlending = true;
  81799. animation.blendingSpeed = blendingSpeed;
  81800. });
  81801. });
  81802. };
  81803. /**
  81804. * Releases all resources associated with the current skeleton
  81805. */
  81806. Skeleton.prototype.dispose = function () {
  81807. this._meshesWithPoseMatrix = [];
  81808. // Animations
  81809. this.getScene().stopAnimation(this);
  81810. // Remove from scene
  81811. this.getScene().removeSkeleton(this);
  81812. };
  81813. /**
  81814. * Serialize the skeleton in a JSON object
  81815. * @returns a JSON object
  81816. */
  81817. Skeleton.prototype.serialize = function () {
  81818. var serializationObject = {};
  81819. serializationObject.name = this.name;
  81820. serializationObject.id = this.id;
  81821. if (this.dimensionsAtRest) {
  81822. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81823. }
  81824. serializationObject.bones = [];
  81825. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81826. for (var index = 0; index < this.bones.length; index++) {
  81827. var bone = this.bones[index];
  81828. var parent_2 = bone.getParent();
  81829. var serializedBone = {
  81830. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81831. name: bone.name,
  81832. matrix: bone.getBaseMatrix().toArray(),
  81833. rest: bone.getRestPose().toArray()
  81834. };
  81835. serializationObject.bones.push(serializedBone);
  81836. if (bone.length) {
  81837. serializedBone.length = bone.length;
  81838. }
  81839. if (bone.metadata) {
  81840. serializedBone.metadata = bone.metadata;
  81841. }
  81842. if (bone.animations && bone.animations.length > 0) {
  81843. serializedBone.animation = bone.animations[0].serialize();
  81844. }
  81845. serializationObject.ranges = [];
  81846. for (var name in this._ranges) {
  81847. var source = this._ranges[name];
  81848. if (!source) {
  81849. continue;
  81850. }
  81851. var range = {};
  81852. range.name = name;
  81853. range.from = source.from;
  81854. range.to = source.to;
  81855. serializationObject.ranges.push(range);
  81856. }
  81857. }
  81858. return serializationObject;
  81859. };
  81860. /**
  81861. * Creates a new skeleton from serialized data
  81862. * @param parsedSkeleton defines the serialized data
  81863. * @param scene defines the hosting scene
  81864. * @returns a new skeleton
  81865. */
  81866. Skeleton.Parse = function (parsedSkeleton, scene) {
  81867. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81868. if (parsedSkeleton.dimensionsAtRest) {
  81869. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81870. }
  81871. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81872. var index;
  81873. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81874. var parsedBone = parsedSkeleton.bones[index];
  81875. var parentBone = null;
  81876. if (parsedBone.parentBoneIndex > -1) {
  81877. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81878. }
  81879. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81880. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81881. if (parsedBone.length) {
  81882. bone.length = parsedBone.length;
  81883. }
  81884. if (parsedBone.metadata) {
  81885. bone.metadata = parsedBone.metadata;
  81886. }
  81887. if (parsedBone.animation) {
  81888. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81889. }
  81890. }
  81891. // placed after bones, so createAnimationRange can cascade down
  81892. if (parsedSkeleton.ranges) {
  81893. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81894. var data = parsedSkeleton.ranges[index];
  81895. skeleton.createAnimationRange(data.name, data.from, data.to);
  81896. }
  81897. }
  81898. return skeleton;
  81899. };
  81900. /**
  81901. * Compute all node absolute transforms
  81902. * @param forceUpdate defines if computation must be done even if cache is up to date
  81903. */
  81904. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81905. if (forceUpdate === void 0) { forceUpdate = false; }
  81906. var renderId = this._scene.getRenderId();
  81907. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81908. this.bones[0].computeAbsoluteTransforms();
  81909. this._lastAbsoluteTransformsUpdateId = renderId;
  81910. }
  81911. };
  81912. /**
  81913. * Gets the root pose matrix
  81914. * @returns a matrix
  81915. */
  81916. Skeleton.prototype.getPoseMatrix = function () {
  81917. var poseMatrix = null;
  81918. if (this._meshesWithPoseMatrix.length > 0) {
  81919. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81920. }
  81921. return poseMatrix;
  81922. };
  81923. /**
  81924. * Sorts bones per internal index
  81925. */
  81926. Skeleton.prototype.sortBones = function () {
  81927. var bones = new Array();
  81928. var visited = new Array(this.bones.length);
  81929. for (var index = 0; index < this.bones.length; index++) {
  81930. this._sortBones(index, bones, visited);
  81931. }
  81932. this.bones = bones;
  81933. };
  81934. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81935. if (visited[index]) {
  81936. return;
  81937. }
  81938. visited[index] = true;
  81939. var bone = this.bones[index];
  81940. if (bone._index === undefined) {
  81941. bone._index = index;
  81942. }
  81943. var parentBone = bone.getParent();
  81944. if (parentBone) {
  81945. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81946. }
  81947. bones.push(bone);
  81948. };
  81949. return Skeleton;
  81950. }());
  81951. BABYLON.Skeleton = Skeleton;
  81952. })(BABYLON || (BABYLON = {}));
  81953. //# sourceMappingURL=babylon.skeleton.js.map
  81954. var BABYLON;
  81955. (function (BABYLON) {
  81956. /**
  81957. * Class representing spherical polynomial coefficients to the 3rd degree
  81958. */
  81959. var SphericalPolynomial = /** @class */ (function () {
  81960. function SphericalPolynomial() {
  81961. /**
  81962. * The x coefficients of the spherical polynomial
  81963. */
  81964. this.x = BABYLON.Vector3.Zero();
  81965. /**
  81966. * The y coefficients of the spherical polynomial
  81967. */
  81968. this.y = BABYLON.Vector3.Zero();
  81969. /**
  81970. * The z coefficients of the spherical polynomial
  81971. */
  81972. this.z = BABYLON.Vector3.Zero();
  81973. /**
  81974. * The xx coefficients of the spherical polynomial
  81975. */
  81976. this.xx = BABYLON.Vector3.Zero();
  81977. /**
  81978. * The yy coefficients of the spherical polynomial
  81979. */
  81980. this.yy = BABYLON.Vector3.Zero();
  81981. /**
  81982. * The zz coefficients of the spherical polynomial
  81983. */
  81984. this.zz = BABYLON.Vector3.Zero();
  81985. /**
  81986. * The xy coefficients of the spherical polynomial
  81987. */
  81988. this.xy = BABYLON.Vector3.Zero();
  81989. /**
  81990. * The yz coefficients of the spherical polynomial
  81991. */
  81992. this.yz = BABYLON.Vector3.Zero();
  81993. /**
  81994. * The zx coefficients of the spherical polynomial
  81995. */
  81996. this.zx = BABYLON.Vector3.Zero();
  81997. }
  81998. /**
  81999. * Adds an ambient color to the spherical polynomial
  82000. * @param color the color to add
  82001. */
  82002. SphericalPolynomial.prototype.addAmbient = function (color) {
  82003. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82004. this.xx = this.xx.add(colorVector);
  82005. this.yy = this.yy.add(colorVector);
  82006. this.zz = this.zz.add(colorVector);
  82007. };
  82008. /**
  82009. * Scales the spherical polynomial by the given amount
  82010. * @param scale the amount to scale
  82011. */
  82012. SphericalPolynomial.prototype.scale = function (scale) {
  82013. this.x = this.x.scale(scale);
  82014. this.y = this.y.scale(scale);
  82015. this.z = this.z.scale(scale);
  82016. this.xx = this.xx.scale(scale);
  82017. this.yy = this.yy.scale(scale);
  82018. this.zz = this.zz.scale(scale);
  82019. this.yz = this.yz.scale(scale);
  82020. this.zx = this.zx.scale(scale);
  82021. this.xy = this.xy.scale(scale);
  82022. };
  82023. /**
  82024. * Gets the spherical polynomial from harmonics
  82025. * @param harmonics the spherical harmonics
  82026. * @returns the spherical polynomial
  82027. */
  82028. SphericalPolynomial.FromHarmonics = function (harmonics) {
  82029. var result = new SphericalPolynomial();
  82030. result.x = harmonics.l11.scale(1.02333);
  82031. result.y = harmonics.l1_1.scale(1.02333);
  82032. result.z = harmonics.l10.scale(1.02333);
  82033. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  82034. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  82035. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  82036. result.yz = harmonics.l2_1.scale(0.858086);
  82037. result.zx = harmonics.l21.scale(0.858086);
  82038. result.xy = harmonics.l2_2.scale(0.858086);
  82039. result.scale(1.0 / Math.PI);
  82040. return result;
  82041. };
  82042. /**
  82043. * Constructs a spherical polynomial from an array.
  82044. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  82045. * @returns the spherical polynomial
  82046. */
  82047. SphericalPolynomial.FromArray = function (data) {
  82048. var sp = new SphericalPolynomial();
  82049. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  82050. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  82051. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  82052. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  82053. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  82054. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  82055. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  82056. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  82057. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  82058. return sp;
  82059. };
  82060. return SphericalPolynomial;
  82061. }());
  82062. BABYLON.SphericalPolynomial = SphericalPolynomial;
  82063. /**
  82064. * Class representing spherical harmonics coefficients to the 3rd degree
  82065. */
  82066. var SphericalHarmonics = /** @class */ (function () {
  82067. function SphericalHarmonics() {
  82068. /**
  82069. * The l0,0 coefficients of the spherical harmonics
  82070. */
  82071. this.l00 = BABYLON.Vector3.Zero();
  82072. /**
  82073. * The l1,-1 coefficients of the spherical harmonics
  82074. */
  82075. this.l1_1 = BABYLON.Vector3.Zero();
  82076. /**
  82077. * The l1,0 coefficients of the spherical harmonics
  82078. */
  82079. this.l10 = BABYLON.Vector3.Zero();
  82080. /**
  82081. * The l1,1 coefficients of the spherical harmonics
  82082. */
  82083. this.l11 = BABYLON.Vector3.Zero();
  82084. /**
  82085. * The l2,-2 coefficients of the spherical harmonics
  82086. */
  82087. this.l2_2 = BABYLON.Vector3.Zero();
  82088. /**
  82089. * The l2,-1 coefficients of the spherical harmonics
  82090. */
  82091. this.l2_1 = BABYLON.Vector3.Zero();
  82092. /**
  82093. * The l2,0 coefficients of the spherical harmonics
  82094. */
  82095. this.l20 = BABYLON.Vector3.Zero();
  82096. /**
  82097. * The l2,1 coefficients of the spherical harmonics
  82098. */
  82099. this.l21 = BABYLON.Vector3.Zero();
  82100. /**
  82101. * The l2,2 coefficients of the spherical harmonics
  82102. */
  82103. this.lL22 = BABYLON.Vector3.Zero();
  82104. }
  82105. /**
  82106. * Adds a light to the spherical harmonics
  82107. * @param direction the direction of the light
  82108. * @param color the color of the light
  82109. * @param deltaSolidAngle the delta solid angle of the light
  82110. */
  82111. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  82112. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82113. var c = colorVector.scale(deltaSolidAngle);
  82114. this.l00 = this.l00.add(c.scale(0.282095));
  82115. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  82116. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  82117. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  82118. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  82119. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  82120. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  82121. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  82122. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  82123. };
  82124. /**
  82125. * Scales the spherical harmonics by the given amount
  82126. * @param scale the amount to scale
  82127. */
  82128. SphericalHarmonics.prototype.scale = function (scale) {
  82129. this.l00 = this.l00.scale(scale);
  82130. this.l1_1 = this.l1_1.scale(scale);
  82131. this.l10 = this.l10.scale(scale);
  82132. this.l11 = this.l11.scale(scale);
  82133. this.l2_2 = this.l2_2.scale(scale);
  82134. this.l2_1 = this.l2_1.scale(scale);
  82135. this.l20 = this.l20.scale(scale);
  82136. this.l21 = this.l21.scale(scale);
  82137. this.lL22 = this.lL22.scale(scale);
  82138. };
  82139. /**
  82140. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  82141. *
  82142. * ```
  82143. * E_lm = A_l * L_lm
  82144. * ```
  82145. *
  82146. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  82147. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  82148. * the scaling factors are given in equation 9.
  82149. */
  82150. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  82151. // Constant (Band 0)
  82152. this.l00 = this.l00.scale(3.141593);
  82153. // Linear (Band 1)
  82154. this.l1_1 = this.l1_1.scale(2.094395);
  82155. this.l10 = this.l10.scale(2.094395);
  82156. this.l11 = this.l11.scale(2.094395);
  82157. // Quadratic (Band 2)
  82158. this.l2_2 = this.l2_2.scale(0.785398);
  82159. this.l2_1 = this.l2_1.scale(0.785398);
  82160. this.l20 = this.l20.scale(0.785398);
  82161. this.l21 = this.l21.scale(0.785398);
  82162. this.lL22 = this.lL22.scale(0.785398);
  82163. };
  82164. /**
  82165. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82166. *
  82167. * ```
  82168. * L = (1/pi) * E * rho
  82169. * ```
  82170. *
  82171. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82172. */
  82173. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  82174. this.scale(1.0 / Math.PI);
  82175. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82176. // (The pixel shader must apply albedo after texture fetches, etc).
  82177. };
  82178. /**
  82179. * Gets the spherical harmonics from polynomial
  82180. * @param polynomial the spherical polynomial
  82181. * @returns the spherical harmonics
  82182. */
  82183. SphericalHarmonics.FromPolynomial = function (polynomial) {
  82184. var result = new SphericalHarmonics();
  82185. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  82186. result.l1_1 = polynomial.y.scale(0.977204);
  82187. result.l10 = polynomial.z.scale(0.977204);
  82188. result.l11 = polynomial.x.scale(0.977204);
  82189. result.l2_2 = polynomial.xy.scale(1.16538);
  82190. result.l2_1 = polynomial.yz.scale(1.16538);
  82191. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  82192. result.l21 = polynomial.zx.scale(1.16538);
  82193. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  82194. result.scale(Math.PI);
  82195. return result;
  82196. };
  82197. /**
  82198. * Constructs a spherical harmonics from an array.
  82199. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  82200. * @returns the spherical harmonics
  82201. */
  82202. SphericalHarmonics.FromArray = function (data) {
  82203. var sh = new SphericalHarmonics();
  82204. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  82205. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  82206. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  82207. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  82208. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  82209. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  82210. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  82211. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  82212. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  82213. return sh;
  82214. };
  82215. return SphericalHarmonics;
  82216. }());
  82217. BABYLON.SphericalHarmonics = SphericalHarmonics;
  82218. })(BABYLON || (BABYLON = {}));
  82219. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  82220. var BABYLON;
  82221. (function (BABYLON) {
  82222. var FileFaceOrientation = /** @class */ (function () {
  82223. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  82224. this.name = name;
  82225. this.worldAxisForNormal = worldAxisForNormal;
  82226. this.worldAxisForFileX = worldAxisForFileX;
  82227. this.worldAxisForFileY = worldAxisForFileY;
  82228. }
  82229. return FileFaceOrientation;
  82230. }());
  82231. ;
  82232. /**
  82233. * Helper class dealing with the extraction of spherical polynomial dataArray
  82234. * from a cube map.
  82235. */
  82236. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  82237. function CubeMapToSphericalPolynomialTools() {
  82238. }
  82239. /**
  82240. * Converts a texture to the according Spherical Polynomial data.
  82241. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82242. *
  82243. * @param texture The texture to extract the information from.
  82244. * @return The Spherical Polynomial data.
  82245. */
  82246. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  82247. if (!texture.isCube) {
  82248. // Only supports cube Textures currently.
  82249. return null;
  82250. }
  82251. var size = texture.getSize().width;
  82252. var right = texture.readPixels(0);
  82253. var left = texture.readPixels(1);
  82254. var up;
  82255. var down;
  82256. if (texture.isRenderTarget) {
  82257. up = texture.readPixels(3);
  82258. down = texture.readPixels(2);
  82259. }
  82260. else {
  82261. up = texture.readPixels(2);
  82262. down = texture.readPixels(3);
  82263. }
  82264. var front = texture.readPixels(4);
  82265. var back = texture.readPixels(5);
  82266. var gammaSpace = texture.gammaSpace;
  82267. // Always read as RGBA.
  82268. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82269. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82270. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82271. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82272. }
  82273. var cubeInfo = {
  82274. size: size,
  82275. right: right,
  82276. left: left,
  82277. up: up,
  82278. down: down,
  82279. front: front,
  82280. back: back,
  82281. format: format,
  82282. type: type,
  82283. gammaSpace: gammaSpace,
  82284. };
  82285. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  82286. };
  82287. /**
  82288. * Converts a cubemap to the according Spherical Polynomial data.
  82289. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82290. *
  82291. * @param cubeInfo The Cube map to extract the information from.
  82292. * @return The Spherical Polynomial data.
  82293. */
  82294. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  82295. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  82296. var totalSolidAngle = 0.0;
  82297. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  82298. var du = 2.0 / cubeInfo.size;
  82299. var dv = du;
  82300. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  82301. var minUV = du * 0.5 - 1.0;
  82302. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  82303. var fileFace = this.FileFaces[faceIndex];
  82304. var dataArray = cubeInfo[fileFace.name];
  82305. var v = minUV;
  82306. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82307. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82308. // Because SP is still linear, so summation is fine in that basis.
  82309. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82310. for (var y = 0; y < cubeInfo.size; y++) {
  82311. var u = minUV;
  82312. for (var x = 0; x < cubeInfo.size; x++) {
  82313. // World direction (not normalised)
  82314. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  82315. worldDirection.normalize();
  82316. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  82317. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  82318. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  82319. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  82320. // Handle Integer types.
  82321. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82322. r /= 255;
  82323. g /= 255;
  82324. b /= 255;
  82325. }
  82326. // Handle Gamma space textures.
  82327. if (cubeInfo.gammaSpace) {
  82328. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  82329. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  82330. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  82331. }
  82332. var color = new BABYLON.Color3(r, g, b);
  82333. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  82334. totalSolidAngle += deltaSolidAngle;
  82335. u += du;
  82336. }
  82337. v += dv;
  82338. }
  82339. }
  82340. // Solid angle for entire sphere is 4*pi
  82341. var sphereSolidAngle = 4.0 * Math.PI;
  82342. // Adjust the solid angle to allow for how many faces we processed.
  82343. var facesProcessed = 6.0;
  82344. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  82345. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  82346. // This is needed because the numerical integration over the cube uses a
  82347. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  82348. // and also to compensate for accumulative error due to float precision in the summation.
  82349. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  82350. sphericalHarmonics.scale(correctionFactor);
  82351. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  82352. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  82353. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  82354. };
  82355. CubeMapToSphericalPolynomialTools.FileFaces = [
  82356. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  82357. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  82358. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  82359. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  82360. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  82361. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  82362. ];
  82363. return CubeMapToSphericalPolynomialTools;
  82364. }());
  82365. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  82366. })(BABYLON || (BABYLON = {}));
  82367. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  82368. var BABYLON;
  82369. (function (BABYLON) {
  82370. /**
  82371. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  82372. */
  82373. var PanoramaToCubeMapTools = /** @class */ (function () {
  82374. function PanoramaToCubeMapTools() {
  82375. }
  82376. /**
  82377. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  82378. *
  82379. * @param float32Array The source data.
  82380. * @param inputWidth The width of the input panorama.
  82381. * @param inputhHeight The height of the input panorama.
  82382. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  82383. * @return The cubemap data
  82384. */
  82385. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  82386. if (!float32Array) {
  82387. throw "ConvertPanoramaToCubemap: input cannot be null";
  82388. }
  82389. if (float32Array.length != inputWidth * inputHeight * 3) {
  82390. throw "ConvertPanoramaToCubemap: input size is wrong";
  82391. }
  82392. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82393. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82394. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  82395. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  82396. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  82397. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  82398. return {
  82399. front: textureFront,
  82400. back: textureBack,
  82401. left: textureLeft,
  82402. right: textureRight,
  82403. up: textureUp,
  82404. down: textureDown,
  82405. size: size,
  82406. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  82407. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  82408. gammaSpace: false,
  82409. };
  82410. };
  82411. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  82412. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  82413. var textureArray = new Float32Array(buffer);
  82414. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82415. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82416. var dy = 1 / texSize;
  82417. var fy = 0;
  82418. for (var y = 0; y < texSize; y++) {
  82419. var xv1 = faceData[0];
  82420. var xv2 = faceData[2];
  82421. for (var x = 0; x < texSize; x++) {
  82422. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82423. v.normalize();
  82424. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82425. // 3 channels per pixels
  82426. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82427. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82428. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82429. xv1 = xv1.add(rotDX1);
  82430. xv2 = xv2.add(rotDX2);
  82431. }
  82432. fy += dy;
  82433. }
  82434. return textureArray;
  82435. };
  82436. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82437. var theta = Math.atan2(vDir.z, vDir.x);
  82438. var phi = Math.acos(vDir.y);
  82439. while (theta < -Math.PI)
  82440. theta += 2 * Math.PI;
  82441. while (theta > Math.PI)
  82442. theta -= 2 * Math.PI;
  82443. var dx = theta / Math.PI;
  82444. var dy = phi / Math.PI;
  82445. // recenter.
  82446. dx = dx * 0.5 + 0.5;
  82447. var px = Math.round(dx * inputWidth);
  82448. if (px < 0)
  82449. px = 0;
  82450. else if (px >= inputWidth)
  82451. px = inputWidth - 1;
  82452. var py = Math.round(dy * inputHeight);
  82453. if (py < 0)
  82454. py = 0;
  82455. else if (py >= inputHeight)
  82456. py = inputHeight - 1;
  82457. var inputY = (inputHeight - py - 1);
  82458. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82459. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82460. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82461. return {
  82462. r: r,
  82463. g: g,
  82464. b: b
  82465. };
  82466. };
  82467. PanoramaToCubeMapTools.FACE_FRONT = [
  82468. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82469. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82470. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82471. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82472. ];
  82473. PanoramaToCubeMapTools.FACE_BACK = [
  82474. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82475. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82476. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82477. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82478. ];
  82479. PanoramaToCubeMapTools.FACE_RIGHT = [
  82480. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82481. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82482. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82483. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82484. ];
  82485. PanoramaToCubeMapTools.FACE_LEFT = [
  82486. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82487. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82488. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82489. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82490. ];
  82491. PanoramaToCubeMapTools.FACE_DOWN = [
  82492. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82493. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82494. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82495. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82496. ];
  82497. PanoramaToCubeMapTools.FACE_UP = [
  82498. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82499. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82500. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82501. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82502. ];
  82503. return PanoramaToCubeMapTools;
  82504. }());
  82505. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82506. })(BABYLON || (BABYLON = {}));
  82507. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82508. var BABYLON;
  82509. (function (BABYLON) {
  82510. ;
  82511. /**
  82512. * This groups tools to convert HDR texture to native colors array.
  82513. */
  82514. var HDRTools = /** @class */ (function () {
  82515. function HDRTools() {
  82516. }
  82517. HDRTools.Ldexp = function (mantissa, exponent) {
  82518. if (exponent > 1023) {
  82519. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82520. }
  82521. if (exponent < -1074) {
  82522. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82523. }
  82524. return mantissa * Math.pow(2, exponent);
  82525. };
  82526. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82527. if (exponent > 0) { /*nonzero pixel*/
  82528. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82529. float32array[index + 0] = red * exponent;
  82530. float32array[index + 1] = green * exponent;
  82531. float32array[index + 2] = blue * exponent;
  82532. }
  82533. else {
  82534. float32array[index + 0] = 0;
  82535. float32array[index + 1] = 0;
  82536. float32array[index + 2] = 0;
  82537. }
  82538. };
  82539. HDRTools.readStringLine = function (uint8array, startIndex) {
  82540. var line = "";
  82541. var character = "";
  82542. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82543. character = String.fromCharCode(uint8array[i]);
  82544. if (character == "\n") {
  82545. break;
  82546. }
  82547. line += character;
  82548. }
  82549. return line;
  82550. };
  82551. /**
  82552. * Reads header information from an RGBE texture stored in a native array.
  82553. * More information on this format are available here:
  82554. * https://en.wikipedia.org/wiki/RGBE_image_format
  82555. *
  82556. * @param uint8array The binary file stored in native array.
  82557. * @return The header information.
  82558. */
  82559. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82560. var height = 0;
  82561. var width = 0;
  82562. var line = this.readStringLine(uint8array, 0);
  82563. if (line[0] != '#' || line[1] != '?') {
  82564. throw "Bad HDR Format.";
  82565. }
  82566. var endOfHeader = false;
  82567. var findFormat = false;
  82568. var lineIndex = 0;
  82569. do {
  82570. lineIndex += (line.length + 1);
  82571. line = this.readStringLine(uint8array, lineIndex);
  82572. if (line == "FORMAT=32-bit_rle_rgbe") {
  82573. findFormat = true;
  82574. }
  82575. else if (line.length == 0) {
  82576. endOfHeader = true;
  82577. }
  82578. } while (!endOfHeader);
  82579. if (!findFormat) {
  82580. throw "HDR Bad header format, unsupported FORMAT";
  82581. }
  82582. lineIndex += (line.length + 1);
  82583. line = this.readStringLine(uint8array, lineIndex);
  82584. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82585. var match = sizeRegexp.exec(line);
  82586. // TODO. Support +Y and -X if needed.
  82587. if (!match || match.length < 3) {
  82588. throw "HDR Bad header format, no size";
  82589. }
  82590. width = parseInt(match[2]);
  82591. height = parseInt(match[1]);
  82592. if (width < 8 || width > 0x7fff) {
  82593. throw "HDR Bad header format, unsupported size";
  82594. }
  82595. lineIndex += (line.length + 1);
  82596. return {
  82597. height: height,
  82598. width: width,
  82599. dataPosition: lineIndex
  82600. };
  82601. };
  82602. /**
  82603. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82604. * This RGBE texture needs to store the information as a panorama.
  82605. *
  82606. * More information on this format are available here:
  82607. * https://en.wikipedia.org/wiki/RGBE_image_format
  82608. *
  82609. * @param buffer The binary file stored in an array buffer.
  82610. * @param size The expected size of the extracted cubemap.
  82611. * @return The Cube Map information.
  82612. */
  82613. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82614. var uint8array = new Uint8Array(buffer);
  82615. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82616. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82617. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82618. return cubeMapData;
  82619. };
  82620. /**
  82621. * Returns the pixels data extracted from an RGBE texture.
  82622. * This pixels will be stored left to right up to down in the R G B order in one array.
  82623. *
  82624. * More information on this format are available here:
  82625. * https://en.wikipedia.org/wiki/RGBE_image_format
  82626. *
  82627. * @param uint8array The binary file stored in an array buffer.
  82628. * @param hdrInfo The header information of the file.
  82629. * @return The pixels data in RGB right to left up to down order.
  82630. */
  82631. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82632. // Keep for multi format supports.
  82633. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82634. };
  82635. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82636. var num_scanlines = hdrInfo.height;
  82637. var scanline_width = hdrInfo.width;
  82638. var a, b, c, d, count;
  82639. var dataIndex = hdrInfo.dataPosition;
  82640. var index = 0, endIndex = 0, i = 0;
  82641. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82642. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82643. // 3 channels of 4 bytes per pixel in float.
  82644. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82645. var resultArray = new Float32Array(resultBuffer);
  82646. // read in each successive scanline
  82647. while (num_scanlines > 0) {
  82648. a = uint8array[dataIndex++];
  82649. b = uint8array[dataIndex++];
  82650. c = uint8array[dataIndex++];
  82651. d = uint8array[dataIndex++];
  82652. if (a != 2 || b != 2 || (c & 0x80)) {
  82653. // this file is not run length encoded
  82654. throw "HDR Bad header format, not RLE";
  82655. }
  82656. if (((c << 8) | d) != scanline_width) {
  82657. throw "HDR Bad header format, wrong scan line width";
  82658. }
  82659. index = 0;
  82660. // read each of the four channels for the scanline into the buffer
  82661. for (i = 0; i < 4; i++) {
  82662. endIndex = (i + 1) * scanline_width;
  82663. while (index < endIndex) {
  82664. a = uint8array[dataIndex++];
  82665. b = uint8array[dataIndex++];
  82666. if (a > 128) {
  82667. // a run of the same value
  82668. count = a - 128;
  82669. if ((count == 0) || (count > endIndex - index)) {
  82670. throw "HDR Bad Format, bad scanline data (run)";
  82671. }
  82672. while (count-- > 0) {
  82673. scanLineArray[index++] = b;
  82674. }
  82675. }
  82676. else {
  82677. // a non-run
  82678. count = a;
  82679. if ((count == 0) || (count > endIndex - index)) {
  82680. throw "HDR Bad Format, bad scanline data (non-run)";
  82681. }
  82682. scanLineArray[index++] = b;
  82683. if (--count > 0) {
  82684. for (var j = 0; j < count; j++) {
  82685. scanLineArray[index++] = uint8array[dataIndex++];
  82686. }
  82687. }
  82688. }
  82689. }
  82690. }
  82691. // now convert data from buffer into floats
  82692. for (i = 0; i < scanline_width; i++) {
  82693. a = scanLineArray[i];
  82694. b = scanLineArray[i + scanline_width];
  82695. c = scanLineArray[i + 2 * scanline_width];
  82696. d = scanLineArray[i + 3 * scanline_width];
  82697. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82698. }
  82699. num_scanlines--;
  82700. }
  82701. return resultArray;
  82702. };
  82703. return HDRTools;
  82704. }());
  82705. BABYLON.HDRTools = HDRTools;
  82706. })(BABYLON || (BABYLON = {}));
  82707. //# sourceMappingURL=babylon.hdr.js.map
  82708. var BABYLON;
  82709. (function (BABYLON) {
  82710. /**
  82711. * Sets of helpers addressing the serialization and deserialization of environment texture
  82712. * stored in a BabylonJS env file.
  82713. * Those files are usually stored as .env files.
  82714. */
  82715. var EnvironmentTextureTools = /** @class */ (function () {
  82716. function EnvironmentTextureTools() {
  82717. }
  82718. /**
  82719. * Gets the environment info from an env file.
  82720. * @param data The array buffer containing the .env bytes.
  82721. * @returns the environment file info (the json header) if successfully parsed.
  82722. */
  82723. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82724. var dataView = new DataView(data);
  82725. var pos = 0;
  82726. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82727. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82728. BABYLON.Tools.Error('Not a babylon environment map');
  82729. return null;
  82730. }
  82731. }
  82732. // Read json manifest - collect characters up to null terminator
  82733. var manifestString = '';
  82734. var charCode = 0x00;
  82735. while ((charCode = dataView.getUint8(pos++))) {
  82736. manifestString += String.fromCharCode(charCode);
  82737. }
  82738. var manifest = JSON.parse(manifestString);
  82739. if (manifest.specular) {
  82740. // Extend the header with the position of the payload.
  82741. manifest.specular.specularDataPosition = pos;
  82742. }
  82743. return manifest;
  82744. };
  82745. /**
  82746. * Creates an environment texture from a loaded cube texture.
  82747. * @param texture defines the cube texture to convert in env file
  82748. * @return a promise containing the environment data if succesfull.
  82749. */
  82750. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82751. var _this = this;
  82752. var internalTexture = texture.getInternalTexture();
  82753. if (!internalTexture) {
  82754. return Promise.reject("The cube texture is invalid.");
  82755. }
  82756. if (!texture._prefiltered) {
  82757. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82758. }
  82759. var engine = internalTexture.getEngine();
  82760. if (engine && engine.premultipliedAlpha) {
  82761. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82762. }
  82763. var canvas = engine.getRenderingCanvas();
  82764. if (!canvas) {
  82765. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82766. }
  82767. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82768. if (!engine.getCaps().textureFloatRender) {
  82769. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82770. if (!engine.getCaps().textureHalfFloatRender) {
  82771. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82772. }
  82773. }
  82774. var cubeWidth = internalTexture.width;
  82775. var hostingScene = new BABYLON.Scene(engine);
  82776. var specularTextures = {};
  82777. var promises = [];
  82778. // Read and collect all mipmaps data from the cube.
  82779. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82780. mipmapsCount = Math.round(mipmapsCount);
  82781. var _loop_1 = function (i) {
  82782. var faceWidth = Math.pow(2, mipmapsCount - i);
  82783. var _loop_2 = function (face) {
  82784. var data = texture.readPixels(face, i);
  82785. // Creates a temp texture with the face data.
  82786. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82787. // And rgbdEncode them.
  82788. var promise = new Promise(function (resolve, reject) {
  82789. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  82790. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82791. rgbdPostProcess.onApply = function (effect) {
  82792. effect._bindTexture("textureSampler", tempTexture);
  82793. };
  82794. // As the process needs to happen on the main canvas, keep track of the current size
  82795. var currentW = engine.getRenderWidth();
  82796. var currentH = engine.getRenderHeight();
  82797. // Set the desired size for the texture
  82798. engine.setSize(faceWidth, faceWidth);
  82799. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82800. // Reading datas from WebGL
  82801. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82802. var fileReader = new FileReader();
  82803. fileReader.onload = function (event) {
  82804. var arrayBuffer = event.target.result;
  82805. specularTextures[i * 6 + face] = arrayBuffer;
  82806. resolve();
  82807. };
  82808. fileReader.readAsArrayBuffer(blob);
  82809. });
  82810. // Reapply the previous canvas size
  82811. engine.setSize(currentW, currentH);
  82812. });
  82813. });
  82814. promises.push(promise);
  82815. };
  82816. // All faces of the cube.
  82817. for (var face = 0; face < 6; face++) {
  82818. _loop_2(face);
  82819. }
  82820. };
  82821. for (var i = 0; i <= mipmapsCount; i++) {
  82822. _loop_1(i);
  82823. }
  82824. // Once all the textures haves been collected as RGBD stored in PNGs
  82825. return Promise.all(promises).then(function () {
  82826. // We can delete the hosting scene keeping track of all the creation objects
  82827. hostingScene.dispose();
  82828. // Creates the json header for the env texture
  82829. var info = {
  82830. version: 1,
  82831. width: cubeWidth,
  82832. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82833. specular: {
  82834. mipmaps: []
  82835. }
  82836. };
  82837. // Sets the specular image data information
  82838. var position = 0;
  82839. for (var i = 0; i <= mipmapsCount; i++) {
  82840. for (var face = 0; face < 6; face++) {
  82841. var byteLength = specularTextures[i * 6 + face].byteLength;
  82842. info.specular.mipmaps.push({
  82843. length: byteLength,
  82844. position: position
  82845. });
  82846. position += byteLength;
  82847. }
  82848. }
  82849. // Encode the JSON as an array buffer
  82850. var infoString = JSON.stringify(info);
  82851. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82852. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82853. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82854. infoView[i] = infoString.charCodeAt(i);
  82855. }
  82856. // Ends up with a null terminator for easier parsing
  82857. infoView[infoString.length] = 0x00;
  82858. // Computes the final required size and creates the storage
  82859. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82860. var finalBuffer = new ArrayBuffer(totalSize);
  82861. var finalBufferView = new Uint8Array(finalBuffer);
  82862. var dataView = new DataView(finalBuffer);
  82863. // Copy the magic bytes identifying the file in
  82864. var pos = 0;
  82865. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82866. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82867. }
  82868. // Add the json info
  82869. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82870. pos += infoBuffer.byteLength;
  82871. // Finally inserts the texture data
  82872. for (var i = 0; i <= mipmapsCount; i++) {
  82873. for (var face = 0; face < 6; face++) {
  82874. var dataBuffer = specularTextures[i * 6 + face];
  82875. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82876. pos += dataBuffer.byteLength;
  82877. }
  82878. }
  82879. // Voila
  82880. return finalBuffer;
  82881. });
  82882. };
  82883. /**
  82884. * Creates a JSON representation of the spherical data.
  82885. * @param texture defines the texture containing the polynomials
  82886. * @return the JSON representation of the spherical info
  82887. */
  82888. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82889. var polynmials = texture.sphericalPolynomial;
  82890. if (polynmials == null) {
  82891. return null;
  82892. }
  82893. return {
  82894. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82895. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82896. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82897. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82898. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82899. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82900. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82901. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82902. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82903. };
  82904. };
  82905. /**
  82906. * Uploads the texture info contained in the env file to the GPU.
  82907. * @param texture defines the internal texture to upload to
  82908. * @param arrayBuffer defines the buffer cotaining the data to load
  82909. * @param info defines the texture info retrieved through the GetEnvInfo method
  82910. * @returns a promise
  82911. */
  82912. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  82913. if (info.version !== 1) {
  82914. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82915. }
  82916. var specularInfo = info.specular;
  82917. if (!specularInfo) {
  82918. // Nothing else parsed so far
  82919. return Promise.resolve();
  82920. }
  82921. // Double checks the enclosed info
  82922. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82923. mipmapsCount = Math.round(mipmapsCount) + 1;
  82924. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82925. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82926. }
  82927. var imageData = new Array(mipmapsCount);
  82928. for (var i = 0; i < mipmapsCount; i++) {
  82929. imageData[i] = new Array(6);
  82930. for (var face = 0; face < 6; face++) {
  82931. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  82932. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  82933. }
  82934. }
  82935. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  82936. };
  82937. /**
  82938. * Uploads the levels of image data to the GPU.
  82939. * @param texture defines the internal texture to upload to
  82940. * @param imageData defines the array buffer views of image data [mipmap][face]
  82941. * @returns a promise
  82942. */
  82943. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  82944. var mipmapsCount = imageData.length;
  82945. // Gets everything ready.
  82946. var engine = texture.getEngine();
  82947. var expandTexture = false;
  82948. var generateNonLODTextures = false;
  82949. var rgbdPostProcess = null;
  82950. var cubeRtt = null;
  82951. var lodTextures = null;
  82952. var caps = engine.getCaps();
  82953. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82954. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82955. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82956. // Add extra process if texture lod is not supported
  82957. if (!caps.textureLOD) {
  82958. expandTexture = false;
  82959. generateNonLODTextures = true;
  82960. lodTextures = {};
  82961. }
  82962. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82963. else if (engine.webGLVersion < 2) {
  82964. expandTexture = false;
  82965. }
  82966. // If half float available we can uncompress the texture
  82967. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82968. expandTexture = true;
  82969. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82970. }
  82971. // If full float available we can uncompress the texture
  82972. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82973. expandTexture = true;
  82974. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82975. }
  82976. // Expand the texture if possible
  82977. if (expandTexture) {
  82978. // Simply run through the decode PP
  82979. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82980. texture._isRGBD = false;
  82981. texture.invertY = false;
  82982. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82983. generateDepthBuffer: false,
  82984. generateMipMaps: true,
  82985. generateStencilBuffer: false,
  82986. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82987. type: texture.type,
  82988. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82989. });
  82990. }
  82991. else {
  82992. texture._isRGBD = true;
  82993. texture.invertY = true;
  82994. // In case of missing support, applies the same patch than DDS files.
  82995. if (generateNonLODTextures) {
  82996. var mipSlices = 3;
  82997. var scale = texture._lodGenerationScale;
  82998. var offset = texture._lodGenerationOffset;
  82999. for (var i = 0; i < mipSlices; i++) {
  83000. //compute LOD from even spacing in smoothness (matching shader calculation)
  83001. var smoothness = i / (mipSlices - 1);
  83002. var roughness = 1 - smoothness;
  83003. var minLODIndex = offset; // roughness = 0
  83004. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  83005. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  83006. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  83007. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  83008. glTextureFromLod.isCube = true;
  83009. glTextureFromLod.invertY = true;
  83010. glTextureFromLod.generateMipMaps = false;
  83011. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  83012. // Wrap in a base texture for easy binding.
  83013. var lodTexture = new BABYLON.BaseTexture(null);
  83014. lodTexture.isCube = true;
  83015. lodTexture._texture = glTextureFromLod;
  83016. lodTextures[mipmapIndex] = lodTexture;
  83017. switch (i) {
  83018. case 0:
  83019. texture._lodTextureLow = lodTexture;
  83020. break;
  83021. case 1:
  83022. texture._lodTextureMid = lodTexture;
  83023. break;
  83024. case 2:
  83025. texture._lodTextureHigh = lodTexture;
  83026. break;
  83027. }
  83028. }
  83029. }
  83030. }
  83031. var promises = [];
  83032. var _loop_3 = function (i) {
  83033. var _loop_4 = function (face) {
  83034. // Constructs an image element from image data
  83035. var bytes = imageData[i][face];
  83036. var blob = new Blob([bytes], { type: 'image/png' });
  83037. var url = URL.createObjectURL(blob);
  83038. var image = new Image();
  83039. image.src = url;
  83040. // Enqueue promise to upload to the texture.
  83041. var promise = new Promise(function (resolve, reject) {
  83042. image.onload = function () {
  83043. if (expandTexture) {
  83044. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  83045. reject(message);
  83046. }, image);
  83047. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  83048. // Uncompress the data to a RTT
  83049. rgbdPostProcess.onApply = function (effect) {
  83050. effect._bindTexture("textureSampler", tempTexture_1);
  83051. effect.setFloat2("scale", 1, 1);
  83052. };
  83053. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  83054. // Cleanup
  83055. engine.restoreDefaultFramebuffer();
  83056. tempTexture_1.dispose();
  83057. window.URL.revokeObjectURL(url);
  83058. resolve();
  83059. });
  83060. }
  83061. else {
  83062. engine._uploadImageToTexture(texture, image, face, i);
  83063. // Upload the face to the none lod texture support
  83064. if (generateNonLODTextures) {
  83065. var lodTexture = lodTextures[i];
  83066. if (lodTexture) {
  83067. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  83068. }
  83069. }
  83070. resolve();
  83071. }
  83072. };
  83073. image.onerror = function (error) {
  83074. reject(error);
  83075. };
  83076. });
  83077. promises.push(promise);
  83078. };
  83079. // All faces
  83080. for (var face = 0; face < 6; face++) {
  83081. _loop_4(face);
  83082. }
  83083. };
  83084. // All mipmaps
  83085. for (var i = 0; i < mipmapsCount; i++) {
  83086. _loop_3(i);
  83087. }
  83088. // Once all done, finishes the cleanup and return
  83089. return Promise.all(promises).then(function () {
  83090. // Relase temp RTT.
  83091. if (cubeRtt) {
  83092. engine._releaseFramebufferObjects(cubeRtt);
  83093. cubeRtt._swapAndDie(texture);
  83094. }
  83095. // Relase temp Post Process.
  83096. if (rgbdPostProcess) {
  83097. rgbdPostProcess.dispose();
  83098. }
  83099. // Flag internal texture as ready in case they are in use.
  83100. if (generateNonLODTextures) {
  83101. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  83102. texture._lodTextureHigh._texture.isReady = true;
  83103. }
  83104. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  83105. texture._lodTextureMid._texture.isReady = true;
  83106. }
  83107. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  83108. texture._lodTextureLow._texture.isReady = true;
  83109. }
  83110. }
  83111. });
  83112. };
  83113. /**
  83114. * Uploads spherical polynomials information to the texture.
  83115. * @param texture defines the texture we are trying to upload the information to
  83116. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  83117. */
  83118. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  83119. if (info.version !== 1) {
  83120. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  83121. }
  83122. var irradianceInfo = info.irradiance;
  83123. if (!irradianceInfo) {
  83124. return;
  83125. }
  83126. var sp = new BABYLON.SphericalPolynomial();
  83127. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  83128. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  83129. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  83130. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  83131. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  83132. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  83133. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  83134. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  83135. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  83136. texture._sphericalPolynomial = sp;
  83137. };
  83138. /**
  83139. * Magic number identifying the env file.
  83140. */
  83141. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  83142. return EnvironmentTextureTools;
  83143. }());
  83144. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  83145. })(BABYLON || (BABYLON = {}));
  83146. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  83147. var BABYLON;
  83148. (function (BABYLON) {
  83149. /**
  83150. * This represents a texture coming from an HDR input.
  83151. *
  83152. * The only supported format is currently panorama picture stored in RGBE format.
  83153. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83154. */
  83155. var HDRCubeTexture = /** @class */ (function (_super) {
  83156. __extends(HDRCubeTexture, _super);
  83157. /**
  83158. * Instantiates an HDRTexture from the following parameters.
  83159. *
  83160. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83161. * @param scene The scene the texture will be used in
  83162. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83163. * @param noMipmap Forces to not generate the mipmap if true
  83164. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83165. * @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)
  83166. * @param reserved Reserved flag for internal use.
  83167. */
  83168. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83169. if (noMipmap === void 0) { noMipmap = false; }
  83170. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83171. if (gammaSpace === void 0) { gammaSpace = false; }
  83172. if (reserved === void 0) { reserved = false; }
  83173. if (onLoad === void 0) { onLoad = null; }
  83174. if (onError === void 0) { onError = null; }
  83175. var _this = _super.call(this, scene) || this;
  83176. _this._generateHarmonics = true;
  83177. _this._onLoad = null;
  83178. _this._onError = null;
  83179. /**
  83180. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83181. */
  83182. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83183. _this._isBlocking = true;
  83184. _this._rotationY = 0;
  83185. /**
  83186. * Gets or sets the center of the bounding box associated with the cube texture
  83187. * It must define where the camera used to render the texture was set
  83188. */
  83189. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83190. if (!url) {
  83191. return _this;
  83192. }
  83193. _this.name = url;
  83194. _this.url = url;
  83195. _this.hasAlpha = false;
  83196. _this.isCube = true;
  83197. _this._textureMatrix = BABYLON.Matrix.Identity();
  83198. _this._onLoad = onLoad;
  83199. _this._onError = onError;
  83200. _this.gammaSpace = gammaSpace;
  83201. _this._noMipmap = noMipmap;
  83202. _this._size = size;
  83203. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83204. if (!_this._texture) {
  83205. if (!scene.useDelayedTextureLoading) {
  83206. _this.loadTexture();
  83207. }
  83208. else {
  83209. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83210. }
  83211. }
  83212. return _this;
  83213. }
  83214. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83215. /**
  83216. * Gets wether or not the texture is blocking during loading.
  83217. */
  83218. get: function () {
  83219. return this._isBlocking;
  83220. },
  83221. /**
  83222. * Sets wether or not the texture is blocking during loading.
  83223. */
  83224. set: function (value) {
  83225. this._isBlocking = value;
  83226. },
  83227. enumerable: true,
  83228. configurable: true
  83229. });
  83230. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83231. /**
  83232. * Gets texture matrix rotation angle around Y axis radians.
  83233. */
  83234. get: function () {
  83235. return this._rotationY;
  83236. },
  83237. /**
  83238. * Sets texture matrix rotation angle around Y axis in radians.
  83239. */
  83240. set: function (value) {
  83241. this._rotationY = value;
  83242. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83243. },
  83244. enumerable: true,
  83245. configurable: true
  83246. });
  83247. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83248. get: function () {
  83249. return this._boundingBoxSize;
  83250. },
  83251. /**
  83252. * Gets or sets the size of the bounding box associated with the cube texture
  83253. * When defined, the cubemap will switch to local mode
  83254. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83255. * @example https://www.babylonjs-playground.com/#RNASML
  83256. */
  83257. set: function (value) {
  83258. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83259. return;
  83260. }
  83261. this._boundingBoxSize = value;
  83262. var scene = this.getScene();
  83263. if (scene) {
  83264. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83265. }
  83266. },
  83267. enumerable: true,
  83268. configurable: true
  83269. });
  83270. /**
  83271. * Occurs when the file is raw .hdr file.
  83272. */
  83273. HDRCubeTexture.prototype.loadTexture = function () {
  83274. var _this = this;
  83275. var callback = function (buffer) {
  83276. _this.lodGenerationOffset = 0.0;
  83277. _this.lodGenerationScale = 0.8;
  83278. var scene = _this.getScene();
  83279. if (!scene) {
  83280. return null;
  83281. }
  83282. // Extract the raw linear data.
  83283. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83284. // Generate harmonics if needed.
  83285. if (_this._generateHarmonics) {
  83286. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83287. _this.sphericalPolynomial = sphericalPolynomial;
  83288. }
  83289. var results = [];
  83290. var byteArray = null;
  83291. // Push each faces.
  83292. for (var j = 0; j < 6; j++) {
  83293. // Create uintarray fallback.
  83294. if (!scene.getEngine().getCaps().textureFloat) {
  83295. // 3 channels of 1 bytes per pixel in bytes.
  83296. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83297. byteArray = new Uint8Array(byteBuffer);
  83298. }
  83299. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83300. // If special cases.
  83301. if (_this.gammaSpace || byteArray) {
  83302. for (var i = 0; i < _this._size * _this._size; i++) {
  83303. // Put in gamma space if requested.
  83304. if (_this.gammaSpace) {
  83305. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83306. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83307. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83308. }
  83309. // Convert to int texture for fallback.
  83310. if (byteArray) {
  83311. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83312. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83313. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83314. // May use luminance instead if the result is not accurate.
  83315. var max = Math.max(Math.max(r, g), b);
  83316. if (max > 255) {
  83317. var scale = 255 / max;
  83318. r *= scale;
  83319. g *= scale;
  83320. b *= scale;
  83321. }
  83322. byteArray[(i * 3) + 0] = r;
  83323. byteArray[(i * 3) + 1] = g;
  83324. byteArray[(i * 3) + 2] = b;
  83325. }
  83326. }
  83327. }
  83328. if (byteArray) {
  83329. results.push(byteArray);
  83330. }
  83331. else {
  83332. results.push(dataFace);
  83333. }
  83334. }
  83335. return results;
  83336. };
  83337. var scene = this.getScene();
  83338. if (scene) {
  83339. 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);
  83340. }
  83341. };
  83342. HDRCubeTexture.prototype.clone = function () {
  83343. var scene = this.getScene();
  83344. if (!scene) {
  83345. return this;
  83346. }
  83347. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83348. // Base texture
  83349. newTexture.level = this.level;
  83350. newTexture.wrapU = this.wrapU;
  83351. newTexture.wrapV = this.wrapV;
  83352. newTexture.coordinatesIndex = this.coordinatesIndex;
  83353. newTexture.coordinatesMode = this.coordinatesMode;
  83354. return newTexture;
  83355. };
  83356. // Methods
  83357. HDRCubeTexture.prototype.delayLoad = function () {
  83358. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83359. return;
  83360. }
  83361. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83362. this._texture = this._getFromCache(this.url, this._noMipmap);
  83363. if (!this._texture) {
  83364. this.loadTexture();
  83365. }
  83366. };
  83367. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83368. return this._textureMatrix;
  83369. };
  83370. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83371. this._textureMatrix = value;
  83372. };
  83373. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83374. var texture = null;
  83375. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83376. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83377. texture.name = parsedTexture.name;
  83378. texture.hasAlpha = parsedTexture.hasAlpha;
  83379. texture.level = parsedTexture.level;
  83380. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83381. texture.isBlocking = parsedTexture.isBlocking;
  83382. }
  83383. if (texture) {
  83384. if (parsedTexture.boundingBoxPosition) {
  83385. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83386. }
  83387. if (parsedTexture.boundingBoxSize) {
  83388. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83389. }
  83390. if (parsedTexture.rotationY) {
  83391. texture.rotationY = parsedTexture.rotationY;
  83392. }
  83393. }
  83394. return texture;
  83395. };
  83396. HDRCubeTexture.prototype.serialize = function () {
  83397. if (!this.name) {
  83398. return null;
  83399. }
  83400. var serializationObject = {};
  83401. serializationObject.name = this.name;
  83402. serializationObject.hasAlpha = this.hasAlpha;
  83403. serializationObject.isCube = true;
  83404. serializationObject.level = this.level;
  83405. serializationObject.size = this._size;
  83406. serializationObject.coordinatesMode = this.coordinatesMode;
  83407. serializationObject.useInGammaSpace = this.gammaSpace;
  83408. serializationObject.generateHarmonics = this._generateHarmonics;
  83409. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83410. serializationObject.noMipmap = this._noMipmap;
  83411. serializationObject.isBlocking = this._isBlocking;
  83412. serializationObject.rotationY = this._rotationY;
  83413. return serializationObject;
  83414. };
  83415. HDRCubeTexture._facesMapping = [
  83416. "right",
  83417. "left",
  83418. "up",
  83419. "down",
  83420. "front",
  83421. "back"
  83422. ];
  83423. return HDRCubeTexture;
  83424. }(BABYLON.BaseTexture));
  83425. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83426. })(BABYLON || (BABYLON = {}));
  83427. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83428. var BABYLON;
  83429. (function (BABYLON) {
  83430. var IndexedVector2 = /** @class */ (function (_super) {
  83431. __extends(IndexedVector2, _super);
  83432. function IndexedVector2(original, index) {
  83433. var _this = _super.call(this, original.x, original.y) || this;
  83434. _this.index = index;
  83435. return _this;
  83436. }
  83437. return IndexedVector2;
  83438. }(BABYLON.Vector2));
  83439. var PolygonPoints = /** @class */ (function () {
  83440. function PolygonPoints() {
  83441. this.elements = new Array();
  83442. }
  83443. PolygonPoints.prototype.add = function (originalPoints) {
  83444. var _this = this;
  83445. var result = new Array();
  83446. originalPoints.forEach(function (point) {
  83447. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83448. var newPoint = new IndexedVector2(point, _this.elements.length);
  83449. result.push(newPoint);
  83450. _this.elements.push(newPoint);
  83451. }
  83452. });
  83453. return result;
  83454. };
  83455. PolygonPoints.prototype.computeBounds = function () {
  83456. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83457. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83458. this.elements.forEach(function (point) {
  83459. // x
  83460. if (point.x < lmin.x) {
  83461. lmin.x = point.x;
  83462. }
  83463. else if (point.x > lmax.x) {
  83464. lmax.x = point.x;
  83465. }
  83466. // y
  83467. if (point.y < lmin.y) {
  83468. lmin.y = point.y;
  83469. }
  83470. else if (point.y > lmax.y) {
  83471. lmax.y = point.y;
  83472. }
  83473. });
  83474. return {
  83475. min: lmin,
  83476. max: lmax,
  83477. width: lmax.x - lmin.x,
  83478. height: lmax.y - lmin.y
  83479. };
  83480. };
  83481. return PolygonPoints;
  83482. }());
  83483. var Polygon = /** @class */ (function () {
  83484. function Polygon() {
  83485. }
  83486. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83487. return [
  83488. new BABYLON.Vector2(xmin, ymin),
  83489. new BABYLON.Vector2(xmax, ymin),
  83490. new BABYLON.Vector2(xmax, ymax),
  83491. new BABYLON.Vector2(xmin, ymax)
  83492. ];
  83493. };
  83494. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83495. if (cx === void 0) { cx = 0; }
  83496. if (cy === void 0) { cy = 0; }
  83497. if (numberOfSides === void 0) { numberOfSides = 32; }
  83498. var result = new Array();
  83499. var angle = 0;
  83500. var increment = (Math.PI * 2) / numberOfSides;
  83501. for (var i = 0; i < numberOfSides; i++) {
  83502. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83503. angle -= increment;
  83504. }
  83505. return result;
  83506. };
  83507. Polygon.Parse = function (input) {
  83508. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83509. var i, result = [];
  83510. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83511. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83512. }
  83513. return result;
  83514. };
  83515. Polygon.StartingAt = function (x, y) {
  83516. return BABYLON.Path2.StartingAt(x, y);
  83517. };
  83518. return Polygon;
  83519. }());
  83520. BABYLON.Polygon = Polygon;
  83521. var PolygonMeshBuilder = /** @class */ (function () {
  83522. function PolygonMeshBuilder(name, contours, scene) {
  83523. this._points = new PolygonPoints();
  83524. this._outlinepoints = new PolygonPoints();
  83525. this._holes = new Array();
  83526. this._epoints = new Array();
  83527. this._eholes = new Array();
  83528. this._name = name;
  83529. this._scene = scene;
  83530. var points;
  83531. if (contours instanceof BABYLON.Path2) {
  83532. points = contours.getPoints();
  83533. }
  83534. else {
  83535. points = contours;
  83536. }
  83537. this._addToepoint(points);
  83538. this._points.add(points);
  83539. this._outlinepoints.add(points);
  83540. if (typeof earcut === 'undefined') {
  83541. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83542. }
  83543. }
  83544. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83545. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83546. var p = points_1[_i];
  83547. this._epoints.push(p.x, p.y);
  83548. }
  83549. };
  83550. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83551. this._points.add(hole);
  83552. var holepoints = new PolygonPoints();
  83553. holepoints.add(hole);
  83554. this._holes.push(holepoints);
  83555. this._eholes.push(this._epoints.length / 2);
  83556. this._addToepoint(hole);
  83557. return this;
  83558. };
  83559. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83560. var _this = this;
  83561. if (updatable === void 0) { updatable = false; }
  83562. if (depth === void 0) { depth = 0; }
  83563. var result = new BABYLON.Mesh(this._name, this._scene);
  83564. var normals = new Array();
  83565. var positions = new Array();
  83566. var uvs = new Array();
  83567. var bounds = this._points.computeBounds();
  83568. this._points.elements.forEach(function (p) {
  83569. normals.push(0, 1.0, 0);
  83570. positions.push(p.x, 0, p.y);
  83571. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83572. });
  83573. var indices = new Array();
  83574. var res = earcut(this._epoints, this._eholes, 2);
  83575. for (var i = 0; i < res.length; i++) {
  83576. indices.push(res[i]);
  83577. }
  83578. if (depth > 0) {
  83579. var positionscount = (positions.length / 3); //get the current pointcount
  83580. this._points.elements.forEach(function (p) {
  83581. normals.push(0, -1.0, 0);
  83582. positions.push(p.x, -depth, p.y);
  83583. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83584. });
  83585. var totalCount = indices.length;
  83586. for (var i = 0; i < totalCount; i += 3) {
  83587. var i0 = indices[i + 0];
  83588. var i1 = indices[i + 1];
  83589. var i2 = indices[i + 2];
  83590. indices.push(i2 + positionscount);
  83591. indices.push(i1 + positionscount);
  83592. indices.push(i0 + positionscount);
  83593. }
  83594. //Add the sides
  83595. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83596. this._holes.forEach(function (hole) {
  83597. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83598. });
  83599. }
  83600. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83601. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83602. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83603. result.setIndices(indices);
  83604. return result;
  83605. };
  83606. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83607. var StartIndex = positions.length / 3;
  83608. var ulength = 0;
  83609. for (var i = 0; i < points.elements.length; i++) {
  83610. var p = points.elements[i];
  83611. var p1;
  83612. if ((i + 1) > points.elements.length - 1) {
  83613. p1 = points.elements[0];
  83614. }
  83615. else {
  83616. p1 = points.elements[i + 1];
  83617. }
  83618. positions.push(p.x, 0, p.y);
  83619. positions.push(p.x, -depth, p.y);
  83620. positions.push(p1.x, 0, p1.y);
  83621. positions.push(p1.x, -depth, p1.y);
  83622. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83623. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83624. var v3 = v2.subtract(v1);
  83625. var v4 = new BABYLON.Vector3(0, 1, 0);
  83626. var vn = BABYLON.Vector3.Cross(v3, v4);
  83627. vn = vn.normalize();
  83628. uvs.push(ulength / bounds.width, 0);
  83629. uvs.push(ulength / bounds.width, 1);
  83630. ulength += v3.length();
  83631. uvs.push((ulength / bounds.width), 0);
  83632. uvs.push((ulength / bounds.width), 1);
  83633. if (!flip) {
  83634. normals.push(-vn.x, -vn.y, -vn.z);
  83635. normals.push(-vn.x, -vn.y, -vn.z);
  83636. normals.push(-vn.x, -vn.y, -vn.z);
  83637. normals.push(-vn.x, -vn.y, -vn.z);
  83638. indices.push(StartIndex);
  83639. indices.push(StartIndex + 1);
  83640. indices.push(StartIndex + 2);
  83641. indices.push(StartIndex + 1);
  83642. indices.push(StartIndex + 3);
  83643. indices.push(StartIndex + 2);
  83644. }
  83645. else {
  83646. normals.push(vn.x, vn.y, vn.z);
  83647. normals.push(vn.x, vn.y, vn.z);
  83648. normals.push(vn.x, vn.y, vn.z);
  83649. normals.push(vn.x, vn.y, vn.z);
  83650. indices.push(StartIndex);
  83651. indices.push(StartIndex + 2);
  83652. indices.push(StartIndex + 1);
  83653. indices.push(StartIndex + 1);
  83654. indices.push(StartIndex + 2);
  83655. indices.push(StartIndex + 3);
  83656. }
  83657. StartIndex += 4;
  83658. }
  83659. ;
  83660. };
  83661. return PolygonMeshBuilder;
  83662. }());
  83663. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83664. })(BABYLON || (BABYLON = {}));
  83665. //# sourceMappingURL=babylon.polygonMesh.js.map
  83666. var BABYLON;
  83667. (function (BABYLON) {
  83668. // Unique ID when we import meshes from Babylon to CSG
  83669. var currentCSGMeshId = 0;
  83670. // # class Vertex
  83671. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83672. // one to provide additional features like texture coordinates and vertex
  83673. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83674. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83675. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83676. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83677. // is not used anywhere else.
  83678. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83679. var Vertex = /** @class */ (function () {
  83680. function Vertex(pos, normal, uv) {
  83681. this.pos = pos;
  83682. this.normal = normal;
  83683. this.uv = uv;
  83684. }
  83685. Vertex.prototype.clone = function () {
  83686. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83687. };
  83688. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83689. // orientation of a polygon is flipped.
  83690. Vertex.prototype.flip = function () {
  83691. this.normal = this.normal.scale(-1);
  83692. };
  83693. // Create a new vertex between this vertex and `other` by linearly
  83694. // interpolating all properties using a parameter of `t`. Subclasses should
  83695. // override this to interpolate additional properties.
  83696. Vertex.prototype.interpolate = function (other, t) {
  83697. 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));
  83698. };
  83699. return Vertex;
  83700. }());
  83701. // # class Plane
  83702. // Represents a plane in 3D space.
  83703. var Plane = /** @class */ (function () {
  83704. function Plane(normal, w) {
  83705. this.normal = normal;
  83706. this.w = w;
  83707. }
  83708. Plane.FromPoints = function (a, b, c) {
  83709. var v0 = c.subtract(a);
  83710. var v1 = b.subtract(a);
  83711. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83712. return null;
  83713. }
  83714. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83715. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83716. };
  83717. Plane.prototype.clone = function () {
  83718. return new Plane(this.normal.clone(), this.w);
  83719. };
  83720. Plane.prototype.flip = function () {
  83721. this.normal.scaleInPlace(-1);
  83722. this.w = -this.w;
  83723. };
  83724. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83725. // fragments in the appropriate lists. Coplanar polygons go into either
  83726. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83727. // respect to this plane. Polygons in front or in back of this plane go into
  83728. // either `front` or `back`.
  83729. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83730. var COPLANAR = 0;
  83731. var FRONT = 1;
  83732. var BACK = 2;
  83733. var SPANNING = 3;
  83734. // Classify each point as well as the entire polygon into one of the above
  83735. // four classes.
  83736. var polygonType = 0;
  83737. var types = [];
  83738. var i;
  83739. var t;
  83740. for (i = 0; i < polygon.vertices.length; i++) {
  83741. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83742. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83743. polygonType |= type;
  83744. types.push(type);
  83745. }
  83746. // Put the polygon in the correct list, splitting it when necessary.
  83747. switch (polygonType) {
  83748. case COPLANAR:
  83749. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83750. break;
  83751. case FRONT:
  83752. front.push(polygon);
  83753. break;
  83754. case BACK:
  83755. back.push(polygon);
  83756. break;
  83757. case SPANNING:
  83758. var f = [], b = [];
  83759. for (i = 0; i < polygon.vertices.length; i++) {
  83760. var j = (i + 1) % polygon.vertices.length;
  83761. var ti = types[i], tj = types[j];
  83762. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83763. if (ti !== BACK)
  83764. f.push(vi);
  83765. if (ti !== FRONT)
  83766. b.push(ti !== BACK ? vi.clone() : vi);
  83767. if ((ti | tj) === SPANNING) {
  83768. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83769. var v = vi.interpolate(vj, t);
  83770. f.push(v);
  83771. b.push(v.clone());
  83772. }
  83773. }
  83774. var poly;
  83775. if (f.length >= 3) {
  83776. poly = new Polygon(f, polygon.shared);
  83777. if (poly.plane)
  83778. front.push(poly);
  83779. }
  83780. if (b.length >= 3) {
  83781. poly = new Polygon(b, polygon.shared);
  83782. if (poly.plane)
  83783. back.push(poly);
  83784. }
  83785. break;
  83786. }
  83787. };
  83788. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83789. // point is on the plane.
  83790. Plane.EPSILON = 1e-5;
  83791. return Plane;
  83792. }());
  83793. // # class Polygon
  83794. // Represents a convex polygon. The vertices used to initialize a polygon must
  83795. // be coplanar and form a convex loop.
  83796. //
  83797. // Each convex polygon has a `shared` property, which is shared between all
  83798. // polygons that are clones of each other or were split from the same polygon.
  83799. // This can be used to define per-polygon properties (such as surface color).
  83800. var Polygon = /** @class */ (function () {
  83801. function Polygon(vertices, shared) {
  83802. this.vertices = vertices;
  83803. this.shared = shared;
  83804. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83805. }
  83806. Polygon.prototype.clone = function () {
  83807. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83808. return new Polygon(vertices, this.shared);
  83809. };
  83810. Polygon.prototype.flip = function () {
  83811. this.vertices.reverse().map(function (v) { v.flip(); });
  83812. this.plane.flip();
  83813. };
  83814. return Polygon;
  83815. }());
  83816. // # class Node
  83817. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83818. // by picking a polygon to split along. That polygon (and all other coplanar
  83819. // polygons) are added directly to that node and the other polygons are added to
  83820. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83821. // no distinction between internal and leaf nodes.
  83822. var Node = /** @class */ (function () {
  83823. function Node(polygons) {
  83824. this.plane = null;
  83825. this.front = null;
  83826. this.back = null;
  83827. this.polygons = new Array();
  83828. if (polygons) {
  83829. this.build(polygons);
  83830. }
  83831. }
  83832. Node.prototype.clone = function () {
  83833. var node = new Node();
  83834. node.plane = this.plane && this.plane.clone();
  83835. node.front = this.front && this.front.clone();
  83836. node.back = this.back && this.back.clone();
  83837. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83838. return node;
  83839. };
  83840. // Convert solid space to empty space and empty space to solid space.
  83841. Node.prototype.invert = function () {
  83842. for (var i = 0; i < this.polygons.length; i++) {
  83843. this.polygons[i].flip();
  83844. }
  83845. if (this.plane) {
  83846. this.plane.flip();
  83847. }
  83848. if (this.front) {
  83849. this.front.invert();
  83850. }
  83851. if (this.back) {
  83852. this.back.invert();
  83853. }
  83854. var temp = this.front;
  83855. this.front = this.back;
  83856. this.back = temp;
  83857. };
  83858. // Recursively remove all polygons in `polygons` that are inside this BSP
  83859. // tree.
  83860. Node.prototype.clipPolygons = function (polygons) {
  83861. if (!this.plane)
  83862. return polygons.slice();
  83863. var front = new Array(), back = new Array();
  83864. for (var i = 0; i < polygons.length; i++) {
  83865. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83866. }
  83867. if (this.front) {
  83868. front = this.front.clipPolygons(front);
  83869. }
  83870. if (this.back) {
  83871. back = this.back.clipPolygons(back);
  83872. }
  83873. else {
  83874. back = [];
  83875. }
  83876. return front.concat(back);
  83877. };
  83878. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83879. // `bsp`.
  83880. Node.prototype.clipTo = function (bsp) {
  83881. this.polygons = bsp.clipPolygons(this.polygons);
  83882. if (this.front)
  83883. this.front.clipTo(bsp);
  83884. if (this.back)
  83885. this.back.clipTo(bsp);
  83886. };
  83887. // Return a list of all polygons in this BSP tree.
  83888. Node.prototype.allPolygons = function () {
  83889. var polygons = this.polygons.slice();
  83890. if (this.front)
  83891. polygons = polygons.concat(this.front.allPolygons());
  83892. if (this.back)
  83893. polygons = polygons.concat(this.back.allPolygons());
  83894. return polygons;
  83895. };
  83896. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83897. // new polygons are filtered down to the bottom of the tree and become new
  83898. // nodes there. Each set of polygons is partitioned using the first polygon
  83899. // (no heuristic is used to pick a good split).
  83900. Node.prototype.build = function (polygons) {
  83901. if (!polygons.length)
  83902. return;
  83903. if (!this.plane)
  83904. this.plane = polygons[0].plane.clone();
  83905. var front = new Array(), back = new Array();
  83906. for (var i = 0; i < polygons.length; i++) {
  83907. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83908. }
  83909. if (front.length) {
  83910. if (!this.front)
  83911. this.front = new Node();
  83912. this.front.build(front);
  83913. }
  83914. if (back.length) {
  83915. if (!this.back)
  83916. this.back = new Node();
  83917. this.back.build(back);
  83918. }
  83919. };
  83920. return Node;
  83921. }());
  83922. var CSG = /** @class */ (function () {
  83923. function CSG() {
  83924. this.polygons = new Array();
  83925. }
  83926. // Convert BABYLON.Mesh to BABYLON.CSG
  83927. CSG.FromMesh = function (mesh) {
  83928. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83929. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83930. if (mesh instanceof BABYLON.Mesh) {
  83931. mesh.computeWorldMatrix(true);
  83932. matrix = mesh.getWorldMatrix();
  83933. meshPosition = mesh.position.clone();
  83934. meshRotation = mesh.rotation.clone();
  83935. if (mesh.rotationQuaternion) {
  83936. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83937. }
  83938. meshScaling = mesh.scaling.clone();
  83939. }
  83940. else {
  83941. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83942. }
  83943. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83944. var subMeshes = mesh.subMeshes;
  83945. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83946. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83947. vertices = [];
  83948. for (var j = 0; j < 3; j++) {
  83949. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83950. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83951. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83952. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83953. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83954. vertex = new Vertex(position, normal, uv);
  83955. vertices.push(vertex);
  83956. }
  83957. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83958. // To handle the case of degenerated triangle
  83959. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83960. if (polygon.plane)
  83961. polygons.push(polygon);
  83962. }
  83963. }
  83964. var csg = CSG.FromPolygons(polygons);
  83965. csg.matrix = matrix;
  83966. csg.position = meshPosition;
  83967. csg.rotation = meshRotation;
  83968. csg.scaling = meshScaling;
  83969. csg.rotationQuaternion = meshRotationQuaternion;
  83970. currentCSGMeshId++;
  83971. return csg;
  83972. };
  83973. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83974. CSG.FromPolygons = function (polygons) {
  83975. var csg = new CSG();
  83976. csg.polygons = polygons;
  83977. return csg;
  83978. };
  83979. CSG.prototype.clone = function () {
  83980. var csg = new CSG();
  83981. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83982. csg.copyTransformAttributes(this);
  83983. return csg;
  83984. };
  83985. CSG.prototype.union = function (csg) {
  83986. var a = new Node(this.clone().polygons);
  83987. var b = new Node(csg.clone().polygons);
  83988. a.clipTo(b);
  83989. b.clipTo(a);
  83990. b.invert();
  83991. b.clipTo(a);
  83992. b.invert();
  83993. a.build(b.allPolygons());
  83994. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83995. };
  83996. CSG.prototype.unionInPlace = function (csg) {
  83997. var a = new Node(this.polygons);
  83998. var b = new Node(csg.polygons);
  83999. a.clipTo(b);
  84000. b.clipTo(a);
  84001. b.invert();
  84002. b.clipTo(a);
  84003. b.invert();
  84004. a.build(b.allPolygons());
  84005. this.polygons = a.allPolygons();
  84006. };
  84007. CSG.prototype.subtract = function (csg) {
  84008. var a = new Node(this.clone().polygons);
  84009. var b = new Node(csg.clone().polygons);
  84010. a.invert();
  84011. a.clipTo(b);
  84012. b.clipTo(a);
  84013. b.invert();
  84014. b.clipTo(a);
  84015. b.invert();
  84016. a.build(b.allPolygons());
  84017. a.invert();
  84018. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84019. };
  84020. CSG.prototype.subtractInPlace = function (csg) {
  84021. var a = new Node(this.polygons);
  84022. var b = new Node(csg.polygons);
  84023. a.invert();
  84024. a.clipTo(b);
  84025. b.clipTo(a);
  84026. b.invert();
  84027. b.clipTo(a);
  84028. b.invert();
  84029. a.build(b.allPolygons());
  84030. a.invert();
  84031. this.polygons = a.allPolygons();
  84032. };
  84033. CSG.prototype.intersect = function (csg) {
  84034. var a = new Node(this.clone().polygons);
  84035. var b = new Node(csg.clone().polygons);
  84036. a.invert();
  84037. b.clipTo(a);
  84038. b.invert();
  84039. a.clipTo(b);
  84040. b.clipTo(a);
  84041. a.build(b.allPolygons());
  84042. a.invert();
  84043. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84044. };
  84045. CSG.prototype.intersectInPlace = function (csg) {
  84046. var a = new Node(this.polygons);
  84047. var b = new Node(csg.polygons);
  84048. a.invert();
  84049. b.clipTo(a);
  84050. b.invert();
  84051. a.clipTo(b);
  84052. b.clipTo(a);
  84053. a.build(b.allPolygons());
  84054. a.invert();
  84055. this.polygons = a.allPolygons();
  84056. };
  84057. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84058. // not modified.
  84059. CSG.prototype.inverse = function () {
  84060. var csg = this.clone();
  84061. csg.inverseInPlace();
  84062. return csg;
  84063. };
  84064. CSG.prototype.inverseInPlace = function () {
  84065. this.polygons.map(function (p) { p.flip(); });
  84066. };
  84067. // This is used to keep meshes transformations so they can be restored
  84068. // when we build back a Babylon Mesh
  84069. // NB : All CSG operations are performed in world coordinates
  84070. CSG.prototype.copyTransformAttributes = function (csg) {
  84071. this.matrix = csg.matrix;
  84072. this.position = csg.position;
  84073. this.rotation = csg.rotation;
  84074. this.scaling = csg.scaling;
  84075. this.rotationQuaternion = csg.rotationQuaternion;
  84076. return this;
  84077. };
  84078. // Build Raw mesh from CSG
  84079. // Coordinates here are in world space
  84080. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84081. var matrix = this.matrix.clone();
  84082. matrix.invert();
  84083. 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;
  84084. if (keepSubMeshes) {
  84085. // Sort Polygons, since subMeshes are indices range
  84086. polygons.sort(function (a, b) {
  84087. if (a.shared.meshId === b.shared.meshId) {
  84088. return a.shared.subMeshId - b.shared.subMeshId;
  84089. }
  84090. else {
  84091. return a.shared.meshId - b.shared.meshId;
  84092. }
  84093. });
  84094. }
  84095. for (var i = 0, il = polygons.length; i < il; i++) {
  84096. polygon = polygons[i];
  84097. // Building SubMeshes
  84098. if (!subMesh_dict[polygon.shared.meshId]) {
  84099. subMesh_dict[polygon.shared.meshId] = {};
  84100. }
  84101. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84102. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84103. indexStart: +Infinity,
  84104. indexEnd: -Infinity,
  84105. materialIndex: polygon.shared.materialIndex
  84106. };
  84107. }
  84108. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84109. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84110. polygonIndices[0] = 0;
  84111. polygonIndices[1] = j - 1;
  84112. polygonIndices[2] = j;
  84113. for (var k = 0; k < 3; k++) {
  84114. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84115. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84116. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84117. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84118. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84119. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84120. // Check if 2 points can be merged
  84121. if (!(typeof vertex_idx !== 'undefined' &&
  84122. normals[vertex_idx * 3] === localNormal.x &&
  84123. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84124. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84125. uvs[vertex_idx * 2] === uv.x &&
  84126. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84127. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84128. uvs.push(uv.x, uv.y);
  84129. normals.push(normal.x, normal.y, normal.z);
  84130. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84131. }
  84132. indices.push(vertex_idx);
  84133. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84134. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84135. currentIndex++;
  84136. }
  84137. }
  84138. }
  84139. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84140. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84141. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84142. mesh.setIndices(indices, null);
  84143. if (keepSubMeshes) {
  84144. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84145. var materialIndexOffset = 0, materialMaxIndex;
  84146. mesh.subMeshes = new Array();
  84147. for (var m in subMesh_dict) {
  84148. materialMaxIndex = -1;
  84149. for (var sm in subMesh_dict[m]) {
  84150. subMesh_obj = subMesh_dict[m][sm];
  84151. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84152. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84153. }
  84154. materialIndexOffset += ++materialMaxIndex;
  84155. }
  84156. }
  84157. return mesh;
  84158. };
  84159. // Build Mesh from CSG taking material and transforms into account
  84160. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84161. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84162. mesh.material = material;
  84163. mesh.position.copyFrom(this.position);
  84164. mesh.rotation.copyFrom(this.rotation);
  84165. if (this.rotationQuaternion) {
  84166. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84167. }
  84168. mesh.scaling.copyFrom(this.scaling);
  84169. mesh.computeWorldMatrix(true);
  84170. return mesh;
  84171. };
  84172. return CSG;
  84173. }());
  84174. BABYLON.CSG = CSG;
  84175. })(BABYLON || (BABYLON = {}));
  84176. //# sourceMappingURL=babylon.csg.js.map
  84177. var BABYLON;
  84178. (function (BABYLON) {
  84179. var LensFlare = /** @class */ (function () {
  84180. function LensFlare(size, position, color, imgUrl, system) {
  84181. this.size = size;
  84182. this.position = position;
  84183. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84184. this.color = color || new BABYLON.Color3(1, 1, 1);
  84185. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84186. this._system = system;
  84187. system.lensFlares.push(this);
  84188. }
  84189. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84190. return new LensFlare(size, position, color, imgUrl, system);
  84191. };
  84192. LensFlare.prototype.dispose = function () {
  84193. if (this.texture) {
  84194. this.texture.dispose();
  84195. }
  84196. // Remove from scene
  84197. var index = this._system.lensFlares.indexOf(this);
  84198. this._system.lensFlares.splice(index, 1);
  84199. };
  84200. ;
  84201. return LensFlare;
  84202. }());
  84203. BABYLON.LensFlare = LensFlare;
  84204. })(BABYLON || (BABYLON = {}));
  84205. //# sourceMappingURL=babylon.lensFlare.js.map
  84206. var BABYLON;
  84207. (function (BABYLON) {
  84208. // Adds the parser to the scene parsers.
  84209. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84210. // Lens flares
  84211. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84212. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84213. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84214. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84215. container.lensFlareSystems.push(lf);
  84216. }
  84217. }
  84218. });
  84219. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84220. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84221. if (this.lensFlareSystems[index].name === name) {
  84222. return this.lensFlareSystems[index];
  84223. }
  84224. }
  84225. return null;
  84226. };
  84227. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84228. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84229. if (this.lensFlareSystems[index].id === id) {
  84230. return this.lensFlareSystems[index];
  84231. }
  84232. }
  84233. return null;
  84234. };
  84235. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84236. var index = this.lensFlareSystems.indexOf(toRemove);
  84237. if (index !== -1) {
  84238. this.lensFlareSystems.splice(index, 1);
  84239. }
  84240. return index;
  84241. };
  84242. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84243. this.lensFlareSystems.push(newLensFlareSystem);
  84244. };
  84245. /**
  84246. * Defines the lens flare scene component responsible to manage any lens flares
  84247. * in a given scene.
  84248. */
  84249. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84250. /**
  84251. * Creates a new instance of the component for the given scene
  84252. * @param scene Defines the scene to register the component in
  84253. */
  84254. function LensFlareSystemSceneComponent(scene) {
  84255. /**
  84256. * The component name helpfull to identify the component in the list of scene components.
  84257. */
  84258. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84259. this.scene = scene;
  84260. scene.lensFlareSystems = new Array();
  84261. }
  84262. /**
  84263. * Registers the component in a given scene
  84264. */
  84265. LensFlareSystemSceneComponent.prototype.register = function () {
  84266. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84267. };
  84268. /**
  84269. * Rebuilds the elements related to this component in case of
  84270. * context lost for instance.
  84271. */
  84272. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84273. // Nothing to do for lens flare
  84274. };
  84275. /**
  84276. * Adds all the element from the container to the scene
  84277. * @param container the container holding the elements
  84278. */
  84279. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84280. var _this = this;
  84281. if (!container.lensFlareSystems) {
  84282. return;
  84283. }
  84284. container.lensFlareSystems.forEach(function (o) {
  84285. _this.scene.addLensFlareSystem(o);
  84286. });
  84287. };
  84288. /**
  84289. * Removes all the elements in the container from the scene
  84290. * @param container contains the elements to remove
  84291. */
  84292. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84293. var _this = this;
  84294. if (!container.lensFlareSystems) {
  84295. return;
  84296. }
  84297. container.lensFlareSystems.forEach(function (o) {
  84298. _this.scene.removeLensFlareSystem(o);
  84299. });
  84300. };
  84301. /**
  84302. * Serializes the component data to the specified json object
  84303. * @param serializationObject The object to serialize to
  84304. */
  84305. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84306. // Lens flares
  84307. serializationObject.lensFlareSystems = [];
  84308. var lensFlareSystems = this.scene.lensFlareSystems;
  84309. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84310. var lensFlareSystem = lensFlareSystems_1[_i];
  84311. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84312. }
  84313. };
  84314. /**
  84315. * Disposes the component and the associated ressources.
  84316. */
  84317. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84318. var lensFlareSystems = this.scene.lensFlareSystems;
  84319. while (lensFlareSystems.length) {
  84320. lensFlareSystems[0].dispose();
  84321. }
  84322. };
  84323. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84324. // Lens flares
  84325. if (this.scene.lensFlaresEnabled) {
  84326. var lensFlareSystems = this.scene.lensFlareSystems;
  84327. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84328. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84329. var lensFlareSystem = lensFlareSystems_2[_i];
  84330. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84331. lensFlareSystem.render();
  84332. }
  84333. }
  84334. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84335. }
  84336. };
  84337. return LensFlareSystemSceneComponent;
  84338. }());
  84339. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84340. })(BABYLON || (BABYLON = {}));
  84341. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84342. var BABYLON;
  84343. (function (BABYLON) {
  84344. var LensFlareSystem = /** @class */ (function () {
  84345. function LensFlareSystem(name, emitter, scene) {
  84346. this.name = name;
  84347. this.lensFlares = new Array();
  84348. this.borderLimit = 300;
  84349. this.viewportBorder = 0;
  84350. this.layerMask = 0x0FFFFFFF;
  84351. this._vertexBuffers = {};
  84352. this._isEnabled = true;
  84353. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84354. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84355. if (!component) {
  84356. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84357. scene._addComponent(component);
  84358. }
  84359. this._emitter = emitter;
  84360. this.id = name;
  84361. scene.lensFlareSystems.push(this);
  84362. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84363. var engine = scene.getEngine();
  84364. // VBO
  84365. var vertices = [];
  84366. vertices.push(1, 1);
  84367. vertices.push(-1, 1);
  84368. vertices.push(-1, -1);
  84369. vertices.push(1, -1);
  84370. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84371. // Indices
  84372. var indices = [];
  84373. indices.push(0);
  84374. indices.push(1);
  84375. indices.push(2);
  84376. indices.push(0);
  84377. indices.push(2);
  84378. indices.push(3);
  84379. this._indexBuffer = engine.createIndexBuffer(indices);
  84380. // Effects
  84381. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84382. }
  84383. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84384. get: function () {
  84385. return this._isEnabled;
  84386. },
  84387. set: function (value) {
  84388. this._isEnabled = value;
  84389. },
  84390. enumerable: true,
  84391. configurable: true
  84392. });
  84393. LensFlareSystem.prototype.getScene = function () {
  84394. return this._scene;
  84395. };
  84396. LensFlareSystem.prototype.getEmitter = function () {
  84397. return this._emitter;
  84398. };
  84399. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84400. this._emitter = newEmitter;
  84401. };
  84402. LensFlareSystem.prototype.getEmitterPosition = function () {
  84403. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84404. };
  84405. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84406. var position = this.getEmitterPosition();
  84407. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84408. this._positionX = position.x;
  84409. this._positionY = position.y;
  84410. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84411. if (this.viewportBorder > 0) {
  84412. globalViewport.x -= this.viewportBorder;
  84413. globalViewport.y -= this.viewportBorder;
  84414. globalViewport.width += this.viewportBorder * 2;
  84415. globalViewport.height += this.viewportBorder * 2;
  84416. position.x += this.viewportBorder;
  84417. position.y += this.viewportBorder;
  84418. this._positionX += this.viewportBorder;
  84419. this._positionY += this.viewportBorder;
  84420. }
  84421. if (position.z > 0) {
  84422. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84423. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84424. return true;
  84425. }
  84426. return true;
  84427. }
  84428. return false;
  84429. };
  84430. LensFlareSystem.prototype._isVisible = function () {
  84431. if (!this._isEnabled || !this._scene.activeCamera) {
  84432. return false;
  84433. }
  84434. var emitterPosition = this.getEmitterPosition();
  84435. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84436. var distance = direction.length();
  84437. direction.normalize();
  84438. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84439. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84440. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84441. };
  84442. LensFlareSystem.prototype.render = function () {
  84443. if (!this._effect.isReady() || !this._scene.activeCamera)
  84444. return false;
  84445. var engine = this._scene.getEngine();
  84446. var viewport = this._scene.activeCamera.viewport;
  84447. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84448. // Position
  84449. if (!this.computeEffectivePosition(globalViewport)) {
  84450. return false;
  84451. }
  84452. // Visibility
  84453. if (!this._isVisible()) {
  84454. return false;
  84455. }
  84456. // Intensity
  84457. var awayX;
  84458. var awayY;
  84459. if (this._positionX < this.borderLimit + globalViewport.x) {
  84460. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84461. }
  84462. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84463. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84464. }
  84465. else {
  84466. awayX = 0;
  84467. }
  84468. if (this._positionY < this.borderLimit + globalViewport.y) {
  84469. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84470. }
  84471. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84472. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84473. }
  84474. else {
  84475. awayY = 0;
  84476. }
  84477. var away = (awayX > awayY) ? awayX : awayY;
  84478. away -= this.viewportBorder;
  84479. if (away > this.borderLimit) {
  84480. away = this.borderLimit;
  84481. }
  84482. var intensity = 1.0 - (away / this.borderLimit);
  84483. if (intensity < 0) {
  84484. return false;
  84485. }
  84486. if (intensity > 1.0) {
  84487. intensity = 1.0;
  84488. }
  84489. if (this.viewportBorder > 0) {
  84490. globalViewport.x += this.viewportBorder;
  84491. globalViewport.y += this.viewportBorder;
  84492. globalViewport.width -= this.viewportBorder * 2;
  84493. globalViewport.height -= this.viewportBorder * 2;
  84494. this._positionX -= this.viewportBorder;
  84495. this._positionY -= this.viewportBorder;
  84496. }
  84497. // Position
  84498. var centerX = globalViewport.x + globalViewport.width / 2;
  84499. var centerY = globalViewport.y + globalViewport.height / 2;
  84500. var distX = centerX - this._positionX;
  84501. var distY = centerY - this._positionY;
  84502. // Effects
  84503. engine.enableEffect(this._effect);
  84504. engine.setState(false);
  84505. engine.setDepthBuffer(false);
  84506. // VBOs
  84507. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84508. // Flares
  84509. for (var index = 0; index < this.lensFlares.length; index++) {
  84510. var flare = this.lensFlares[index];
  84511. engine.setAlphaMode(flare.alphaMode);
  84512. var x = centerX - (distX * flare.position);
  84513. var y = centerY - (distY * flare.position);
  84514. var cw = flare.size;
  84515. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84516. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84517. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84518. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84519. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84520. // Texture
  84521. this._effect.setTexture("textureSampler", flare.texture);
  84522. // Color
  84523. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84524. // Draw order
  84525. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84526. }
  84527. engine.setDepthBuffer(true);
  84528. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84529. return true;
  84530. };
  84531. LensFlareSystem.prototype.dispose = function () {
  84532. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84533. if (vertexBuffer) {
  84534. vertexBuffer.dispose();
  84535. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84536. }
  84537. if (this._indexBuffer) {
  84538. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84539. this._indexBuffer = null;
  84540. }
  84541. while (this.lensFlares.length) {
  84542. this.lensFlares[0].dispose();
  84543. }
  84544. // Remove from scene
  84545. var index = this._scene.lensFlareSystems.indexOf(this);
  84546. this._scene.lensFlareSystems.splice(index, 1);
  84547. };
  84548. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84549. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84550. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84551. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84552. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84553. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84554. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84555. var parsedFlare = parsedLensFlareSystem.flares[index];
  84556. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84557. }
  84558. return lensFlareSystem;
  84559. };
  84560. LensFlareSystem.prototype.serialize = function () {
  84561. var serializationObject = {};
  84562. serializationObject.id = this.id;
  84563. serializationObject.name = this.name;
  84564. serializationObject.emitterId = this.getEmitter().id;
  84565. serializationObject.borderLimit = this.borderLimit;
  84566. serializationObject.flares = [];
  84567. for (var index = 0; index < this.lensFlares.length; index++) {
  84568. var flare = this.lensFlares[index];
  84569. serializationObject.flares.push({
  84570. size: flare.size,
  84571. position: flare.position,
  84572. color: flare.color.asArray(),
  84573. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84574. });
  84575. }
  84576. return serializationObject;
  84577. };
  84578. return LensFlareSystem;
  84579. }());
  84580. BABYLON.LensFlareSystem = LensFlareSystem;
  84581. })(BABYLON || (BABYLON = {}));
  84582. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84583. var BABYLON;
  84584. (function (BABYLON) {
  84585. /**
  84586. * This is a holder class for the physics joint created by the physics plugin.
  84587. * It holds a set of functions to control the underlying joint.
  84588. */
  84589. var PhysicsJoint = /** @class */ (function () {
  84590. function PhysicsJoint(type, jointData) {
  84591. this.type = type;
  84592. this.jointData = jointData;
  84593. jointData.nativeParams = jointData.nativeParams || {};
  84594. }
  84595. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84596. get: function () {
  84597. return this._physicsJoint;
  84598. },
  84599. set: function (newJoint) {
  84600. if (this._physicsJoint) {
  84601. //remove from the wolrd
  84602. }
  84603. this._physicsJoint = newJoint;
  84604. },
  84605. enumerable: true,
  84606. configurable: true
  84607. });
  84608. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84609. set: function (physicsPlugin) {
  84610. this._physicsPlugin = physicsPlugin;
  84611. },
  84612. enumerable: true,
  84613. configurable: true
  84614. });
  84615. /**
  84616. * Execute a function that is physics-plugin specific.
  84617. * @param {Function} func the function that will be executed.
  84618. * It accepts two parameters: the physics world and the physics joint.
  84619. */
  84620. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84621. func(this._physicsPlugin.world, this._physicsJoint);
  84622. };
  84623. //TODO check if the native joints are the same
  84624. //Joint Types
  84625. PhysicsJoint.DistanceJoint = 0;
  84626. PhysicsJoint.HingeJoint = 1;
  84627. PhysicsJoint.BallAndSocketJoint = 2;
  84628. PhysicsJoint.WheelJoint = 3;
  84629. PhysicsJoint.SliderJoint = 4;
  84630. //OIMO
  84631. PhysicsJoint.PrismaticJoint = 5;
  84632. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84633. PhysicsJoint.UniversalJoint = 6;
  84634. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84635. //Cannon
  84636. //Similar to a Ball-Joint. Different in params
  84637. PhysicsJoint.PointToPointJoint = 8;
  84638. //Cannon only at the moment
  84639. PhysicsJoint.SpringJoint = 9;
  84640. PhysicsJoint.LockJoint = 10;
  84641. return PhysicsJoint;
  84642. }());
  84643. BABYLON.PhysicsJoint = PhysicsJoint;
  84644. /**
  84645. * A class representing a physics distance joint.
  84646. */
  84647. var DistanceJoint = /** @class */ (function (_super) {
  84648. __extends(DistanceJoint, _super);
  84649. function DistanceJoint(jointData) {
  84650. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84651. }
  84652. /**
  84653. * Update the predefined distance.
  84654. */
  84655. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84656. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84657. };
  84658. return DistanceJoint;
  84659. }(PhysicsJoint));
  84660. BABYLON.DistanceJoint = DistanceJoint;
  84661. var MotorEnabledJoint = /** @class */ (function (_super) {
  84662. __extends(MotorEnabledJoint, _super);
  84663. function MotorEnabledJoint(type, jointData) {
  84664. return _super.call(this, type, jointData) || this;
  84665. }
  84666. /**
  84667. * Set the motor values.
  84668. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84669. * @param {number} force the force to apply
  84670. * @param {number} maxForce max force for this motor.
  84671. */
  84672. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84673. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84674. };
  84675. /**
  84676. * Set the motor's limits.
  84677. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84678. */
  84679. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84680. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84681. };
  84682. return MotorEnabledJoint;
  84683. }(PhysicsJoint));
  84684. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84685. /**
  84686. * This class represents a single hinge physics joint
  84687. */
  84688. var HingeJoint = /** @class */ (function (_super) {
  84689. __extends(HingeJoint, _super);
  84690. function HingeJoint(jointData) {
  84691. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84692. }
  84693. /**
  84694. * Set the motor values.
  84695. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84696. * @param {number} force the force to apply
  84697. * @param {number} maxForce max force for this motor.
  84698. */
  84699. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84700. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84701. };
  84702. /**
  84703. * Set the motor's limits.
  84704. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84705. */
  84706. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84707. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84708. };
  84709. return HingeJoint;
  84710. }(MotorEnabledJoint));
  84711. BABYLON.HingeJoint = HingeJoint;
  84712. /**
  84713. * This class represents a dual hinge physics joint (same as wheel joint)
  84714. */
  84715. var Hinge2Joint = /** @class */ (function (_super) {
  84716. __extends(Hinge2Joint, _super);
  84717. function Hinge2Joint(jointData) {
  84718. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84719. }
  84720. /**
  84721. * Set the motor values.
  84722. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84723. * @param {number} force the force to apply
  84724. * @param {number} maxForce max force for this motor.
  84725. * @param {motorIndex} the motor's index, 0 or 1.
  84726. */
  84727. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84728. if (motorIndex === void 0) { motorIndex = 0; }
  84729. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84730. };
  84731. /**
  84732. * Set the motor limits.
  84733. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84734. * @param {number} upperLimit the upper limit
  84735. * @param {number} lowerLimit lower limit
  84736. * @param {motorIndex} the motor's index, 0 or 1.
  84737. */
  84738. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84739. if (motorIndex === void 0) { motorIndex = 0; }
  84740. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84741. };
  84742. return Hinge2Joint;
  84743. }(MotorEnabledJoint));
  84744. BABYLON.Hinge2Joint = Hinge2Joint;
  84745. })(BABYLON || (BABYLON = {}));
  84746. //# sourceMappingURL=babylon.physicsJoint.js.map
  84747. var BABYLON;
  84748. (function (BABYLON) {
  84749. var PhysicsImpostor = /** @class */ (function () {
  84750. function PhysicsImpostor(object, type, _options, _scene) {
  84751. if (_options === void 0) { _options = { mass: 0 }; }
  84752. var _this = this;
  84753. this.object = object;
  84754. this.type = type;
  84755. this._options = _options;
  84756. this._scene = _scene;
  84757. this._bodyUpdateRequired = false;
  84758. this._onBeforePhysicsStepCallbacks = new Array();
  84759. this._onAfterPhysicsStepCallbacks = new Array();
  84760. this._onPhysicsCollideCallbacks = [];
  84761. this._deltaPosition = BABYLON.Vector3.Zero();
  84762. this._isDisposed = false;
  84763. //temp variables for parent rotation calculations
  84764. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84765. this._tmpQuat = new BABYLON.Quaternion();
  84766. this._tmpQuat2 = new BABYLON.Quaternion();
  84767. /**
  84768. * this function is executed by the physics engine.
  84769. */
  84770. this.beforeStep = function () {
  84771. if (!_this._physicsEngine) {
  84772. return;
  84773. }
  84774. _this.object.translate(_this._deltaPosition, -1);
  84775. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84776. _this.object.computeWorldMatrix(false);
  84777. if (_this.object.parent && _this.object.rotationQuaternion) {
  84778. _this.getParentsRotation();
  84779. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84780. }
  84781. else {
  84782. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84783. }
  84784. if (!_this._options.disableBidirectionalTransformation) {
  84785. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84786. }
  84787. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84788. func(_this);
  84789. });
  84790. };
  84791. /**
  84792. * this function is executed by the physics engine.
  84793. */
  84794. this.afterStep = function () {
  84795. if (!_this._physicsEngine) {
  84796. return;
  84797. }
  84798. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84799. func(_this);
  84800. });
  84801. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84802. // object has now its world rotation. needs to be converted to local.
  84803. if (_this.object.parent && _this.object.rotationQuaternion) {
  84804. _this.getParentsRotation();
  84805. _this._tmpQuat.conjugateInPlace();
  84806. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84807. }
  84808. // take the position set and make it the absolute position of this object.
  84809. _this.object.setAbsolutePosition(_this.object.position);
  84810. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84811. _this.object.translate(_this._deltaPosition, 1);
  84812. };
  84813. /**
  84814. * Legacy collision detection event support
  84815. */
  84816. this.onCollideEvent = null;
  84817. //event and body object due to cannon's event-based architecture.
  84818. this.onCollide = function (e) {
  84819. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84820. return;
  84821. }
  84822. if (!_this._physicsEngine) {
  84823. return;
  84824. }
  84825. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84826. if (otherImpostor) {
  84827. // Legacy collision detection event support
  84828. if (_this.onCollideEvent) {
  84829. _this.onCollideEvent(_this, otherImpostor);
  84830. }
  84831. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84832. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84833. }).forEach(function (obj) {
  84834. obj.callback(_this, otherImpostor);
  84835. });
  84836. }
  84837. };
  84838. //sanity check!
  84839. if (!this.object) {
  84840. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84841. return;
  84842. }
  84843. //legacy support for old syntax.
  84844. if (!this._scene && object.getScene) {
  84845. this._scene = object.getScene();
  84846. }
  84847. if (!this._scene) {
  84848. return;
  84849. }
  84850. this._physicsEngine = this._scene.getPhysicsEngine();
  84851. if (!this._physicsEngine) {
  84852. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84853. }
  84854. else {
  84855. //set the object's quaternion, if not set
  84856. if (!this.object.rotationQuaternion) {
  84857. if (this.object.rotation) {
  84858. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84859. }
  84860. else {
  84861. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84862. }
  84863. }
  84864. //default options params
  84865. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84866. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84867. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84868. this._joints = [];
  84869. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84870. if (!this.object.parent || this._options.ignoreParent) {
  84871. this._init();
  84872. }
  84873. else if (this.object.parent.physicsImpostor) {
  84874. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84875. }
  84876. }
  84877. }
  84878. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84879. get: function () {
  84880. return this._isDisposed;
  84881. },
  84882. enumerable: true,
  84883. configurable: true
  84884. });
  84885. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84886. get: function () {
  84887. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84888. },
  84889. set: function (value) {
  84890. this.setMass(value);
  84891. },
  84892. enumerable: true,
  84893. configurable: true
  84894. });
  84895. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84896. get: function () {
  84897. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84898. },
  84899. set: function (value) {
  84900. if (!this._physicsEngine) {
  84901. return;
  84902. }
  84903. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84904. },
  84905. enumerable: true,
  84906. configurable: true
  84907. });
  84908. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84909. get: function () {
  84910. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84911. },
  84912. set: function (value) {
  84913. if (!this._physicsEngine) {
  84914. return;
  84915. }
  84916. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84917. },
  84918. enumerable: true,
  84919. configurable: true
  84920. });
  84921. /**
  84922. * This function will completly initialize this impostor.
  84923. * It will create a new body - but only if this mesh has no parent.
  84924. * If it has, this impostor will not be used other than to define the impostor
  84925. * of the child mesh.
  84926. */
  84927. PhysicsImpostor.prototype._init = function () {
  84928. if (!this._physicsEngine) {
  84929. return;
  84930. }
  84931. this._physicsEngine.removeImpostor(this);
  84932. this.physicsBody = null;
  84933. this._parent = this._parent || this._getPhysicsParent();
  84934. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84935. this._physicsEngine.addImpostor(this);
  84936. }
  84937. };
  84938. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84939. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84940. var parentMesh = this.object.parent;
  84941. return parentMesh.physicsImpostor;
  84942. }
  84943. return null;
  84944. };
  84945. /**
  84946. * Should a new body be generated.
  84947. */
  84948. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84949. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84950. };
  84951. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84952. this.forceUpdate();
  84953. };
  84954. /**
  84955. * Force a regeneration of this or the parent's impostor's body.
  84956. * Use under cautious - This will remove all joints already implemented.
  84957. */
  84958. PhysicsImpostor.prototype.forceUpdate = function () {
  84959. this._init();
  84960. if (this.parent && !this._options.ignoreParent) {
  84961. this.parent.forceUpdate();
  84962. }
  84963. };
  84964. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84965. /*public get mesh(): AbstractMesh {
  84966. return this._mesh;
  84967. }*/
  84968. /**
  84969. * Gets the body that holds this impostor. Either its own, or its parent.
  84970. */
  84971. get: function () {
  84972. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84973. },
  84974. /**
  84975. * Set the physics body. Used mainly by the physics engine/plugin
  84976. */
  84977. set: function (physicsBody) {
  84978. if (this._physicsBody && this._physicsEngine) {
  84979. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84980. }
  84981. this._physicsBody = physicsBody;
  84982. this.resetUpdateFlags();
  84983. },
  84984. enumerable: true,
  84985. configurable: true
  84986. });
  84987. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84988. get: function () {
  84989. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84990. },
  84991. set: function (value) {
  84992. this._parent = value;
  84993. },
  84994. enumerable: true,
  84995. configurable: true
  84996. });
  84997. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84998. this._bodyUpdateRequired = false;
  84999. };
  85000. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85001. if (this.object.getBoundingInfo) {
  85002. var q = this.object.rotationQuaternion;
  85003. //reset rotation
  85004. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85005. //calculate the world matrix with no rotation
  85006. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85007. var boundingInfo = this.object.getBoundingInfo();
  85008. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85009. //bring back the rotation
  85010. this.object.rotationQuaternion = q;
  85011. //calculate the world matrix with the new rotation
  85012. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85013. return size;
  85014. }
  85015. else {
  85016. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85017. }
  85018. };
  85019. PhysicsImpostor.prototype.getObjectCenter = function () {
  85020. if (this.object.getBoundingInfo) {
  85021. var boundingInfo = this.object.getBoundingInfo();
  85022. return boundingInfo.boundingBox.centerWorld;
  85023. }
  85024. else {
  85025. return this.object.position;
  85026. }
  85027. };
  85028. /**
  85029. * Get a specific parametes from the options parameter.
  85030. */
  85031. PhysicsImpostor.prototype.getParam = function (paramName) {
  85032. return this._options[paramName];
  85033. };
  85034. /**
  85035. * Sets a specific parameter in the options given to the physics plugin
  85036. */
  85037. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85038. this._options[paramName] = value;
  85039. this._bodyUpdateRequired = true;
  85040. };
  85041. /**
  85042. * Specifically change the body's mass option. Won't recreate the physics body object
  85043. */
  85044. PhysicsImpostor.prototype.setMass = function (mass) {
  85045. if (this.getParam("mass") !== mass) {
  85046. this.setParam("mass", mass);
  85047. }
  85048. if (this._physicsEngine) {
  85049. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85050. }
  85051. };
  85052. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85053. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85054. };
  85055. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85056. if (this._physicsEngine) {
  85057. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85058. }
  85059. };
  85060. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85061. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85062. };
  85063. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85064. if (this._physicsEngine) {
  85065. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85066. }
  85067. };
  85068. /**
  85069. * Execute a function with the physics plugin native code.
  85070. * Provide a function the will have two variables - the world object and the physics body object.
  85071. */
  85072. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85073. if (this._physicsEngine) {
  85074. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85075. }
  85076. };
  85077. /**
  85078. * Register a function that will be executed before the physics world is stepping forward.
  85079. */
  85080. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85081. this._onBeforePhysicsStepCallbacks.push(func);
  85082. };
  85083. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85084. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85085. if (index > -1) {
  85086. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85087. }
  85088. else {
  85089. BABYLON.Tools.Warn("Function to remove was not found");
  85090. }
  85091. };
  85092. /**
  85093. * Register a function that will be executed after the physics step
  85094. */
  85095. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85096. this._onAfterPhysicsStepCallbacks.push(func);
  85097. };
  85098. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85099. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85100. if (index > -1) {
  85101. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85102. }
  85103. else {
  85104. BABYLON.Tools.Warn("Function to remove was not found");
  85105. }
  85106. };
  85107. /**
  85108. * register a function that will be executed when this impostor collides against a different body.
  85109. */
  85110. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85111. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85112. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85113. };
  85114. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85115. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85116. var index = -1;
  85117. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85118. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85119. // chcek the arrays match
  85120. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85121. return collidedAgainstList.indexOf(impostor) > -1;
  85122. });
  85123. if (sameList) {
  85124. index = idx;
  85125. }
  85126. return sameList;
  85127. }
  85128. return false;
  85129. });
  85130. if (found) {
  85131. this._onPhysicsCollideCallbacks.splice(index, 1);
  85132. }
  85133. else {
  85134. BABYLON.Tools.Warn("Function to remove was not found");
  85135. }
  85136. };
  85137. PhysicsImpostor.prototype.getParentsRotation = function () {
  85138. var parent = this.object.parent;
  85139. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85140. while (parent) {
  85141. if (parent.rotationQuaternion) {
  85142. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85143. }
  85144. else {
  85145. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85146. }
  85147. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85148. parent = parent.parent;
  85149. }
  85150. return this._tmpQuat;
  85151. };
  85152. /**
  85153. * Apply a force
  85154. */
  85155. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85156. if (this._physicsEngine) {
  85157. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85158. }
  85159. return this;
  85160. };
  85161. /**
  85162. * Apply an impulse
  85163. */
  85164. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85165. if (this._physicsEngine) {
  85166. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85167. }
  85168. return this;
  85169. };
  85170. /**
  85171. * A help function to create a joint.
  85172. */
  85173. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85174. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85175. this.addJoint(otherImpostor, joint);
  85176. return this;
  85177. };
  85178. /**
  85179. * Add a joint to this impostor with a different impostor.
  85180. */
  85181. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85182. this._joints.push({
  85183. otherImpostor: otherImpostor,
  85184. joint: joint
  85185. });
  85186. if (this._physicsEngine) {
  85187. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85188. }
  85189. return this;
  85190. };
  85191. /**
  85192. * Will keep this body still, in a sleep mode.
  85193. */
  85194. PhysicsImpostor.prototype.sleep = function () {
  85195. if (this._physicsEngine) {
  85196. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85197. }
  85198. return this;
  85199. };
  85200. /**
  85201. * Wake the body up.
  85202. */
  85203. PhysicsImpostor.prototype.wakeUp = function () {
  85204. if (this._physicsEngine) {
  85205. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85206. }
  85207. return this;
  85208. };
  85209. PhysicsImpostor.prototype.clone = function (newObject) {
  85210. if (!newObject)
  85211. return null;
  85212. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85213. };
  85214. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85215. var _this = this;
  85216. //no dispose if no physics engine is available.
  85217. if (!this._physicsEngine) {
  85218. return;
  85219. }
  85220. this._joints.forEach(function (j) {
  85221. if (_this._physicsEngine) {
  85222. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85223. }
  85224. });
  85225. //dispose the physics body
  85226. this._physicsEngine.removeImpostor(this);
  85227. if (this.parent) {
  85228. this.parent.forceUpdate();
  85229. }
  85230. else {
  85231. /*this._object.getChildMeshes().forEach(function(mesh) {
  85232. if (mesh.physicsImpostor) {
  85233. if (disposeChildren) {
  85234. mesh.physicsImpostor.dispose();
  85235. mesh.physicsImpostor = null;
  85236. }
  85237. }
  85238. })*/
  85239. }
  85240. this._isDisposed = true;
  85241. };
  85242. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85243. this._deltaPosition.copyFrom(position);
  85244. };
  85245. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85246. if (!this._deltaRotation) {
  85247. this._deltaRotation = new BABYLON.Quaternion();
  85248. }
  85249. this._deltaRotation.copyFrom(rotation);
  85250. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85251. };
  85252. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85253. if (this._physicsEngine) {
  85254. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85255. }
  85256. return this;
  85257. };
  85258. PhysicsImpostor.prototype.getRadius = function () {
  85259. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85260. };
  85261. /**
  85262. * Sync a bone with this impostor
  85263. * @param bone The bone to sync to the impostor.
  85264. * @param boneMesh The mesh that the bone is influencing.
  85265. * @param jointPivot The pivot of the joint / bone in local space.
  85266. * @param distToJoint Optional distance from the impostor to the joint.
  85267. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85268. */
  85269. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85270. var tempVec = PhysicsImpostor._tmpVecs[0];
  85271. var mesh = this.object;
  85272. if (mesh.rotationQuaternion) {
  85273. if (adjustRotation) {
  85274. var tempQuat = PhysicsImpostor._tmpQuat;
  85275. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85276. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85277. }
  85278. else {
  85279. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85280. }
  85281. }
  85282. tempVec.x = 0;
  85283. tempVec.y = 0;
  85284. tempVec.z = 0;
  85285. if (jointPivot) {
  85286. tempVec.x = jointPivot.x;
  85287. tempVec.y = jointPivot.y;
  85288. tempVec.z = jointPivot.z;
  85289. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85290. if (distToJoint === undefined || distToJoint === null) {
  85291. distToJoint = jointPivot.length();
  85292. }
  85293. tempVec.x *= distToJoint;
  85294. tempVec.y *= distToJoint;
  85295. tempVec.z *= distToJoint;
  85296. }
  85297. if (bone.getParent()) {
  85298. tempVec.addInPlace(mesh.getAbsolutePosition());
  85299. bone.setAbsolutePosition(tempVec, boneMesh);
  85300. }
  85301. else {
  85302. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85303. boneMesh.position.x -= tempVec.x;
  85304. boneMesh.position.y -= tempVec.y;
  85305. boneMesh.position.z -= tempVec.z;
  85306. }
  85307. };
  85308. /**
  85309. * Sync impostor to a bone
  85310. * @param bone The bone that the impostor will be synced to.
  85311. * @param boneMesh The mesh that the bone is influencing.
  85312. * @param jointPivot The pivot of the joint / bone in local space.
  85313. * @param distToJoint Optional distance from the impostor to the joint.
  85314. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85315. * @param boneAxis Optional vector3 axis the bone is aligned with
  85316. */
  85317. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85318. var mesh = this.object;
  85319. if (mesh.rotationQuaternion) {
  85320. if (adjustRotation) {
  85321. var tempQuat = PhysicsImpostor._tmpQuat;
  85322. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85323. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85324. }
  85325. else {
  85326. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85327. }
  85328. }
  85329. var pos = PhysicsImpostor._tmpVecs[0];
  85330. var boneDir = PhysicsImpostor._tmpVecs[1];
  85331. if (!boneAxis) {
  85332. boneAxis = PhysicsImpostor._tmpVecs[2];
  85333. boneAxis.x = 0;
  85334. boneAxis.y = 1;
  85335. boneAxis.z = 0;
  85336. }
  85337. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85338. bone.getAbsolutePositionToRef(boneMesh, pos);
  85339. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85340. distToJoint = jointPivot.length();
  85341. }
  85342. if (distToJoint !== undefined && distToJoint !== null) {
  85343. pos.x += boneDir.x * distToJoint;
  85344. pos.y += boneDir.y * distToJoint;
  85345. pos.z += boneDir.z * distToJoint;
  85346. }
  85347. mesh.setAbsolutePosition(pos);
  85348. };
  85349. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85350. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85351. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85352. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85353. //Impostor types
  85354. PhysicsImpostor.NoImpostor = 0;
  85355. PhysicsImpostor.SphereImpostor = 1;
  85356. PhysicsImpostor.BoxImpostor = 2;
  85357. PhysicsImpostor.PlaneImpostor = 3;
  85358. PhysicsImpostor.MeshImpostor = 4;
  85359. PhysicsImpostor.CylinderImpostor = 7;
  85360. PhysicsImpostor.ParticleImpostor = 8;
  85361. PhysicsImpostor.HeightmapImpostor = 9;
  85362. return PhysicsImpostor;
  85363. }());
  85364. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85365. })(BABYLON || (BABYLON = {}));
  85366. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85367. var BABYLON;
  85368. (function (BABYLON) {
  85369. var PhysicsEngine = /** @class */ (function () {
  85370. function PhysicsEngine(gravity, _physicsPlugin) {
  85371. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85372. this._physicsPlugin = _physicsPlugin;
  85373. //new methods and parameters
  85374. this._impostors = [];
  85375. this._joints = [];
  85376. if (!this._physicsPlugin.isSupported()) {
  85377. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85378. + "Please make sure it is included.");
  85379. }
  85380. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85381. this.setGravity(gravity);
  85382. this.setTimeStep();
  85383. }
  85384. PhysicsEngine.prototype.setGravity = function (gravity) {
  85385. this.gravity = gravity;
  85386. this._physicsPlugin.setGravity(this.gravity);
  85387. };
  85388. /**
  85389. * Set the time step of the physics engine.
  85390. * default is 1/60.
  85391. * To slow it down, enter 1/600 for example.
  85392. * To speed it up, 1/30
  85393. * @param {number} newTimeStep the new timestep to apply to this world.
  85394. */
  85395. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85396. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85397. this._physicsPlugin.setTimeStep(newTimeStep);
  85398. };
  85399. /**
  85400. * Get the time step of the physics engine.
  85401. */
  85402. PhysicsEngine.prototype.getTimeStep = function () {
  85403. return this._physicsPlugin.getTimeStep();
  85404. };
  85405. PhysicsEngine.prototype.dispose = function () {
  85406. this._impostors.forEach(function (impostor) {
  85407. impostor.dispose();
  85408. });
  85409. this._physicsPlugin.dispose();
  85410. };
  85411. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85412. return this._physicsPlugin.name;
  85413. };
  85414. /**
  85415. * Adding a new impostor for the impostor tracking.
  85416. * This will be done by the impostor itself.
  85417. * @param {PhysicsImpostor} impostor the impostor to add
  85418. */
  85419. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85420. impostor.uniqueId = this._impostors.push(impostor);
  85421. //if no parent, generate the body
  85422. if (!impostor.parent) {
  85423. this._physicsPlugin.generatePhysicsBody(impostor);
  85424. }
  85425. };
  85426. /**
  85427. * Remove an impostor from the engine.
  85428. * This impostor and its mesh will not longer be updated by the physics engine.
  85429. * @param {PhysicsImpostor} impostor the impostor to remove
  85430. */
  85431. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85432. var index = this._impostors.indexOf(impostor);
  85433. if (index > -1) {
  85434. var removed = this._impostors.splice(index, 1);
  85435. //Is it needed?
  85436. if (removed.length) {
  85437. //this will also remove it from the world.
  85438. removed[0].physicsBody = null;
  85439. }
  85440. }
  85441. };
  85442. /**
  85443. * Add a joint to the physics engine
  85444. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85445. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85446. * @param {PhysicsJoint} the joint that will connect both impostors.
  85447. */
  85448. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85449. var impostorJoint = {
  85450. mainImpostor: mainImpostor,
  85451. connectedImpostor: connectedImpostor,
  85452. joint: joint
  85453. };
  85454. joint.physicsPlugin = this._physicsPlugin;
  85455. this._joints.push(impostorJoint);
  85456. this._physicsPlugin.generateJoint(impostorJoint);
  85457. };
  85458. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85459. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85460. return (impostorJoint.connectedImpostor === connectedImpostor
  85461. && impostorJoint.joint === joint
  85462. && impostorJoint.mainImpostor === mainImpostor);
  85463. });
  85464. if (matchingJoints.length) {
  85465. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85466. //TODO remove it from the list as well
  85467. }
  85468. };
  85469. /**
  85470. * Called by the scene. no need to call it.
  85471. */
  85472. PhysicsEngine.prototype._step = function (delta) {
  85473. var _this = this;
  85474. //check if any mesh has no body / requires an update
  85475. this._impostors.forEach(function (impostor) {
  85476. if (impostor.isBodyInitRequired()) {
  85477. _this._physicsPlugin.generatePhysicsBody(impostor);
  85478. }
  85479. });
  85480. if (delta > 0.1) {
  85481. delta = 0.1;
  85482. }
  85483. else if (delta <= 0) {
  85484. delta = 1.0 / 60.0;
  85485. }
  85486. this._physicsPlugin.executeStep(delta, this._impostors);
  85487. };
  85488. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85489. return this._physicsPlugin;
  85490. };
  85491. PhysicsEngine.prototype.getImpostors = function () {
  85492. return this._impostors;
  85493. };
  85494. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85495. for (var i = 0; i < this._impostors.length; ++i) {
  85496. if (this._impostors[i].object === object) {
  85497. return this._impostors[i];
  85498. }
  85499. }
  85500. return null;
  85501. };
  85502. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85503. for (var i = 0; i < this._impostors.length; ++i) {
  85504. if (this._impostors[i].physicsBody === body) {
  85505. return this._impostors[i];
  85506. }
  85507. }
  85508. return null;
  85509. };
  85510. // Statics
  85511. PhysicsEngine.Epsilon = 0.001;
  85512. return PhysicsEngine;
  85513. }());
  85514. BABYLON.PhysicsEngine = PhysicsEngine;
  85515. })(BABYLON || (BABYLON = {}));
  85516. //# sourceMappingURL=babylon.physicsEngine.js.map
  85517. var BABYLON;
  85518. (function (BABYLON) {
  85519. var PhysicsHelper = /** @class */ (function () {
  85520. function PhysicsHelper(scene) {
  85521. this._scene = scene;
  85522. this._physicsEngine = this._scene.getPhysicsEngine();
  85523. if (!this._physicsEngine) {
  85524. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85525. }
  85526. }
  85527. /**
  85528. * @param {Vector3} origin the origin of the explosion
  85529. * @param {number} radius the explosion radius
  85530. * @param {number} strength the explosion strength
  85531. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85532. */
  85533. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85534. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85535. if (!this._physicsEngine) {
  85536. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85537. return null;
  85538. }
  85539. var impostors = this._physicsEngine.getImpostors();
  85540. if (impostors.length === 0) {
  85541. return null;
  85542. }
  85543. var event = new PhysicsRadialExplosionEvent(this._scene);
  85544. impostors.forEach(function (impostor) {
  85545. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85546. if (!impostorForceAndContactPoint) {
  85547. return;
  85548. }
  85549. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85550. });
  85551. event.dispose(false);
  85552. return event;
  85553. };
  85554. /**
  85555. * @param {Vector3} origin the origin of the explosion
  85556. * @param {number} radius the explosion radius
  85557. * @param {number} strength the explosion strength
  85558. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85559. */
  85560. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85561. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85562. if (!this._physicsEngine) {
  85563. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85564. return null;
  85565. }
  85566. var impostors = this._physicsEngine.getImpostors();
  85567. if (impostors.length === 0) {
  85568. return null;
  85569. }
  85570. var event = new PhysicsRadialExplosionEvent(this._scene);
  85571. impostors.forEach(function (impostor) {
  85572. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85573. if (!impostorForceAndContactPoint) {
  85574. return;
  85575. }
  85576. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85577. });
  85578. event.dispose(false);
  85579. return event;
  85580. };
  85581. /**
  85582. * @param {Vector3} origin the origin of the explosion
  85583. * @param {number} radius the explosion radius
  85584. * @param {number} strength the explosion strength
  85585. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85586. */
  85587. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85588. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85589. if (!this._physicsEngine) {
  85590. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85591. return null;
  85592. }
  85593. var impostors = this._physicsEngine.getImpostors();
  85594. if (impostors.length === 0) {
  85595. return null;
  85596. }
  85597. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85598. event.dispose(false);
  85599. return event;
  85600. };
  85601. /**
  85602. * @param {Vector3} origin the origin of the updraft
  85603. * @param {number} radius the radius of the updraft
  85604. * @param {number} strength the strength of the updraft
  85605. * @param {number} height the height of the updraft
  85606. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85607. */
  85608. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85609. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85610. if (!this._physicsEngine) {
  85611. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85612. return null;
  85613. }
  85614. if (this._physicsEngine.getImpostors().length === 0) {
  85615. return null;
  85616. }
  85617. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85618. event.dispose(false);
  85619. return event;
  85620. };
  85621. /**
  85622. * @param {Vector3} origin the of the vortex
  85623. * @param {number} radius the radius of the vortex
  85624. * @param {number} strength the strength of the vortex
  85625. * @param {number} height the height of the vortex
  85626. */
  85627. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85628. if (!this._physicsEngine) {
  85629. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85630. return null;
  85631. }
  85632. if (this._physicsEngine.getImpostors().length === 0) {
  85633. return null;
  85634. }
  85635. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85636. event.dispose(false);
  85637. return event;
  85638. };
  85639. return PhysicsHelper;
  85640. }());
  85641. BABYLON.PhysicsHelper = PhysicsHelper;
  85642. /***** Radial explosion *****/
  85643. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85644. function PhysicsRadialExplosionEvent(scene) {
  85645. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85646. this._rays = [];
  85647. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85648. this._scene = scene;
  85649. }
  85650. /**
  85651. * Returns the data related to the radial explosion event (sphere & rays).
  85652. * @returns {PhysicsRadialExplosionEventData}
  85653. */
  85654. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85655. this._dataFetched = true;
  85656. return {
  85657. sphere: this._sphere,
  85658. rays: this._rays,
  85659. };
  85660. };
  85661. /**
  85662. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85663. * @param impostor
  85664. * @param {Vector3} origin the origin of the explosion
  85665. * @param {number} radius the explosion radius
  85666. * @param {number} strength the explosion strength
  85667. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85668. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85669. */
  85670. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85671. if (impostor.mass === 0) {
  85672. return null;
  85673. }
  85674. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85675. return null;
  85676. }
  85677. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85678. return null;
  85679. }
  85680. var impostorObjectCenter = impostor.getObjectCenter();
  85681. var direction = impostorObjectCenter.subtract(origin);
  85682. var ray = new BABYLON.Ray(origin, direction, radius);
  85683. this._rays.push(ray);
  85684. var hit = ray.intersectsMesh(impostor.object);
  85685. var contactPoint = hit.pickedPoint;
  85686. if (!contactPoint) {
  85687. return null;
  85688. }
  85689. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85690. if (distanceFromOrigin > radius) {
  85691. return null;
  85692. }
  85693. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85694. ? strength
  85695. : strength * (1 - (distanceFromOrigin / radius));
  85696. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85697. return { force: force, contactPoint: contactPoint };
  85698. };
  85699. /**
  85700. * Disposes the sphere.
  85701. * @param {bolean} force
  85702. */
  85703. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85704. var _this = this;
  85705. if (force === void 0) { force = true; }
  85706. if (force) {
  85707. this._sphere.dispose();
  85708. }
  85709. else {
  85710. setTimeout(function () {
  85711. if (!_this._dataFetched) {
  85712. _this._sphere.dispose();
  85713. }
  85714. }, 0);
  85715. }
  85716. };
  85717. /*** Helpers ***/
  85718. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85719. if (!this._sphere) {
  85720. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85721. this._sphere.isVisible = false;
  85722. }
  85723. };
  85724. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85725. var impostorObject = impostor.object;
  85726. this._prepareSphere();
  85727. this._sphere.position = origin;
  85728. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85729. this._sphere._updateBoundingInfo();
  85730. this._sphere.computeWorldMatrix(true);
  85731. return this._sphere.intersectsMesh(impostorObject, true);
  85732. };
  85733. return PhysicsRadialExplosionEvent;
  85734. }());
  85735. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85736. /***** Gravitational Field *****/
  85737. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85738. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85739. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85740. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85741. this._physicsHelper = physicsHelper;
  85742. this._scene = scene;
  85743. this._origin = origin;
  85744. this._radius = radius;
  85745. this._strength = strength;
  85746. this._falloff = falloff;
  85747. this._tickCallback = this._tick.bind(this);
  85748. }
  85749. /**
  85750. * Returns the data related to the gravitational field event (sphere).
  85751. * @returns {PhysicsGravitationalFieldEventData}
  85752. */
  85753. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85754. this._dataFetched = true;
  85755. return {
  85756. sphere: this._sphere,
  85757. };
  85758. };
  85759. /**
  85760. * Enables the gravitational field.
  85761. */
  85762. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85763. this._tickCallback.call(this);
  85764. this._scene.registerBeforeRender(this._tickCallback);
  85765. };
  85766. /**
  85767. * Disables the gravitational field.
  85768. */
  85769. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85770. this._scene.unregisterBeforeRender(this._tickCallback);
  85771. };
  85772. /**
  85773. * Disposes the sphere.
  85774. * @param {bolean} force
  85775. */
  85776. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85777. var _this = this;
  85778. if (force === void 0) { force = true; }
  85779. if (force) {
  85780. this._sphere.dispose();
  85781. }
  85782. else {
  85783. setTimeout(function () {
  85784. if (!_this._dataFetched) {
  85785. _this._sphere.dispose();
  85786. }
  85787. }, 0);
  85788. }
  85789. };
  85790. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85791. // Since the params won't change, we fetch the event only once
  85792. if (this._sphere) {
  85793. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85794. }
  85795. else {
  85796. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85797. if (radialExplosionEvent) {
  85798. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85799. }
  85800. }
  85801. };
  85802. return PhysicsGravitationalFieldEvent;
  85803. }());
  85804. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85805. /***** Updraft *****/
  85806. var PhysicsUpdraftEvent = /** @class */ (function () {
  85807. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85808. this._scene = _scene;
  85809. this._origin = _origin;
  85810. this._radius = _radius;
  85811. this._strength = _strength;
  85812. this._height = _height;
  85813. this._updraftMode = _updraftMode;
  85814. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85815. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85816. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85817. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85818. this._physicsEngine = this._scene.getPhysicsEngine();
  85819. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85820. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85821. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85822. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85823. }
  85824. this._tickCallback = this._tick.bind(this);
  85825. }
  85826. /**
  85827. * Returns the data related to the updraft event (cylinder).
  85828. * @returns {PhysicsUpdraftEventData}
  85829. */
  85830. PhysicsUpdraftEvent.prototype.getData = function () {
  85831. this._dataFetched = true;
  85832. return {
  85833. cylinder: this._cylinder,
  85834. };
  85835. };
  85836. /**
  85837. * Enables the updraft.
  85838. */
  85839. PhysicsUpdraftEvent.prototype.enable = function () {
  85840. this._tickCallback.call(this);
  85841. this._scene.registerBeforeRender(this._tickCallback);
  85842. };
  85843. /**
  85844. * Disables the cortex.
  85845. */
  85846. PhysicsUpdraftEvent.prototype.disable = function () {
  85847. this._scene.unregisterBeforeRender(this._tickCallback);
  85848. };
  85849. /**
  85850. * Disposes the sphere.
  85851. * @param {bolean} force
  85852. */
  85853. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85854. var _this = this;
  85855. if (force === void 0) { force = true; }
  85856. if (force) {
  85857. this._cylinder.dispose();
  85858. }
  85859. else {
  85860. setTimeout(function () {
  85861. if (!_this._dataFetched) {
  85862. _this._cylinder.dispose();
  85863. }
  85864. }, 0);
  85865. }
  85866. };
  85867. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85868. if (impostor.mass === 0) {
  85869. return null;
  85870. }
  85871. if (!this._intersectsWithCylinder(impostor)) {
  85872. return null;
  85873. }
  85874. var impostorObjectCenter = impostor.getObjectCenter();
  85875. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85876. var direction = this._originDirection;
  85877. }
  85878. else {
  85879. var direction = impostorObjectCenter.subtract(this._originTop);
  85880. }
  85881. var multiplier = this._strength * -1;
  85882. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85883. return { force: force, contactPoint: impostorObjectCenter };
  85884. };
  85885. PhysicsUpdraftEvent.prototype._tick = function () {
  85886. var _this = this;
  85887. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85888. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85889. if (!impostorForceAndContactPoint) {
  85890. return;
  85891. }
  85892. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85893. });
  85894. };
  85895. /*** Helpers ***/
  85896. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85897. if (!this._cylinder) {
  85898. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85899. height: this._height,
  85900. diameter: this._radius * 2,
  85901. }, this._scene);
  85902. this._cylinder.isVisible = false;
  85903. }
  85904. };
  85905. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85906. var impostorObject = impostor.object;
  85907. this._prepareCylinder();
  85908. this._cylinder.position = this._cylinderPosition;
  85909. return this._cylinder.intersectsMesh(impostorObject, true);
  85910. };
  85911. return PhysicsUpdraftEvent;
  85912. }());
  85913. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85914. /***** Vortex *****/
  85915. var PhysicsVortexEvent = /** @class */ (function () {
  85916. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85917. this._scene = _scene;
  85918. this._origin = _origin;
  85919. this._radius = _radius;
  85920. this._strength = _strength;
  85921. this._height = _height;
  85922. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85923. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85924. this._updraftMultiplier = 0.02;
  85925. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85926. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85927. this._physicsEngine = this._scene.getPhysicsEngine();
  85928. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85929. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85930. this._tickCallback = this._tick.bind(this);
  85931. }
  85932. /**
  85933. * Returns the data related to the vortex event (cylinder).
  85934. * @returns {PhysicsVortexEventData}
  85935. */
  85936. PhysicsVortexEvent.prototype.getData = function () {
  85937. this._dataFetched = true;
  85938. return {
  85939. cylinder: this._cylinder,
  85940. };
  85941. };
  85942. /**
  85943. * Enables the vortex.
  85944. */
  85945. PhysicsVortexEvent.prototype.enable = function () {
  85946. this._tickCallback.call(this);
  85947. this._scene.registerBeforeRender(this._tickCallback);
  85948. };
  85949. /**
  85950. * Disables the cortex.
  85951. */
  85952. PhysicsVortexEvent.prototype.disable = function () {
  85953. this._scene.unregisterBeforeRender(this._tickCallback);
  85954. };
  85955. /**
  85956. * Disposes the sphere.
  85957. * @param {bolean} force
  85958. */
  85959. PhysicsVortexEvent.prototype.dispose = function (force) {
  85960. var _this = this;
  85961. if (force === void 0) { force = true; }
  85962. if (force) {
  85963. this._cylinder.dispose();
  85964. }
  85965. else {
  85966. setTimeout(function () {
  85967. if (!_this._dataFetched) {
  85968. _this._cylinder.dispose();
  85969. }
  85970. }, 0);
  85971. }
  85972. };
  85973. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85974. if (impostor.mass === 0) {
  85975. return null;
  85976. }
  85977. if (!this._intersectsWithCylinder(impostor)) {
  85978. return null;
  85979. }
  85980. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85981. return null;
  85982. }
  85983. var impostorObjectCenter = impostor.getObjectCenter();
  85984. 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)
  85985. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85986. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85987. var hit = ray.intersectsMesh(impostor.object);
  85988. var contactPoint = hit.pickedPoint;
  85989. if (!contactPoint) {
  85990. return null;
  85991. }
  85992. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85993. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85994. var directionToOrigin = contactPoint.normalize();
  85995. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85996. directionToOrigin = directionToOrigin.negate();
  85997. }
  85998. // TODO: find a more physically based solution
  85999. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86000. var forceX = directionToOrigin.x * this._strength / 8;
  86001. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86002. var forceZ = directionToOrigin.z * this._strength / 8;
  86003. }
  86004. else {
  86005. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86006. var forceY = this._originTop.y * this._updraftMultiplier;
  86007. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86008. }
  86009. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86010. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86011. return { force: force, contactPoint: impostorObjectCenter };
  86012. };
  86013. PhysicsVortexEvent.prototype._tick = function () {
  86014. var _this = this;
  86015. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86016. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86017. if (!impostorForceAndContactPoint) {
  86018. return;
  86019. }
  86020. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86021. });
  86022. };
  86023. /*** Helpers ***/
  86024. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86025. if (!this._cylinder) {
  86026. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86027. height: this._height,
  86028. diameter: this._radius * 2,
  86029. }, this._scene);
  86030. this._cylinder.isVisible = false;
  86031. }
  86032. };
  86033. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86034. var impostorObject = impostor.object;
  86035. this._prepareCylinder();
  86036. this._cylinder.position = this._cylinderPosition;
  86037. return this._cylinder.intersectsMesh(impostorObject, true);
  86038. };
  86039. return PhysicsVortexEvent;
  86040. }());
  86041. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86042. /***** Enums *****/
  86043. /**
  86044. * The strenght of the force in correspondence to the distance of the affected object
  86045. */
  86046. var PhysicsRadialImpulseFalloff;
  86047. (function (PhysicsRadialImpulseFalloff) {
  86048. /** Defines that impulse is constant in strength across it's whole radius */
  86049. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86050. /** DEfines that impulse gets weaker if it's further from the origin */
  86051. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86052. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86053. /**
  86054. * The strenght of the force in correspondence to the distance of the affected object
  86055. */
  86056. var PhysicsUpdraftMode;
  86057. (function (PhysicsUpdraftMode) {
  86058. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86059. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86060. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86061. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86062. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86063. })(BABYLON || (BABYLON = {}));
  86064. //# sourceMappingURL=babylon.physicsHelper.js.map
  86065. var BABYLON;
  86066. (function (BABYLON) {
  86067. var CannonJSPlugin = /** @class */ (function () {
  86068. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86069. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86070. if (iterations === void 0) { iterations = 10; }
  86071. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86072. this.name = "CannonJSPlugin";
  86073. this._physicsMaterials = new Array();
  86074. this._fixedTimeStep = 1 / 60;
  86075. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86076. this.BJSCANNON = CANNON;
  86077. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86078. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86079. this._tmpPosition = BABYLON.Vector3.Zero();
  86080. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86081. this._tmpUnityRotation = new BABYLON.Quaternion();
  86082. if (!this.isSupported()) {
  86083. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86084. return;
  86085. }
  86086. this._extendNamespace();
  86087. this.world = new this.BJSCANNON.World();
  86088. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86089. this.world.solver.iterations = iterations;
  86090. }
  86091. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86092. this.world.gravity.copy(gravity);
  86093. };
  86094. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86095. this._fixedTimeStep = timeStep;
  86096. };
  86097. CannonJSPlugin.prototype.getTimeStep = function () {
  86098. return this._fixedTimeStep;
  86099. };
  86100. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86101. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86102. };
  86103. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86104. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86105. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86106. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86107. };
  86108. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86109. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86110. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86111. impostor.physicsBody.applyForce(impulse, worldPoint);
  86112. };
  86113. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86114. //parent-child relationship. Does this impostor has a parent impostor?
  86115. if (impostor.parent) {
  86116. if (impostor.physicsBody) {
  86117. this.removePhysicsBody(impostor);
  86118. //TODO is that needed?
  86119. impostor.forceUpdate();
  86120. }
  86121. return;
  86122. }
  86123. //should a new body be created for this impostor?
  86124. if (impostor.isBodyInitRequired()) {
  86125. var shape = this._createShape(impostor);
  86126. //unregister events, if body is being changed
  86127. var oldBody = impostor.physicsBody;
  86128. if (oldBody) {
  86129. this.removePhysicsBody(impostor);
  86130. }
  86131. //create the body and material
  86132. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86133. var bodyCreationObject = {
  86134. mass: impostor.getParam("mass"),
  86135. material: material
  86136. };
  86137. // A simple extend, in case native options were used.
  86138. var nativeOptions = impostor.getParam("nativeOptions");
  86139. for (var key in nativeOptions) {
  86140. if (nativeOptions.hasOwnProperty(key)) {
  86141. bodyCreationObject[key] = nativeOptions[key];
  86142. }
  86143. }
  86144. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86145. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86146. this.world.addEventListener("preStep", impostor.beforeStep);
  86147. this.world.addEventListener("postStep", impostor.afterStep);
  86148. impostor.physicsBody.addShape(shape);
  86149. this.world.add(impostor.physicsBody);
  86150. //try to keep the body moving in the right direction by taking old properties.
  86151. //Should be tested!
  86152. if (oldBody) {
  86153. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86154. impostor.physicsBody[param].copy(oldBody[param]);
  86155. });
  86156. }
  86157. this._processChildMeshes(impostor);
  86158. }
  86159. //now update the body's transformation
  86160. this._updatePhysicsBodyTransformation(impostor);
  86161. };
  86162. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86163. var _this = this;
  86164. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86165. var currentRotation = mainImpostor.object.rotationQuaternion;
  86166. if (meshChildren.length) {
  86167. var processMesh = function (localPosition, mesh) {
  86168. if (!currentRotation || !mesh.rotationQuaternion) {
  86169. return;
  86170. }
  86171. var childImpostor = mesh.getPhysicsImpostor();
  86172. if (childImpostor) {
  86173. var parent = childImpostor.parent;
  86174. if (parent !== mainImpostor) {
  86175. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86176. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86177. if (childImpostor.physicsBody) {
  86178. _this.removePhysicsBody(childImpostor);
  86179. childImpostor.physicsBody = null;
  86180. }
  86181. childImpostor.parent = mainImpostor;
  86182. childImpostor.resetUpdateFlags();
  86183. 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));
  86184. //Add the mass of the children.
  86185. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86186. }
  86187. }
  86188. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86189. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86190. };
  86191. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86192. }
  86193. };
  86194. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86195. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86196. this.world.removeEventListener("preStep", impostor.beforeStep);
  86197. this.world.removeEventListener("postStep", impostor.afterStep);
  86198. this.world.remove(impostor.physicsBody);
  86199. };
  86200. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86201. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86202. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86203. if (!mainBody || !connectedBody) {
  86204. return;
  86205. }
  86206. var constraint;
  86207. var jointData = impostorJoint.joint.jointData;
  86208. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86209. var constraintData = {
  86210. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86211. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86212. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86213. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86214. maxForce: jointData.nativeParams.maxForce,
  86215. collideConnected: !!jointData.collision
  86216. };
  86217. switch (impostorJoint.joint.type) {
  86218. case BABYLON.PhysicsJoint.HingeJoint:
  86219. case BABYLON.PhysicsJoint.Hinge2Joint:
  86220. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86221. break;
  86222. case BABYLON.PhysicsJoint.DistanceJoint:
  86223. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86224. break;
  86225. case BABYLON.PhysicsJoint.SpringJoint:
  86226. var springData = jointData;
  86227. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86228. restLength: springData.length,
  86229. stiffness: springData.stiffness,
  86230. damping: springData.damping,
  86231. localAnchorA: constraintData.pivotA,
  86232. localAnchorB: constraintData.pivotB
  86233. });
  86234. break;
  86235. case BABYLON.PhysicsJoint.LockJoint:
  86236. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86237. break;
  86238. case BABYLON.PhysicsJoint.PointToPointJoint:
  86239. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86240. default:
  86241. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86242. break;
  86243. }
  86244. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86245. constraint.collideConnected = !!jointData.collision;
  86246. impostorJoint.joint.physicsJoint = constraint;
  86247. //don't add spring as constraint, as it is not one.
  86248. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86249. this.world.addConstraint(constraint);
  86250. }
  86251. else {
  86252. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86253. constraint.applyForce();
  86254. });
  86255. }
  86256. };
  86257. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86258. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86259. };
  86260. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86261. var index;
  86262. var mat;
  86263. for (index = 0; index < this._physicsMaterials.length; index++) {
  86264. mat = this._physicsMaterials[index];
  86265. if (mat.friction === friction && mat.restitution === restitution) {
  86266. return mat;
  86267. }
  86268. }
  86269. var currentMat = new this.BJSCANNON.Material(name);
  86270. currentMat.friction = friction;
  86271. currentMat.restitution = restitution;
  86272. this._physicsMaterials.push(currentMat);
  86273. return currentMat;
  86274. };
  86275. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86276. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86277. };
  86278. CannonJSPlugin.prototype._createShape = function (impostor) {
  86279. var object = impostor.object;
  86280. var returnValue;
  86281. var extendSize = impostor.getObjectExtendSize();
  86282. switch (impostor.type) {
  86283. case BABYLON.PhysicsImpostor.SphereImpostor:
  86284. var radiusX = extendSize.x;
  86285. var radiusY = extendSize.y;
  86286. var radiusZ = extendSize.z;
  86287. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86288. break;
  86289. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86290. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86291. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86292. break;
  86293. case BABYLON.PhysicsImpostor.BoxImpostor:
  86294. var box = extendSize.scale(0.5);
  86295. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86296. break;
  86297. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86298. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86299. returnValue = new this.BJSCANNON.Plane();
  86300. break;
  86301. case BABYLON.PhysicsImpostor.MeshImpostor:
  86302. // should transform the vertex data to world coordinates!!
  86303. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86304. var rawFaces = object.getIndices ? object.getIndices() : [];
  86305. if (!rawVerts)
  86306. return;
  86307. // get only scale! so the object could transform correctly.
  86308. var oldPosition = object.position.clone();
  86309. var oldRotation = object.rotation && object.rotation.clone();
  86310. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86311. object.position.copyFromFloats(0, 0, 0);
  86312. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86313. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86314. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86315. var transform = object.computeWorldMatrix(true);
  86316. // convert rawVerts to object space
  86317. var temp = new Array();
  86318. var index;
  86319. for (index = 0; index < rawVerts.length; index += 3) {
  86320. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86321. }
  86322. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86323. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86324. //now set back the transformation!
  86325. object.position.copyFrom(oldPosition);
  86326. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86327. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86328. break;
  86329. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86330. var oldPosition2 = object.position.clone();
  86331. var oldRotation2 = object.rotation && object.rotation.clone();
  86332. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86333. object.position.copyFromFloats(0, 0, 0);
  86334. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86335. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86336. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86337. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86338. returnValue = this._createHeightmap(object);
  86339. object.position.copyFrom(oldPosition2);
  86340. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86341. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86342. object.computeWorldMatrix(true);
  86343. break;
  86344. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86345. returnValue = new this.BJSCANNON.Particle();
  86346. break;
  86347. }
  86348. return returnValue;
  86349. };
  86350. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86351. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86352. var transform = object.computeWorldMatrix(true);
  86353. // convert rawVerts to object space
  86354. var temp = new Array();
  86355. var index;
  86356. for (index = 0; index < pos.length; index += 3) {
  86357. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86358. }
  86359. pos = temp;
  86360. var matrix = new Array();
  86361. //For now pointDepth will not be used and will be automatically calculated.
  86362. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86363. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86364. var boundingInfo = object.getBoundingInfo();
  86365. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86366. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86367. var elementSize = dim * 2 / arraySize;
  86368. for (var i = 0; i < pos.length; i = i + 3) {
  86369. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86370. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86371. var y = -pos[i + 2] + minY;
  86372. if (!matrix[x]) {
  86373. matrix[x] = [];
  86374. }
  86375. if (!matrix[x][z]) {
  86376. matrix[x][z] = y;
  86377. }
  86378. matrix[x][z] = Math.max(y, matrix[x][z]);
  86379. }
  86380. for (var x = 0; x <= arraySize; ++x) {
  86381. if (!matrix[x]) {
  86382. var loc = 1;
  86383. while (!matrix[(x + loc) % arraySize]) {
  86384. loc++;
  86385. }
  86386. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86387. //console.log("missing x", x);
  86388. }
  86389. for (var z = 0; z <= arraySize; ++z) {
  86390. if (!matrix[x][z]) {
  86391. var loc = 1;
  86392. var newValue;
  86393. while (newValue === undefined) {
  86394. newValue = matrix[x][(z + loc++) % arraySize];
  86395. }
  86396. matrix[x][z] = newValue;
  86397. }
  86398. }
  86399. }
  86400. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86401. elementSize: elementSize
  86402. });
  86403. //For future reference, needed for body transformation
  86404. shape.minY = minY;
  86405. return shape;
  86406. };
  86407. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86408. var object = impostor.object;
  86409. //make sure it is updated...
  86410. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86411. // The delta between the mesh position and the mesh bounding box center
  86412. var bInfo = object.getBoundingInfo();
  86413. if (!bInfo)
  86414. return;
  86415. var center = impostor.getObjectCenter();
  86416. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86417. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86418. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86419. this._tmpPosition.copyFrom(center);
  86420. var quaternion = object.rotationQuaternion;
  86421. if (!quaternion) {
  86422. return;
  86423. }
  86424. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86425. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86426. //-90 DEG in X, precalculated
  86427. quaternion = quaternion.multiply(this._minus90X);
  86428. //Invert! (Precalculated, 90 deg in X)
  86429. //No need to clone. this will never change.
  86430. impostor.setDeltaRotation(this._plus90X);
  86431. }
  86432. //If it is a heightfield, if should be centered.
  86433. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86434. var mesh = object;
  86435. var boundingInfo = mesh.getBoundingInfo();
  86436. //calculate the correct body position:
  86437. var rotationQuaternion = mesh.rotationQuaternion;
  86438. mesh.rotationQuaternion = this._tmpUnityRotation;
  86439. mesh.computeWorldMatrix(true);
  86440. //get original center with no rotation
  86441. var c = center.clone();
  86442. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86443. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86444. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86445. mesh.setPreTransformMatrix(p);
  86446. mesh.computeWorldMatrix(true);
  86447. //calculate the translation
  86448. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86449. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86450. //add it inverted to the delta
  86451. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86452. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86453. //rotation is back
  86454. mesh.rotationQuaternion = rotationQuaternion;
  86455. mesh.setPreTransformMatrix(oldPivot);
  86456. mesh.computeWorldMatrix(true);
  86457. }
  86458. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86459. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86460. //this._tmpPosition.copyFrom(object.position);
  86461. }
  86462. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86463. //Now update the impostor object
  86464. impostor.physicsBody.position.copy(this._tmpPosition);
  86465. impostor.physicsBody.quaternion.copy(quaternion);
  86466. };
  86467. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86468. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86469. if (impostor.object.rotationQuaternion) {
  86470. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86471. }
  86472. };
  86473. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86474. impostor.physicsBody.position.copy(newPosition);
  86475. impostor.physicsBody.quaternion.copy(newRotation);
  86476. };
  86477. CannonJSPlugin.prototype.isSupported = function () {
  86478. return this.BJSCANNON !== undefined;
  86479. };
  86480. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86481. impostor.physicsBody.velocity.copy(velocity);
  86482. };
  86483. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86484. impostor.physicsBody.angularVelocity.copy(velocity);
  86485. };
  86486. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86487. var v = impostor.physicsBody.velocity;
  86488. if (!v) {
  86489. return null;
  86490. }
  86491. return new BABYLON.Vector3(v.x, v.y, v.z);
  86492. };
  86493. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86494. var v = impostor.physicsBody.angularVelocity;
  86495. if (!v) {
  86496. return null;
  86497. }
  86498. return new BABYLON.Vector3(v.x, v.y, v.z);
  86499. };
  86500. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86501. impostor.physicsBody.mass = mass;
  86502. impostor.physicsBody.updateMassProperties();
  86503. };
  86504. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86505. return impostor.physicsBody.mass;
  86506. };
  86507. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86508. return impostor.physicsBody.material.friction;
  86509. };
  86510. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86511. impostor.physicsBody.material.friction = friction;
  86512. };
  86513. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86514. return impostor.physicsBody.material.restitution;
  86515. };
  86516. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86517. impostor.physicsBody.material.restitution = restitution;
  86518. };
  86519. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86520. impostor.physicsBody.sleep();
  86521. };
  86522. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86523. impostor.physicsBody.wakeUp();
  86524. };
  86525. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86526. joint.physicsJoint.distance = maxDistance;
  86527. };
  86528. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86529. // if (!motorIndex) {
  86530. // joint.physicsJoint.enableMotor();
  86531. // }
  86532. // }
  86533. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86534. // if (!motorIndex) {
  86535. // joint.physicsJoint.disableMotor();
  86536. // }
  86537. // }
  86538. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86539. if (!motorIndex) {
  86540. joint.physicsJoint.enableMotor();
  86541. joint.physicsJoint.setMotorSpeed(speed);
  86542. if (maxForce) {
  86543. this.setLimit(joint, maxForce);
  86544. }
  86545. }
  86546. };
  86547. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86548. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86549. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86550. };
  86551. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86552. var body = impostor.physicsBody;
  86553. mesh.position.x = body.position.x;
  86554. mesh.position.y = body.position.y;
  86555. mesh.position.z = body.position.z;
  86556. if (mesh.rotationQuaternion) {
  86557. mesh.rotationQuaternion.x = body.quaternion.x;
  86558. mesh.rotationQuaternion.y = body.quaternion.y;
  86559. mesh.rotationQuaternion.z = body.quaternion.z;
  86560. mesh.rotationQuaternion.w = body.quaternion.w;
  86561. }
  86562. };
  86563. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86564. var shape = impostor.physicsBody.shapes[0];
  86565. return shape.boundingSphereRadius;
  86566. };
  86567. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86568. var shape = impostor.physicsBody.shapes[0];
  86569. result.x = shape.halfExtents.x * 2;
  86570. result.y = shape.halfExtents.y * 2;
  86571. result.z = shape.halfExtents.z * 2;
  86572. };
  86573. CannonJSPlugin.prototype.dispose = function () {
  86574. };
  86575. CannonJSPlugin.prototype._extendNamespace = function () {
  86576. //this will force cannon to execute at least one step when using interpolation
  86577. var step_tmp1 = new this.BJSCANNON.Vec3();
  86578. var Engine = this.BJSCANNON;
  86579. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86580. maxSubSteps = maxSubSteps || 10;
  86581. timeSinceLastCalled = timeSinceLastCalled || 0;
  86582. if (timeSinceLastCalled === 0) {
  86583. this.internalStep(dt);
  86584. this.time += dt;
  86585. }
  86586. else {
  86587. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86588. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86589. var t0 = performance.now();
  86590. for (var i = 0; i !== internalSteps; i++) {
  86591. this.internalStep(dt);
  86592. if (performance.now() - t0 > dt * 1000) {
  86593. break;
  86594. }
  86595. }
  86596. this.time += timeSinceLastCalled;
  86597. var h = this.time % dt;
  86598. var h_div_dt = h / dt;
  86599. var interpvelo = step_tmp1;
  86600. var bodies = this.bodies;
  86601. for (var j = 0; j !== bodies.length; j++) {
  86602. var b = bodies[j];
  86603. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86604. b.position.vsub(b.previousPosition, interpvelo);
  86605. interpvelo.scale(h_div_dt, interpvelo);
  86606. b.position.vadd(interpvelo, b.interpolatedPosition);
  86607. }
  86608. else {
  86609. b.interpolatedPosition.copy(b.position);
  86610. b.interpolatedQuaternion.copy(b.quaternion);
  86611. }
  86612. }
  86613. }
  86614. };
  86615. };
  86616. return CannonJSPlugin;
  86617. }());
  86618. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86619. })(BABYLON || (BABYLON = {}));
  86620. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86621. var BABYLON;
  86622. (function (BABYLON) {
  86623. var OimoJSPlugin = /** @class */ (function () {
  86624. function OimoJSPlugin(iterations) {
  86625. this.name = "OimoJSPlugin";
  86626. this._tmpImpostorsArray = [];
  86627. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86628. this.BJSOIMO = OIMO;
  86629. this.world = new this.BJSOIMO.World({
  86630. iterations: iterations
  86631. });
  86632. this.world.clear();
  86633. }
  86634. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86635. this.world.gravity.copy(gravity);
  86636. };
  86637. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86638. this.world.timeStep = timeStep;
  86639. };
  86640. OimoJSPlugin.prototype.getTimeStep = function () {
  86641. return this.world.timeStep;
  86642. };
  86643. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86644. var _this = this;
  86645. impostors.forEach(function (impostor) {
  86646. impostor.beforeStep();
  86647. });
  86648. this.world.step();
  86649. impostors.forEach(function (impostor) {
  86650. impostor.afterStep();
  86651. //update the ordered impostors array
  86652. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86653. });
  86654. //check for collisions
  86655. var contact = this.world.contacts;
  86656. while (contact !== null) {
  86657. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86658. contact = contact.next;
  86659. continue;
  86660. }
  86661. //is this body colliding with any other? get the impostor
  86662. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86663. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86664. if (!mainImpostor || !collidingImpostor) {
  86665. contact = contact.next;
  86666. continue;
  86667. }
  86668. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86669. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86670. contact = contact.next;
  86671. }
  86672. };
  86673. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86674. var mass = impostor.physicsBody.mass;
  86675. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86676. };
  86677. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86678. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86679. this.applyImpulse(impostor, force, contactPoint);
  86680. };
  86681. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86682. var _this = this;
  86683. //parent-child relationship. Does this impostor has a parent impostor?
  86684. if (impostor.parent) {
  86685. if (impostor.physicsBody) {
  86686. this.removePhysicsBody(impostor);
  86687. //TODO is that needed?
  86688. impostor.forceUpdate();
  86689. }
  86690. return;
  86691. }
  86692. if (impostor.isBodyInitRequired()) {
  86693. var bodyConfig = {
  86694. name: impostor.uniqueId,
  86695. //Oimo must have mass, also for static objects.
  86696. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86697. size: [],
  86698. type: [],
  86699. pos: [],
  86700. posShape: [],
  86701. rot: [],
  86702. rotShape: [],
  86703. move: impostor.getParam("mass") !== 0,
  86704. density: impostor.getParam("mass"),
  86705. friction: impostor.getParam("friction"),
  86706. restitution: impostor.getParam("restitution"),
  86707. //Supporting older versions of Oimo
  86708. world: this.world
  86709. };
  86710. var impostors = [impostor];
  86711. var addToArray = function (parent) {
  86712. if (!parent.getChildMeshes)
  86713. return;
  86714. parent.getChildMeshes().forEach(function (m) {
  86715. if (m.physicsImpostor) {
  86716. impostors.push(m.physicsImpostor);
  86717. //m.physicsImpostor._init();
  86718. }
  86719. });
  86720. };
  86721. addToArray(impostor.object);
  86722. var checkWithEpsilon_1 = function (value) {
  86723. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86724. };
  86725. impostors.forEach(function (i) {
  86726. if (!i.object.rotationQuaternion) {
  86727. return;
  86728. }
  86729. //get the correct bounding box
  86730. var oldQuaternion = i.object.rotationQuaternion;
  86731. var rot = oldQuaternion.toEulerAngles();
  86732. var extendSize = i.getObjectExtendSize();
  86733. var radToDeg = 57.295779513082320876;
  86734. if (i === impostor) {
  86735. var center = impostor.getObjectCenter();
  86736. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86737. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86738. //Can also use Array.prototype.push.apply
  86739. bodyConfig.pos.push(center.x);
  86740. bodyConfig.pos.push(center.y);
  86741. bodyConfig.pos.push(center.z);
  86742. bodyConfig.posShape.push(0, 0, 0);
  86743. //tmp solution
  86744. bodyConfig.rot.push(rot.x * radToDeg);
  86745. bodyConfig.rot.push(rot.y * radToDeg);
  86746. bodyConfig.rot.push(rot.z * radToDeg);
  86747. bodyConfig.rotShape.push(0, 0, 0);
  86748. }
  86749. else {
  86750. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86751. bodyConfig.posShape.push(localPosition.x);
  86752. bodyConfig.posShape.push(localPosition.y);
  86753. bodyConfig.posShape.push(localPosition.z);
  86754. bodyConfig.pos.push(0, 0, 0);
  86755. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86756. bodyConfig.rot.push(0);
  86757. bodyConfig.rot.push(0);
  86758. bodyConfig.rot.push(0);
  86759. bodyConfig.rotShape.push(rot.x * radToDeg);
  86760. bodyConfig.rotShape.push(rot.y * radToDeg);
  86761. bodyConfig.rotShape.push(rot.z * radToDeg);
  86762. }
  86763. // register mesh
  86764. switch (i.type) {
  86765. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86766. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86767. case BABYLON.PhysicsImpostor.SphereImpostor:
  86768. var radiusX = extendSize.x;
  86769. var radiusY = extendSize.y;
  86770. var radiusZ = extendSize.z;
  86771. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86772. bodyConfig.type.push('sphere');
  86773. //due to the way oimo works with compounds, add 3 times
  86774. bodyConfig.size.push(size);
  86775. bodyConfig.size.push(size);
  86776. bodyConfig.size.push(size);
  86777. break;
  86778. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86779. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86780. var sizeY = checkWithEpsilon_1(extendSize.y);
  86781. bodyConfig.type.push('cylinder');
  86782. bodyConfig.size.push(sizeX);
  86783. bodyConfig.size.push(sizeY);
  86784. //due to the way oimo works with compounds, add one more value.
  86785. bodyConfig.size.push(sizeY);
  86786. break;
  86787. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86788. case BABYLON.PhysicsImpostor.BoxImpostor:
  86789. default:
  86790. var sizeX = checkWithEpsilon_1(extendSize.x);
  86791. var sizeY = checkWithEpsilon_1(extendSize.y);
  86792. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86793. bodyConfig.type.push('box');
  86794. //if (i === impostor) {
  86795. bodyConfig.size.push(sizeX);
  86796. bodyConfig.size.push(sizeY);
  86797. bodyConfig.size.push(sizeZ);
  86798. //} else {
  86799. // bodyConfig.size.push(0,0,0);
  86800. //}
  86801. break;
  86802. }
  86803. //actually not needed, but hey...
  86804. i.object.rotationQuaternion = oldQuaternion;
  86805. });
  86806. impostor.physicsBody = this.world.add(bodyConfig);
  86807. }
  86808. else {
  86809. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86810. }
  86811. impostor.setDeltaPosition(this._tmpPositionVector);
  86812. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86813. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86814. };
  86815. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86816. //impostor.physicsBody.dispose();
  86817. //Same as : (older oimo versions)
  86818. this.world.removeRigidBody(impostor.physicsBody);
  86819. };
  86820. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86821. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86822. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86823. if (!mainBody || !connectedBody) {
  86824. return;
  86825. }
  86826. var jointData = impostorJoint.joint.jointData;
  86827. var options = jointData.nativeParams || {};
  86828. var type;
  86829. var nativeJointData = {
  86830. body1: mainBody,
  86831. body2: connectedBody,
  86832. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86833. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86834. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86835. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86836. min: options.min,
  86837. max: options.max,
  86838. collision: options.collision || jointData.collision,
  86839. spring: options.spring,
  86840. //supporting older version of Oimo
  86841. world: this.world
  86842. };
  86843. switch (impostorJoint.joint.type) {
  86844. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86845. type = "jointBall";
  86846. break;
  86847. case BABYLON.PhysicsJoint.SpringJoint:
  86848. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86849. var springData = jointData;
  86850. nativeJointData.min = springData.length || nativeJointData.min;
  86851. //Max should also be set, just make sure it is at least min
  86852. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86853. case BABYLON.PhysicsJoint.DistanceJoint:
  86854. type = "jointDistance";
  86855. nativeJointData.max = jointData.maxDistance;
  86856. break;
  86857. case BABYLON.PhysicsJoint.PrismaticJoint:
  86858. type = "jointPrisme";
  86859. break;
  86860. case BABYLON.PhysicsJoint.SliderJoint:
  86861. type = "jointSlide";
  86862. break;
  86863. case BABYLON.PhysicsJoint.WheelJoint:
  86864. type = "jointWheel";
  86865. break;
  86866. case BABYLON.PhysicsJoint.HingeJoint:
  86867. default:
  86868. type = "jointHinge";
  86869. break;
  86870. }
  86871. nativeJointData.type = type;
  86872. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86873. };
  86874. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86875. //Bug in Oimo prevents us from disposing a joint in the playground
  86876. //joint.joint.physicsJoint.dispose();
  86877. //So we will bruteforce it!
  86878. try {
  86879. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86880. }
  86881. catch (e) {
  86882. BABYLON.Tools.Warn(e);
  86883. }
  86884. };
  86885. OimoJSPlugin.prototype.isSupported = function () {
  86886. return this.BJSOIMO !== undefined;
  86887. };
  86888. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86889. if (!impostor.physicsBody.sleeping) {
  86890. //TODO check that
  86891. /*if (impostor.physicsBody.shapes.next) {
  86892. var parentShape = this._getLastShape(impostor.physicsBody);
  86893. impostor.object.position.copyFrom(parentShape.position);
  86894. console.log(parentShape.position);
  86895. } else {*/
  86896. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86897. //}
  86898. if (impostor.object.rotationQuaternion) {
  86899. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86900. }
  86901. }
  86902. };
  86903. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86904. var body = impostor.physicsBody;
  86905. body.position.copy(newPosition);
  86906. body.orientation.copy(newRotation);
  86907. body.syncShapes();
  86908. body.awake();
  86909. };
  86910. /*private _getLastShape(body: any): any {
  86911. var lastShape = body.shapes;
  86912. while (lastShape.next) {
  86913. lastShape = lastShape.next;
  86914. }
  86915. return lastShape;
  86916. }*/
  86917. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86918. impostor.physicsBody.linearVelocity.copy(velocity);
  86919. };
  86920. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86921. impostor.physicsBody.angularVelocity.copy(velocity);
  86922. };
  86923. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86924. var v = impostor.physicsBody.linearVelocity;
  86925. if (!v) {
  86926. return null;
  86927. }
  86928. return new BABYLON.Vector3(v.x, v.y, v.z);
  86929. };
  86930. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86931. var v = impostor.physicsBody.angularVelocity;
  86932. if (!v) {
  86933. return null;
  86934. }
  86935. return new BABYLON.Vector3(v.x, v.y, v.z);
  86936. };
  86937. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86938. var staticBody = mass === 0;
  86939. //this will actually set the body's density and not its mass.
  86940. //But this is how oimo treats the mass variable.
  86941. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86942. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86943. };
  86944. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86945. return impostor.physicsBody.shapes.density;
  86946. };
  86947. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86948. return impostor.physicsBody.shapes.friction;
  86949. };
  86950. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86951. impostor.physicsBody.shapes.friction = friction;
  86952. };
  86953. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86954. return impostor.physicsBody.shapes.restitution;
  86955. };
  86956. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86957. impostor.physicsBody.shapes.restitution = restitution;
  86958. };
  86959. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86960. impostor.physicsBody.sleep();
  86961. };
  86962. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86963. impostor.physicsBody.awake();
  86964. };
  86965. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86966. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86967. if (minDistance !== void 0) {
  86968. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86969. }
  86970. };
  86971. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86972. //TODO separate rotational and transational motors.
  86973. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86974. if (motor) {
  86975. motor.setMotor(speed, maxForce);
  86976. }
  86977. };
  86978. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86979. //TODO separate rotational and transational motors.
  86980. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86981. if (motor) {
  86982. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86983. }
  86984. };
  86985. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86986. var body = impostor.physicsBody;
  86987. mesh.position.x = body.position.x;
  86988. mesh.position.y = body.position.y;
  86989. mesh.position.z = body.position.z;
  86990. if (mesh.rotationQuaternion) {
  86991. mesh.rotationQuaternion.x = body.orientation.x;
  86992. mesh.rotationQuaternion.y = body.orientation.y;
  86993. mesh.rotationQuaternion.z = body.orientation.z;
  86994. mesh.rotationQuaternion.w = body.orientation.s;
  86995. }
  86996. };
  86997. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86998. return impostor.physicsBody.shapes.radius;
  86999. };
  87000. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87001. var shape = impostor.physicsBody.shapes;
  87002. result.x = shape.halfWidth * 2;
  87003. result.y = shape.halfHeight * 2;
  87004. result.z = shape.halfDepth * 2;
  87005. };
  87006. OimoJSPlugin.prototype.dispose = function () {
  87007. this.world.clear();
  87008. };
  87009. return OimoJSPlugin;
  87010. }());
  87011. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87012. })(BABYLON || (BABYLON = {}));
  87013. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87014. var BABYLON;
  87015. (function (BABYLON) {
  87016. /*
  87017. * Based on jsTGALoader - Javascript loader for TGA file
  87018. * By Vincent Thibault
  87019. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87020. */
  87021. var TGATools = /** @class */ (function () {
  87022. function TGATools() {
  87023. }
  87024. TGATools.GetTGAHeader = function (data) {
  87025. var offset = 0;
  87026. var header = {
  87027. id_length: data[offset++],
  87028. colormap_type: data[offset++],
  87029. image_type: data[offset++],
  87030. colormap_index: data[offset++] | data[offset++] << 8,
  87031. colormap_length: data[offset++] | data[offset++] << 8,
  87032. colormap_size: data[offset++],
  87033. origin: [
  87034. data[offset++] | data[offset++] << 8,
  87035. data[offset++] | data[offset++] << 8
  87036. ],
  87037. width: data[offset++] | data[offset++] << 8,
  87038. height: data[offset++] | data[offset++] << 8,
  87039. pixel_size: data[offset++],
  87040. flags: data[offset++]
  87041. };
  87042. return header;
  87043. };
  87044. /**
  87045. * Uploads TGA content to a Babylon Texture
  87046. * @hidden
  87047. */
  87048. TGATools.UploadContent = function (texture, data) {
  87049. // Not enough data to contain header ?
  87050. if (data.length < 19) {
  87051. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87052. return;
  87053. }
  87054. // Read Header
  87055. var offset = 18;
  87056. var header = TGATools.GetTGAHeader(data);
  87057. // Assume it's a valid Targa file.
  87058. if (header.id_length + offset > data.length) {
  87059. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87060. return;
  87061. }
  87062. // Skip not needed data
  87063. offset += header.id_length;
  87064. var use_rle = false;
  87065. var use_pal = false;
  87066. var use_grey = false;
  87067. // Get some informations.
  87068. switch (header.image_type) {
  87069. case TGATools._TYPE_RLE_INDEXED:
  87070. use_rle = true;
  87071. case TGATools._TYPE_INDEXED:
  87072. use_pal = true;
  87073. break;
  87074. case TGATools._TYPE_RLE_RGB:
  87075. use_rle = true;
  87076. case TGATools._TYPE_RGB:
  87077. // use_rgb = true;
  87078. break;
  87079. case TGATools._TYPE_RLE_GREY:
  87080. use_rle = true;
  87081. case TGATools._TYPE_GREY:
  87082. use_grey = true;
  87083. break;
  87084. }
  87085. var pixel_data;
  87086. // var numAlphaBits = header.flags & 0xf;
  87087. var pixel_size = header.pixel_size >> 3;
  87088. var pixel_total = header.width * header.height * pixel_size;
  87089. // Read palettes
  87090. var palettes;
  87091. if (use_pal) {
  87092. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87093. }
  87094. // Read LRE
  87095. if (use_rle) {
  87096. pixel_data = new Uint8Array(pixel_total);
  87097. var c, count, i;
  87098. var localOffset = 0;
  87099. var pixels = new Uint8Array(pixel_size);
  87100. while (offset < pixel_total && localOffset < pixel_total) {
  87101. c = data[offset++];
  87102. count = (c & 0x7f) + 1;
  87103. // RLE pixels
  87104. if (c & 0x80) {
  87105. // Bind pixel tmp array
  87106. for (i = 0; i < pixel_size; ++i) {
  87107. pixels[i] = data[offset++];
  87108. }
  87109. // Copy pixel array
  87110. for (i = 0; i < count; ++i) {
  87111. pixel_data.set(pixels, localOffset + i * pixel_size);
  87112. }
  87113. localOffset += pixel_size * count;
  87114. }
  87115. // Raw pixels
  87116. else {
  87117. count *= pixel_size;
  87118. for (i = 0; i < count; ++i) {
  87119. pixel_data[localOffset + i] = data[offset++];
  87120. }
  87121. localOffset += count;
  87122. }
  87123. }
  87124. }
  87125. // RAW Pixels
  87126. else {
  87127. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87128. }
  87129. // Load to texture
  87130. var x_start, y_start, x_step, y_step, y_end, x_end;
  87131. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87132. default:
  87133. case TGATools._ORIGIN_UL:
  87134. x_start = 0;
  87135. x_step = 1;
  87136. x_end = header.width;
  87137. y_start = 0;
  87138. y_step = 1;
  87139. y_end = header.height;
  87140. break;
  87141. case TGATools._ORIGIN_BL:
  87142. x_start = 0;
  87143. x_step = 1;
  87144. x_end = header.width;
  87145. y_start = header.height - 1;
  87146. y_step = -1;
  87147. y_end = -1;
  87148. break;
  87149. case TGATools._ORIGIN_UR:
  87150. x_start = header.width - 1;
  87151. x_step = -1;
  87152. x_end = -1;
  87153. y_start = 0;
  87154. y_step = 1;
  87155. y_end = header.height;
  87156. break;
  87157. case TGATools._ORIGIN_BR:
  87158. x_start = header.width - 1;
  87159. x_step = -1;
  87160. x_end = -1;
  87161. y_start = header.height - 1;
  87162. y_step = -1;
  87163. y_end = -1;
  87164. break;
  87165. }
  87166. // Load the specify method
  87167. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87168. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87169. var engine = texture.getEngine();
  87170. engine._uploadArrayBufferViewToTexture(texture, imageData);
  87171. };
  87172. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87173. var image = pixel_data, colormap = palettes;
  87174. var width = header.width, height = header.height;
  87175. var color, i = 0, x, y;
  87176. var imageData = new Uint8Array(width * height * 4);
  87177. for (y = y_start; y !== y_end; y += y_step) {
  87178. for (x = x_start; x !== x_end; x += x_step, i++) {
  87179. color = image[i];
  87180. imageData[(x + width * y) * 4 + 3] = 255;
  87181. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  87182. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  87183. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  87184. }
  87185. }
  87186. return imageData;
  87187. };
  87188. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87189. var image = pixel_data;
  87190. var width = header.width, height = header.height;
  87191. var color, i = 0, x, y;
  87192. var imageData = new Uint8Array(width * height * 4);
  87193. for (y = y_start; y !== y_end; y += y_step) {
  87194. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87195. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  87196. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  87197. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  87198. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  87199. imageData[(x + width * y) * 4 + 0] = r;
  87200. imageData[(x + width * y) * 4 + 1] = g;
  87201. imageData[(x + width * y) * 4 + 2] = b;
  87202. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  87203. }
  87204. }
  87205. return imageData;
  87206. };
  87207. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87208. var image = pixel_data;
  87209. var width = header.width, height = header.height;
  87210. var i = 0, x, y;
  87211. var imageData = new Uint8Array(width * height * 4);
  87212. for (y = y_start; y !== y_end; y += y_step) {
  87213. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  87214. imageData[(x + width * y) * 4 + 3] = 255;
  87215. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87216. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87217. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87218. }
  87219. }
  87220. return imageData;
  87221. };
  87222. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87223. var image = pixel_data;
  87224. var width = header.width, height = header.height;
  87225. var i = 0, x, y;
  87226. var imageData = new Uint8Array(width * height * 4);
  87227. for (y = y_start; y !== y_end; y += y_step) {
  87228. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  87229. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87230. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87231. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87232. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  87233. }
  87234. }
  87235. return imageData;
  87236. };
  87237. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87238. var image = pixel_data;
  87239. var width = header.width, height = header.height;
  87240. var color, i = 0, x, y;
  87241. var imageData = new Uint8Array(width * height * 4);
  87242. for (y = y_start; y !== y_end; y += y_step) {
  87243. for (x = x_start; x !== x_end; x += x_step, i++) {
  87244. color = image[i];
  87245. imageData[(x + width * y) * 4 + 0] = color;
  87246. imageData[(x + width * y) * 4 + 1] = color;
  87247. imageData[(x + width * y) * 4 + 2] = color;
  87248. imageData[(x + width * y) * 4 + 3] = 255;
  87249. }
  87250. }
  87251. return imageData;
  87252. };
  87253. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87254. var image = pixel_data;
  87255. var width = header.width, height = header.height;
  87256. var i = 0, x, y;
  87257. var imageData = new Uint8Array(width * height * 4);
  87258. for (y = y_start; y !== y_end; y += y_step) {
  87259. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87260. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87261. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87262. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87263. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87264. }
  87265. }
  87266. return imageData;
  87267. };
  87268. //private static _TYPE_NO_DATA = 0;
  87269. TGATools._TYPE_INDEXED = 1;
  87270. TGATools._TYPE_RGB = 2;
  87271. TGATools._TYPE_GREY = 3;
  87272. TGATools._TYPE_RLE_INDEXED = 9;
  87273. TGATools._TYPE_RLE_RGB = 10;
  87274. TGATools._TYPE_RLE_GREY = 11;
  87275. TGATools._ORIGIN_MASK = 0x30;
  87276. TGATools._ORIGIN_SHIFT = 0x04;
  87277. TGATools._ORIGIN_BL = 0x00;
  87278. TGATools._ORIGIN_BR = 0x01;
  87279. TGATools._ORIGIN_UL = 0x02;
  87280. TGATools._ORIGIN_UR = 0x03;
  87281. return TGATools;
  87282. }());
  87283. BABYLON.TGATools = TGATools;
  87284. })(BABYLON || (BABYLON = {}));
  87285. //# sourceMappingURL=babylon.tga.js.map
  87286. var BABYLON;
  87287. (function (BABYLON) {
  87288. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87289. // All values and structures referenced from:
  87290. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87291. var DDS_MAGIC = 0x20534444;
  87292. var
  87293. //DDSD_CAPS = 0x1,
  87294. //DDSD_HEIGHT = 0x2,
  87295. //DDSD_WIDTH = 0x4,
  87296. //DDSD_PITCH = 0x8,
  87297. //DDSD_PIXELFORMAT = 0x1000,
  87298. DDSD_MIPMAPCOUNT = 0x20000;
  87299. //DDSD_LINEARSIZE = 0x80000,
  87300. //DDSD_DEPTH = 0x800000;
  87301. // var DDSCAPS_COMPLEX = 0x8,
  87302. // DDSCAPS_MIPMAP = 0x400000,
  87303. // DDSCAPS_TEXTURE = 0x1000;
  87304. var DDSCAPS2_CUBEMAP = 0x200;
  87305. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87306. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87307. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87308. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87309. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87310. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87311. // DDSCAPS2_VOLUME = 0x200000;
  87312. var
  87313. //DDPF_ALPHAPIXELS = 0x1,
  87314. //DDPF_ALPHA = 0x2,
  87315. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87316. //DDPF_YUV = 0x200,
  87317. DDPF_LUMINANCE = 0x20000;
  87318. function FourCCToInt32(value) {
  87319. return value.charCodeAt(0) +
  87320. (value.charCodeAt(1) << 8) +
  87321. (value.charCodeAt(2) << 16) +
  87322. (value.charCodeAt(3) << 24);
  87323. }
  87324. function Int32ToFourCC(value) {
  87325. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87326. }
  87327. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87328. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87329. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87330. var FOURCC_DX10 = FourCCToInt32("DX10");
  87331. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87332. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87333. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87334. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87335. var headerLengthInt = 31; // The header length in 32 bit ints
  87336. // Offsets into the header array
  87337. var off_magic = 0;
  87338. var off_size = 1;
  87339. var off_flags = 2;
  87340. var off_height = 3;
  87341. var off_width = 4;
  87342. var off_mipmapCount = 7;
  87343. var off_pfFlags = 20;
  87344. var off_pfFourCC = 21;
  87345. var off_RGBbpp = 22;
  87346. var off_RMask = 23;
  87347. var off_GMask = 24;
  87348. var off_BMask = 25;
  87349. var off_AMask = 26;
  87350. // var off_caps1 = 27;
  87351. var off_caps2 = 28;
  87352. // var off_caps3 = 29;
  87353. // var off_caps4 = 30;
  87354. var off_dxgiFormat = 32;
  87355. ;
  87356. var DDSTools = /** @class */ (function () {
  87357. function DDSTools() {
  87358. }
  87359. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87360. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87361. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87362. var mipmapCount = 1;
  87363. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87364. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87365. }
  87366. var fourCC = header[off_pfFourCC];
  87367. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87368. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87369. switch (fourCC) {
  87370. case FOURCC_D3DFMT_R16G16B16A16F:
  87371. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87372. break;
  87373. case FOURCC_D3DFMT_R32G32B32A32F:
  87374. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87375. break;
  87376. case FOURCC_DX10:
  87377. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87378. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87379. break;
  87380. }
  87381. }
  87382. return {
  87383. width: header[off_width],
  87384. height: header[off_height],
  87385. mipmapCount: mipmapCount,
  87386. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87387. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87388. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87389. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87390. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87391. dxgiFormat: dxgiFormat,
  87392. textureType: textureType
  87393. };
  87394. };
  87395. DDSTools._ToHalfFloat = function (value) {
  87396. if (!DDSTools._FloatView) {
  87397. DDSTools._FloatView = new Float32Array(1);
  87398. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87399. }
  87400. DDSTools._FloatView[0] = value;
  87401. var x = DDSTools._Int32View[0];
  87402. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87403. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87404. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87405. /* If zero, or denormal, or exponent underflows too much for a denormal
  87406. * half, return signed zero. */
  87407. if (e < 103) {
  87408. return bits;
  87409. }
  87410. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87411. if (e > 142) {
  87412. bits |= 0x7c00;
  87413. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87414. * not Inf, so make sure we set one mantissa bit too. */
  87415. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87416. return bits;
  87417. }
  87418. /* If exponent underflows but not too much, return a denormal */
  87419. if (e < 113) {
  87420. m |= 0x0800;
  87421. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87422. * to 1, which is OK. */
  87423. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87424. return bits;
  87425. }
  87426. bits |= ((e - 112) << 10) | (m >> 1);
  87427. bits += m & 1;
  87428. return bits;
  87429. };
  87430. DDSTools._FromHalfFloat = function (value) {
  87431. var s = (value & 0x8000) >> 15;
  87432. var e = (value & 0x7C00) >> 10;
  87433. var f = value & 0x03FF;
  87434. if (e === 0) {
  87435. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87436. }
  87437. else if (e == 0x1F) {
  87438. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87439. }
  87440. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87441. };
  87442. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87443. var destArray = new Float32Array(dataLength);
  87444. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87445. var index = 0;
  87446. for (var y = 0; y < height; y++) {
  87447. for (var x = 0; x < width; x++) {
  87448. var srcPos = (x + y * width) * 4;
  87449. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87450. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87451. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87452. if (DDSTools.StoreLODInAlphaChannel) {
  87453. destArray[index + 3] = lod;
  87454. }
  87455. else {
  87456. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87457. }
  87458. index += 4;
  87459. }
  87460. }
  87461. return destArray;
  87462. };
  87463. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87464. if (DDSTools.StoreLODInAlphaChannel) {
  87465. var destArray = new Uint16Array(dataLength);
  87466. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87467. var index = 0;
  87468. for (var y = 0; y < height; y++) {
  87469. for (var x = 0; x < width; x++) {
  87470. var srcPos = (x + y * width) * 4;
  87471. destArray[index] = srcData[srcPos];
  87472. destArray[index + 1] = srcData[srcPos + 1];
  87473. destArray[index + 2] = srcData[srcPos + 2];
  87474. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87475. index += 4;
  87476. }
  87477. }
  87478. return destArray;
  87479. }
  87480. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87481. };
  87482. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87483. if (DDSTools.StoreLODInAlphaChannel) {
  87484. var destArray = new Float32Array(dataLength);
  87485. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87486. var index = 0;
  87487. for (var y = 0; y < height; y++) {
  87488. for (var x = 0; x < width; x++) {
  87489. var srcPos = (x + y * width) * 4;
  87490. destArray[index] = srcData[srcPos];
  87491. destArray[index + 1] = srcData[srcPos + 1];
  87492. destArray[index + 2] = srcData[srcPos + 2];
  87493. destArray[index + 3] = lod;
  87494. index += 4;
  87495. }
  87496. }
  87497. return destArray;
  87498. }
  87499. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87500. };
  87501. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87502. var destArray = new Uint8Array(dataLength);
  87503. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87504. var index = 0;
  87505. for (var y = 0; y < height; y++) {
  87506. for (var x = 0; x < width; x++) {
  87507. var srcPos = (x + y * width) * 4;
  87508. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87509. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87510. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87511. if (DDSTools.StoreLODInAlphaChannel) {
  87512. destArray[index + 3] = lod;
  87513. }
  87514. else {
  87515. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87516. }
  87517. index += 4;
  87518. }
  87519. }
  87520. return destArray;
  87521. };
  87522. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87523. var destArray = new Uint8Array(dataLength);
  87524. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87525. var index = 0;
  87526. for (var y = 0; y < height; y++) {
  87527. for (var x = 0; x < width; x++) {
  87528. var srcPos = (x + y * width) * 4;
  87529. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87530. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87531. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87532. if (DDSTools.StoreLODInAlphaChannel) {
  87533. destArray[index + 3] = lod;
  87534. }
  87535. else {
  87536. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87537. }
  87538. index += 4;
  87539. }
  87540. }
  87541. return destArray;
  87542. };
  87543. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87544. var byteArray = new Uint8Array(dataLength);
  87545. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87546. var index = 0;
  87547. for (var y = 0; y < height; y++) {
  87548. for (var x = 0; x < width; x++) {
  87549. var srcPos = (x + y * width) * 4;
  87550. byteArray[index] = srcData[srcPos + rOffset];
  87551. byteArray[index + 1] = srcData[srcPos + gOffset];
  87552. byteArray[index + 2] = srcData[srcPos + bOffset];
  87553. byteArray[index + 3] = srcData[srcPos + aOffset];
  87554. index += 4;
  87555. }
  87556. }
  87557. return byteArray;
  87558. };
  87559. DDSTools._ExtractLongWordOrder = function (value) {
  87560. if (value === 0 || value === 255 || value === -16777216) {
  87561. return 0;
  87562. }
  87563. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87564. };
  87565. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87566. var byteArray = new Uint8Array(dataLength);
  87567. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87568. var index = 0;
  87569. for (var y = 0; y < height; y++) {
  87570. for (var x = 0; x < width; x++) {
  87571. var srcPos = (x + y * width) * 3;
  87572. byteArray[index] = srcData[srcPos + rOffset];
  87573. byteArray[index + 1] = srcData[srcPos + gOffset];
  87574. byteArray[index + 2] = srcData[srcPos + bOffset];
  87575. index += 3;
  87576. }
  87577. }
  87578. return byteArray;
  87579. };
  87580. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87581. var byteArray = new Uint8Array(dataLength);
  87582. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87583. var index = 0;
  87584. for (var y = 0; y < height; y++) {
  87585. for (var x = 0; x < width; x++) {
  87586. var srcPos = (x + y * width);
  87587. byteArray[index] = srcData[srcPos];
  87588. index++;
  87589. }
  87590. }
  87591. return byteArray;
  87592. };
  87593. /**
  87594. * Uploads DDS Levels to a Babylon Texture
  87595. * @hidden
  87596. */
  87597. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87598. if (lodIndex === void 0) { lodIndex = -1; }
  87599. var sphericalPolynomialFaces = null;
  87600. if (info.sphericalPolynomial) {
  87601. sphericalPolynomialFaces = new Array();
  87602. }
  87603. var ext = engine.getCaps().s3tc;
  87604. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87605. var fourCC, width, height, dataLength = 0, dataOffset;
  87606. var byteArray, mipmapCount, mip;
  87607. var internalCompressedFormat = 0;
  87608. var blockBytes = 1;
  87609. if (header[off_magic] !== DDS_MAGIC) {
  87610. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87611. return;
  87612. }
  87613. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87614. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87615. return;
  87616. }
  87617. if (info.isCompressed && !ext) {
  87618. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87619. return;
  87620. }
  87621. var bpp = header[off_RGBbpp];
  87622. dataOffset = header[off_size] + 4;
  87623. var computeFormats = false;
  87624. if (info.isFourCC) {
  87625. fourCC = header[off_pfFourCC];
  87626. switch (fourCC) {
  87627. case FOURCC_DXT1:
  87628. blockBytes = 8;
  87629. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87630. break;
  87631. case FOURCC_DXT3:
  87632. blockBytes = 16;
  87633. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87634. break;
  87635. case FOURCC_DXT5:
  87636. blockBytes = 16;
  87637. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87638. break;
  87639. case FOURCC_D3DFMT_R16G16B16A16F:
  87640. computeFormats = true;
  87641. break;
  87642. case FOURCC_D3DFMT_R32G32B32A32F:
  87643. computeFormats = true;
  87644. break;
  87645. case FOURCC_DX10:
  87646. // There is an additionnal header so dataOffset need to be changed
  87647. dataOffset += 5 * 4; // 5 uints
  87648. var supported = false;
  87649. switch (info.dxgiFormat) {
  87650. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87651. computeFormats = true;
  87652. supported = true;
  87653. break;
  87654. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87655. info.isRGB = true;
  87656. info.isFourCC = false;
  87657. bpp = 32;
  87658. supported = true;
  87659. break;
  87660. }
  87661. if (supported) {
  87662. break;
  87663. }
  87664. default:
  87665. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87666. return;
  87667. }
  87668. }
  87669. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87670. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87671. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87672. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87673. if (computeFormats) {
  87674. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87675. }
  87676. mipmapCount = 1;
  87677. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87678. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87679. }
  87680. for (var face = 0; face < faces; face++) {
  87681. width = header[off_width];
  87682. height = header[off_height];
  87683. for (mip = 0; mip < mipmapCount; ++mip) {
  87684. if (lodIndex === -1 || lodIndex === mip) {
  87685. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87686. var i = (lodIndex === -1) ? mip : 0;
  87687. if (!info.isCompressed && info.isFourCC) {
  87688. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87689. dataLength = width * height * 4;
  87690. var floatArray = null;
  87691. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87692. if (bpp === 128) {
  87693. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87694. if (sphericalPolynomialFaces && i == 0) {
  87695. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87696. }
  87697. }
  87698. else if (bpp === 64) {
  87699. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87700. if (sphericalPolynomialFaces && i == 0) {
  87701. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87702. }
  87703. }
  87704. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87705. }
  87706. else {
  87707. if (bpp === 128) {
  87708. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87709. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87710. if (sphericalPolynomialFaces && i == 0) {
  87711. sphericalPolynomialFaces.push(floatArray);
  87712. }
  87713. }
  87714. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87715. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87716. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87717. if (sphericalPolynomialFaces && i == 0) {
  87718. sphericalPolynomialFaces.push(floatArray);
  87719. }
  87720. }
  87721. else { // 64
  87722. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87723. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87724. if (sphericalPolynomialFaces && i == 0) {
  87725. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87726. }
  87727. }
  87728. }
  87729. if (floatArray) {
  87730. engine._uploadDataToTextureDirectly(texture, width, height, floatArray, face, i);
  87731. }
  87732. }
  87733. else if (info.isRGB) {
  87734. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87735. if (bpp === 24) {
  87736. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  87737. dataLength = width * height * 3;
  87738. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87739. engine._uploadDataToTextureDirectly(texture, width, height, byteArray, face, i);
  87740. }
  87741. else { // 32
  87742. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87743. dataLength = width * height * 4;
  87744. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87745. engine._uploadDataToTextureDirectly(texture, width, height, byteArray, face, i);
  87746. }
  87747. }
  87748. else if (info.isLuminance) {
  87749. var unpackAlignment = engine._getUnpackAlignement();
  87750. var unpaddedRowSize = width;
  87751. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87752. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87753. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87754. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  87755. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87756. engine._uploadDataToTextureDirectly(texture, width, height, byteArray, face, i);
  87757. }
  87758. else {
  87759. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87760. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87761. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87762. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  87763. }
  87764. }
  87765. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87766. width *= 0.5;
  87767. height *= 0.5;
  87768. width = Math.max(1.0, width);
  87769. height = Math.max(1.0, height);
  87770. }
  87771. if (currentFace !== undefined) {
  87772. // Loading a single face
  87773. break;
  87774. }
  87775. }
  87776. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87777. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87778. size: header[off_width],
  87779. right: sphericalPolynomialFaces[0],
  87780. left: sphericalPolynomialFaces[1],
  87781. up: sphericalPolynomialFaces[2],
  87782. down: sphericalPolynomialFaces[3],
  87783. front: sphericalPolynomialFaces[4],
  87784. back: sphericalPolynomialFaces[5],
  87785. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87786. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87787. gammaSpace: false,
  87788. });
  87789. }
  87790. else {
  87791. info.sphericalPolynomial = undefined;
  87792. }
  87793. };
  87794. DDSTools.StoreLODInAlphaChannel = false;
  87795. return DDSTools;
  87796. }());
  87797. BABYLON.DDSTools = DDSTools;
  87798. })(BABYLON || (BABYLON = {}));
  87799. //# sourceMappingURL=babylon.dds.js.map
  87800. var BABYLON;
  87801. (function (BABYLON) {
  87802. /**
  87803. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87804. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87805. */
  87806. var KhronosTextureContainer = /** @class */ (function () {
  87807. /**
  87808. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87809. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87810. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87811. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87812. */
  87813. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87814. this.arrayBuffer = arrayBuffer;
  87815. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87816. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87817. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87818. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87819. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87820. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87821. BABYLON.Tools.Error("texture missing KTX identifier");
  87822. return;
  87823. }
  87824. // load the reset of the header in native 32 bit int
  87825. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87826. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87827. var oppositeEndianess = header[0] === 0x01020304;
  87828. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87829. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87830. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87831. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87832. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87833. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87834. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87835. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87836. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87837. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87838. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87839. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87840. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87841. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87842. if (this.glType !== 0) {
  87843. BABYLON.Tools.Error("only compressed formats currently supported");
  87844. return;
  87845. }
  87846. else {
  87847. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87848. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87849. }
  87850. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87851. BABYLON.Tools.Error("only 2D textures currently supported");
  87852. return;
  87853. }
  87854. if (this.numberOfArrayElements !== 0) {
  87855. BABYLON.Tools.Error("texture arrays not currently supported");
  87856. return;
  87857. }
  87858. if (this.numberOfFaces !== facesExpected) {
  87859. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87860. return;
  87861. }
  87862. // we now have a completely validated file, so could use existence of loadType as success
  87863. // would need to make this more elaborate & adjust checks above to support more than one load type
  87864. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87865. }
  87866. // not as fast hardware based, but will probably never need to use
  87867. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87868. return ((val & 0xFF) << 24)
  87869. | ((val & 0xFF00) << 8)
  87870. | ((val >> 8) & 0xFF00)
  87871. | ((val >> 24) & 0xFF);
  87872. };
  87873. /**
  87874. * Uploads KTX content to a Babylon Texture.
  87875. * It is assumed that the texture has already been created & is currently bound
  87876. * @hidden
  87877. */
  87878. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  87879. switch (this.loadType) {
  87880. case KhronosTextureContainer.COMPRESSED_2D:
  87881. this._upload2DCompressedLevels(texture, loadMipmaps);
  87882. break;
  87883. case KhronosTextureContainer.TEX_2D:
  87884. case KhronosTextureContainer.COMPRESSED_3D:
  87885. case KhronosTextureContainer.TEX_3D:
  87886. }
  87887. };
  87888. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  87889. // initialize width & height for level 1
  87890. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87891. var width = this.pixelWidth;
  87892. var height = this.pixelHeight;
  87893. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87894. for (var level = 0; level < mipmapCount; level++) {
  87895. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87896. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87897. for (var face = 0; face < this.numberOfFaces; face++) {
  87898. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87899. var engine = texture.getEngine();
  87900. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  87901. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87902. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87903. }
  87904. width = Math.max(1.0, width * 0.5);
  87905. height = Math.max(1.0, height * 0.5);
  87906. }
  87907. };
  87908. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87909. // load types
  87910. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87911. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87912. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87913. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87914. return KhronosTextureContainer;
  87915. }());
  87916. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87917. })(BABYLON || (BABYLON = {}));
  87918. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87919. var BABYLON;
  87920. (function (BABYLON) {
  87921. var Debug;
  87922. (function (Debug) {
  87923. /**
  87924. * Class used to render a debug view of a given skeleton
  87925. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87926. */
  87927. var SkeletonViewer = /** @class */ (function () {
  87928. /**
  87929. * Creates a new SkeletonViewer
  87930. * @param skeleton defines the skeleton to render
  87931. * @param mesh defines the mesh attached to the skeleton
  87932. * @param scene defines the hosting scene
  87933. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87934. * @param renderingGroupId defines the rendering group id to use with the viewer
  87935. */
  87936. function SkeletonViewer(
  87937. /** defines the skeleton to render */
  87938. skeleton,
  87939. /** defines the mesh attached to the skeleton */
  87940. mesh, scene,
  87941. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87942. autoUpdateBonesMatrices,
  87943. /** defines the rendering group id to use with the viewer */
  87944. renderingGroupId) {
  87945. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87946. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87947. this.skeleton = skeleton;
  87948. this.mesh = mesh;
  87949. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87950. this.renderingGroupId = renderingGroupId;
  87951. /** Gets or sets the color used to render the skeleton */
  87952. this.color = BABYLON.Color3.White();
  87953. this._debugLines = new Array();
  87954. this._isEnabled = false;
  87955. this._scene = scene;
  87956. this.update();
  87957. this._renderFunction = this.update.bind(this);
  87958. }
  87959. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87960. get: function () {
  87961. return this._isEnabled;
  87962. },
  87963. /** Gets or sets a boolean indicating if the viewer is enabled */
  87964. set: function (value) {
  87965. if (this._isEnabled === value) {
  87966. return;
  87967. }
  87968. this._isEnabled = value;
  87969. if (value) {
  87970. this._scene.registerBeforeRender(this._renderFunction);
  87971. }
  87972. else {
  87973. this._scene.unregisterBeforeRender(this._renderFunction);
  87974. }
  87975. },
  87976. enumerable: true,
  87977. configurable: true
  87978. });
  87979. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87980. if (x === void 0) { x = 0; }
  87981. if (y === void 0) { y = 0; }
  87982. if (z === void 0) { z = 0; }
  87983. var tmat = BABYLON.Tmp.Matrix[0];
  87984. var parentBone = bone.getParent();
  87985. tmat.copyFrom(bone.getLocalMatrix());
  87986. if (x !== 0 || y !== 0 || z !== 0) {
  87987. var tmat2 = BABYLON.Tmp.Matrix[1];
  87988. BABYLON.Matrix.IdentityToRef(tmat2);
  87989. tmat2.m[12] = x;
  87990. tmat2.m[13] = y;
  87991. tmat2.m[14] = z;
  87992. tmat2.multiplyToRef(tmat, tmat);
  87993. }
  87994. if (parentBone) {
  87995. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87996. }
  87997. tmat.multiplyToRef(meshMat, tmat);
  87998. position.x = tmat.m[12];
  87999. position.y = tmat.m[13];
  88000. position.z = tmat.m[14];
  88001. };
  88002. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  88003. var len = bones.length;
  88004. var meshPos = this.mesh.position;
  88005. for (var i = 0; i < len; i++) {
  88006. var bone = bones[i];
  88007. var points = this._debugLines[i];
  88008. if (!points) {
  88009. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88010. this._debugLines[i] = points;
  88011. }
  88012. this._getBonePosition(points[0], bone, meshMat);
  88013. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  88014. points[0].subtractInPlace(meshPos);
  88015. points[1].subtractInPlace(meshPos);
  88016. }
  88017. };
  88018. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  88019. var len = bones.length;
  88020. var boneNum = 0;
  88021. var meshPos = this.mesh.position;
  88022. for (var i = len - 1; i >= 0; i--) {
  88023. var childBone = bones[i];
  88024. var parentBone = childBone.getParent();
  88025. if (!parentBone) {
  88026. continue;
  88027. }
  88028. var points = this._debugLines[boneNum];
  88029. if (!points) {
  88030. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88031. this._debugLines[boneNum] = points;
  88032. }
  88033. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  88034. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  88035. points[0].subtractInPlace(meshPos);
  88036. points[1].subtractInPlace(meshPos);
  88037. boneNum++;
  88038. }
  88039. };
  88040. /** Update the viewer to sync with current skeleton state */
  88041. SkeletonViewer.prototype.update = function () {
  88042. if (this.autoUpdateBonesMatrices) {
  88043. this.skeleton.computeAbsoluteTransforms();
  88044. }
  88045. if (this.skeleton.bones[0].length === undefined) {
  88046. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  88047. }
  88048. else {
  88049. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  88050. }
  88051. if (!this._debugMesh) {
  88052. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  88053. this._debugMesh.renderingGroupId = this.renderingGroupId;
  88054. }
  88055. else {
  88056. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  88057. }
  88058. this._debugMesh.position.copyFrom(this.mesh.position);
  88059. this._debugMesh.color = this.color;
  88060. };
  88061. /** Release associated resources */
  88062. SkeletonViewer.prototype.dispose = function () {
  88063. if (this._debugMesh) {
  88064. this.isEnabled = false;
  88065. this._debugMesh.dispose();
  88066. this._debugMesh = null;
  88067. }
  88068. };
  88069. return SkeletonViewer;
  88070. }());
  88071. Debug.SkeletonViewer = SkeletonViewer;
  88072. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88073. })(BABYLON || (BABYLON = {}));
  88074. //# sourceMappingURL=babylon.skeletonViewer.js.map
  88075. /**
  88076. * Module Debug contains the (visual) components to debug a scene correctly
  88077. */
  88078. var BABYLON;
  88079. (function (BABYLON) {
  88080. var Debug;
  88081. (function (Debug) {
  88082. /**
  88083. * The Axes viewer will show 3 axes in a specific point in space
  88084. */
  88085. var AxesViewer = /** @class */ (function () {
  88086. /**
  88087. * Creates a new AxesViewer
  88088. * @param scene defines the hosting scene
  88089. * @param scaleLines defines a number used to scale line length (1 by default)
  88090. */
  88091. function AxesViewer(scene, scaleLines) {
  88092. if (scaleLines === void 0) { scaleLines = 1; }
  88093. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88094. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88095. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88096. /**
  88097. * Gets or sets a number used to scale line length
  88098. */
  88099. this.scaleLines = 1;
  88100. this.scaleLines = scaleLines;
  88101. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  88102. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  88103. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  88104. this._xmesh.renderingGroupId = 2;
  88105. this._ymesh.renderingGroupId = 2;
  88106. this._zmesh.renderingGroupId = 2;
  88107. this._xmesh.material.checkReadyOnlyOnce = true;
  88108. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  88109. this._ymesh.material.checkReadyOnlyOnce = true;
  88110. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  88111. this._zmesh.material.checkReadyOnlyOnce = true;
  88112. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  88113. this.scene = scene;
  88114. }
  88115. /**
  88116. * Force the viewer to update
  88117. * @param position defines the position of the viewer
  88118. * @param xaxis defines the x axis of the viewer
  88119. * @param yaxis defines the y axis of the viewer
  88120. * @param zaxis defines the z axis of the viewer
  88121. */
  88122. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  88123. var scaleLines = this.scaleLines;
  88124. if (this._xmesh) {
  88125. this._xmesh.position.copyFrom(position);
  88126. }
  88127. if (this._ymesh) {
  88128. this._ymesh.position.copyFrom(position);
  88129. }
  88130. if (this._zmesh) {
  88131. this._zmesh.position.copyFrom(position);
  88132. }
  88133. var point2 = this._xline[1];
  88134. point2.x = xaxis.x * scaleLines;
  88135. point2.y = xaxis.y * scaleLines;
  88136. point2.z = xaxis.z * scaleLines;
  88137. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  88138. point2 = this._yline[1];
  88139. point2.x = yaxis.x * scaleLines;
  88140. point2.y = yaxis.y * scaleLines;
  88141. point2.z = yaxis.z * scaleLines;
  88142. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  88143. point2 = this._zline[1];
  88144. point2.x = zaxis.x * scaleLines;
  88145. point2.y = zaxis.y * scaleLines;
  88146. point2.z = zaxis.z * scaleLines;
  88147. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  88148. };
  88149. /** Releases resources */
  88150. AxesViewer.prototype.dispose = function () {
  88151. if (this._xmesh) {
  88152. this._xmesh.dispose();
  88153. }
  88154. if (this._ymesh) {
  88155. this._ymesh.dispose();
  88156. }
  88157. if (this._zmesh) {
  88158. this._zmesh.dispose();
  88159. }
  88160. this._xmesh = null;
  88161. this._ymesh = null;
  88162. this._zmesh = null;
  88163. this.scene = null;
  88164. };
  88165. return AxesViewer;
  88166. }());
  88167. Debug.AxesViewer = AxesViewer;
  88168. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88169. })(BABYLON || (BABYLON = {}));
  88170. //# sourceMappingURL=babylon.axesViewer.js.map
  88171. var BABYLON;
  88172. (function (BABYLON) {
  88173. var Debug;
  88174. (function (Debug) {
  88175. /**
  88176. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  88177. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  88178. */
  88179. var BoneAxesViewer = /** @class */ (function (_super) {
  88180. __extends(BoneAxesViewer, _super);
  88181. /**
  88182. * Creates a new BoneAxesViewer
  88183. * @param scene defines the hosting scene
  88184. * @param bone defines the target bone
  88185. * @param mesh defines the target mesh
  88186. * @param scaleLines defines a scaling factor for line length (1 by default)
  88187. */
  88188. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  88189. if (scaleLines === void 0) { scaleLines = 1; }
  88190. var _this = _super.call(this, scene, scaleLines) || this;
  88191. /** Gets current position */
  88192. _this.pos = BABYLON.Vector3.Zero();
  88193. /** Gets direction of X axis */
  88194. _this.xaxis = BABYLON.Vector3.Zero();
  88195. /** Gets direction of Y axis */
  88196. _this.yaxis = BABYLON.Vector3.Zero();
  88197. /** Gets direction of Z axis */
  88198. _this.zaxis = BABYLON.Vector3.Zero();
  88199. _this.mesh = mesh;
  88200. _this.bone = bone;
  88201. return _this;
  88202. }
  88203. /**
  88204. * Force the viewer to update
  88205. */
  88206. BoneAxesViewer.prototype.update = function () {
  88207. if (!this.mesh || !this.bone) {
  88208. return;
  88209. }
  88210. var bone = this.bone;
  88211. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  88212. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  88213. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  88214. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  88215. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  88216. };
  88217. /** Releases resources */
  88218. BoneAxesViewer.prototype.dispose = function () {
  88219. if (this.mesh) {
  88220. this.mesh = null;
  88221. this.bone = null;
  88222. _super.prototype.dispose.call(this);
  88223. }
  88224. };
  88225. return BoneAxesViewer;
  88226. }(Debug.AxesViewer));
  88227. Debug.BoneAxesViewer = BoneAxesViewer;
  88228. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88229. })(BABYLON || (BABYLON = {}));
  88230. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  88231. var BABYLON;
  88232. (function (BABYLON) {
  88233. var RayHelper = /** @class */ (function () {
  88234. function RayHelper(ray) {
  88235. this.ray = ray;
  88236. }
  88237. RayHelper.CreateAndShow = function (ray, scene, color) {
  88238. var helper = new RayHelper(ray);
  88239. helper.show(scene, color);
  88240. return helper;
  88241. };
  88242. RayHelper.prototype.show = function (scene, color) {
  88243. if (!this._renderFunction && this.ray) {
  88244. var ray = this.ray;
  88245. this._renderFunction = this._render.bind(this);
  88246. this._scene = scene;
  88247. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  88248. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  88249. if (this._renderFunction) {
  88250. this._scene.registerBeforeRender(this._renderFunction);
  88251. }
  88252. }
  88253. if (color && this._renderLine) {
  88254. this._renderLine.color.copyFrom(color);
  88255. }
  88256. };
  88257. RayHelper.prototype.hide = function () {
  88258. if (this._renderFunction && this._scene) {
  88259. this._scene.unregisterBeforeRender(this._renderFunction);
  88260. this._scene = null;
  88261. this._renderFunction = null;
  88262. if (this._renderLine) {
  88263. this._renderLine.dispose();
  88264. this._renderLine = null;
  88265. }
  88266. this._renderPoints = [];
  88267. }
  88268. };
  88269. RayHelper.prototype._render = function () {
  88270. var ray = this.ray;
  88271. if (!ray) {
  88272. return;
  88273. }
  88274. var point = this._renderPoints[1];
  88275. var len = Math.min(ray.length, 1000000);
  88276. point.copyFrom(ray.direction);
  88277. point.scaleInPlace(len);
  88278. point.addInPlace(ray.origin);
  88279. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  88280. };
  88281. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  88282. this._attachedToMesh = mesh;
  88283. var ray = this.ray;
  88284. if (!ray) {
  88285. return;
  88286. }
  88287. if (!ray.direction) {
  88288. ray.direction = BABYLON.Vector3.Zero();
  88289. }
  88290. if (!ray.origin) {
  88291. ray.origin = BABYLON.Vector3.Zero();
  88292. }
  88293. if (length) {
  88294. ray.length = length;
  88295. }
  88296. if (!meshSpaceOrigin) {
  88297. meshSpaceOrigin = BABYLON.Vector3.Zero();
  88298. }
  88299. if (!meshSpaceDirection) {
  88300. // -1 so that this will work with Mesh.lookAt
  88301. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  88302. }
  88303. if (!this._meshSpaceDirection) {
  88304. this._meshSpaceDirection = meshSpaceDirection.clone();
  88305. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  88306. }
  88307. else {
  88308. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  88309. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  88310. }
  88311. if (!this._updateToMeshFunction) {
  88312. this._updateToMeshFunction = this._updateToMesh.bind(this);
  88313. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  88314. }
  88315. this._updateToMesh();
  88316. };
  88317. RayHelper.prototype.detachFromMesh = function () {
  88318. if (this._attachedToMesh) {
  88319. if (this._updateToMeshFunction) {
  88320. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  88321. }
  88322. this._attachedToMesh = null;
  88323. this._updateToMeshFunction = null;
  88324. }
  88325. };
  88326. RayHelper.prototype._updateToMesh = function () {
  88327. var ray = this.ray;
  88328. if (!this._attachedToMesh || !ray) {
  88329. return;
  88330. }
  88331. if (this._attachedToMesh._isDisposed) {
  88332. this.detachFromMesh();
  88333. return;
  88334. }
  88335. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  88336. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  88337. };
  88338. RayHelper.prototype.dispose = function () {
  88339. this.hide();
  88340. this.detachFromMesh();
  88341. this.ray = null;
  88342. };
  88343. return RayHelper;
  88344. }());
  88345. BABYLON.RayHelper = RayHelper;
  88346. })(BABYLON || (BABYLON = {}));
  88347. //# sourceMappingURL=babylon.rayHelper.js.map
  88348. var BABYLON;
  88349. (function (BABYLON) {
  88350. // load the inspector using require, if not present in the global namespace.
  88351. var DebugLayer = /** @class */ (function () {
  88352. function DebugLayer(scene) {
  88353. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88354. this._scene = scene;
  88355. // load inspector using require, if it doesn't exist on the global namespace.
  88356. }
  88357. /** Creates the inspector window. */
  88358. DebugLayer.prototype._createInspector = function (config) {
  88359. if (config === void 0) { config = {}; }
  88360. var popup = config.popup || false;
  88361. var initialTab = config.initialTab || 0;
  88362. var parentElement = config.parentElement || null;
  88363. if (!this._inspector) {
  88364. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88365. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  88366. } // else nothing to do,; instance is already existing
  88367. };
  88368. DebugLayer.prototype.isVisible = function () {
  88369. if (!this._inspector) {
  88370. return false;
  88371. }
  88372. return true;
  88373. };
  88374. DebugLayer.prototype.hide = function () {
  88375. if (this._inspector) {
  88376. try {
  88377. this._inspector.dispose();
  88378. }
  88379. catch (e) {
  88380. // If the inspector has been removed directly from the inspector tool
  88381. }
  88382. this.onPropertyChangedObservable.clear();
  88383. this._inspector = null;
  88384. }
  88385. };
  88386. /**
  88387. *
  88388. * Launch the debugLayer.
  88389. *
  88390. * initialTab:
  88391. * | Value | Tab Name |
  88392. * | --- | --- |
  88393. * | 0 | Scene |
  88394. * | 1 | Console |
  88395. * | 2 | Stats |
  88396. * | 3 | Textures |
  88397. * | 4 | Mesh |
  88398. * | 5 | Light |
  88399. * | 6 | Material |
  88400. * | 7 | GLTF |
  88401. * | 8 | GUI |
  88402. * | 9 | Physics |
  88403. * | 10 | Camera |
  88404. * | 11 | Audio |
  88405. *
  88406. */
  88407. DebugLayer.prototype.show = function (config) {
  88408. if (config === void 0) { config = {}; }
  88409. if (typeof this.BJSINSPECTOR == 'undefined') {
  88410. // Load inspector and add it to the DOM
  88411. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  88412. }
  88413. else {
  88414. // Otherwise creates the inspector
  88415. this._createInspector(config);
  88416. this.onPropertyChangedObservable = new BABYLON.Observable();
  88417. }
  88418. };
  88419. /**
  88420. * Gets the active tab
  88421. * @return the index of the active tab or -1 if the inspector is hidden
  88422. */
  88423. DebugLayer.prototype.getActiveTab = function () {
  88424. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  88425. };
  88426. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  88427. return DebugLayer;
  88428. }());
  88429. BABYLON.DebugLayer = DebugLayer;
  88430. })(BABYLON || (BABYLON = {}));
  88431. //# sourceMappingURL=babylon.debugLayer.js.map
  88432. var BABYLON;
  88433. (function (BABYLON) {
  88434. var Debug;
  88435. (function (Debug) {
  88436. /**
  88437. * Used to show the physics impostor around the specific mesh
  88438. */
  88439. var PhysicsViewer = /** @class */ (function () {
  88440. /**
  88441. * Creates a new PhysicsViewer
  88442. * @param scene defines the hosting scene
  88443. */
  88444. function PhysicsViewer(scene) {
  88445. /** @hidden */
  88446. this._impostors = [];
  88447. /** @hidden */
  88448. this._meshes = [];
  88449. /** @hidden */
  88450. this._numMeshes = 0;
  88451. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88452. var physicEngine = this._scene.getPhysicsEngine();
  88453. if (physicEngine) {
  88454. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88455. }
  88456. }
  88457. /** @hidden */
  88458. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88459. var plugin = this._physicsEnginePlugin;
  88460. for (var i = 0; i < this._numMeshes; i++) {
  88461. var impostor = this._impostors[i];
  88462. if (!impostor) {
  88463. continue;
  88464. }
  88465. if (impostor.isDisposed) {
  88466. this.hideImpostor(this._impostors[i--]);
  88467. }
  88468. else {
  88469. var mesh = this._meshes[i];
  88470. if (mesh && plugin) {
  88471. plugin.syncMeshWithImpostor(mesh, impostor);
  88472. }
  88473. }
  88474. }
  88475. };
  88476. /**
  88477. * Renders a specified physic impostor
  88478. * @param impostor defines the impostor to render
  88479. */
  88480. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88481. if (!this._scene) {
  88482. return;
  88483. }
  88484. for (var i = 0; i < this._numMeshes; i++) {
  88485. if (this._impostors[i] == impostor) {
  88486. return;
  88487. }
  88488. }
  88489. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88490. if (debugMesh) {
  88491. this._impostors[this._numMeshes] = impostor;
  88492. this._meshes[this._numMeshes] = debugMesh;
  88493. if (this._numMeshes === 0) {
  88494. this._renderFunction = this._updateDebugMeshes.bind(this);
  88495. this._scene.registerBeforeRender(this._renderFunction);
  88496. }
  88497. this._numMeshes++;
  88498. }
  88499. };
  88500. /**
  88501. * Hides a specified physic impostor
  88502. * @param impostor defines the impostor to hide
  88503. */
  88504. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88505. if (!impostor || !this._scene) {
  88506. return;
  88507. }
  88508. var removed = false;
  88509. for (var i = 0; i < this._numMeshes; i++) {
  88510. if (this._impostors[i] == impostor) {
  88511. var mesh = this._meshes[i];
  88512. if (!mesh) {
  88513. continue;
  88514. }
  88515. this._scene.removeMesh(mesh);
  88516. mesh.dispose();
  88517. this._numMeshes--;
  88518. if (this._numMeshes > 0) {
  88519. this._meshes[i] = this._meshes[this._numMeshes];
  88520. this._impostors[i] = this._impostors[this._numMeshes];
  88521. this._meshes[this._numMeshes] = null;
  88522. this._impostors[this._numMeshes] = null;
  88523. }
  88524. else {
  88525. this._meshes[0] = null;
  88526. this._impostors[0] = null;
  88527. }
  88528. removed = true;
  88529. break;
  88530. }
  88531. }
  88532. if (removed && this._numMeshes === 0) {
  88533. this._scene.unregisterBeforeRender(this._renderFunction);
  88534. }
  88535. };
  88536. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88537. if (!this._debugMaterial) {
  88538. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88539. this._debugMaterial.wireframe = true;
  88540. }
  88541. return this._debugMaterial;
  88542. };
  88543. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88544. if (!this._debugBoxMesh) {
  88545. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88546. this._debugBoxMesh.renderingGroupId = 1;
  88547. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88548. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88549. scene.removeMesh(this._debugBoxMesh);
  88550. }
  88551. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88552. };
  88553. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88554. if (!this._debugSphereMesh) {
  88555. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88556. this._debugSphereMesh.renderingGroupId = 1;
  88557. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88558. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88559. scene.removeMesh(this._debugSphereMesh);
  88560. }
  88561. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88562. };
  88563. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88564. var mesh = null;
  88565. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88566. mesh = this._getDebugBoxMesh(scene);
  88567. impostor.getBoxSizeToRef(mesh.scaling);
  88568. }
  88569. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88570. mesh = this._getDebugSphereMesh(scene);
  88571. var radius = impostor.getRadius();
  88572. mesh.scaling.x = radius * 2;
  88573. mesh.scaling.y = radius * 2;
  88574. mesh.scaling.z = radius * 2;
  88575. }
  88576. return mesh;
  88577. };
  88578. /** Releases all resources */
  88579. PhysicsViewer.prototype.dispose = function () {
  88580. for (var i = 0; i < this._numMeshes; i++) {
  88581. this.hideImpostor(this._impostors[i]);
  88582. }
  88583. if (this._debugBoxMesh) {
  88584. this._debugBoxMesh.dispose();
  88585. }
  88586. if (this._debugSphereMesh) {
  88587. this._debugSphereMesh.dispose();
  88588. }
  88589. if (this._debugMaterial) {
  88590. this._debugMaterial.dispose();
  88591. }
  88592. this._impostors.length = 0;
  88593. this._scene = null;
  88594. this._physicsEnginePlugin = null;
  88595. };
  88596. return PhysicsViewer;
  88597. }());
  88598. Debug.PhysicsViewer = PhysicsViewer;
  88599. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88600. })(BABYLON || (BABYLON = {}));
  88601. //# sourceMappingURL=babylon.physicsViewer.js.map
  88602. var BABYLON;
  88603. (function (BABYLON) {
  88604. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  88605. get: function () {
  88606. return this._forceShowBoundingBoxes || false;
  88607. },
  88608. set: function (value) {
  88609. this._forceShowBoundingBoxes = value;
  88610. // Lazyly creates a BB renderer if needed.
  88611. if (value) {
  88612. this.getBoundingBoxRenderer();
  88613. }
  88614. },
  88615. enumerable: true,
  88616. configurable: true
  88617. });
  88618. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  88619. if (!this._boundingBoxRenderer) {
  88620. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  88621. }
  88622. return this._boundingBoxRenderer;
  88623. };
  88624. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  88625. get: function () {
  88626. return this._showBoundingBox || false;
  88627. },
  88628. set: function (value) {
  88629. this._showBoundingBox = value;
  88630. // Lazyly creates a BB renderer if needed.
  88631. if (value) {
  88632. this.getScene().getBoundingBoxRenderer();
  88633. }
  88634. },
  88635. enumerable: true,
  88636. configurable: true
  88637. });
  88638. var BoundingBoxRenderer = /** @class */ (function () {
  88639. function BoundingBoxRenderer(scene) {
  88640. /**
  88641. * The component name helpfull to identify the component in the list of scene components.
  88642. */
  88643. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  88644. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88645. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88646. this.showBackLines = true;
  88647. this.renderList = new BABYLON.SmartArray(32);
  88648. this._vertexBuffers = {};
  88649. this.scene = scene;
  88650. scene._addComponent(this);
  88651. }
  88652. /**
  88653. * Registers the component in a given scene
  88654. */
  88655. BoundingBoxRenderer.prototype.register = function () {
  88656. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  88657. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  88658. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  88659. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  88660. };
  88661. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  88662. if (mesh.showSubMeshesBoundingBox) {
  88663. var boundingInfo = subMesh.getBoundingInfo();
  88664. if (boundingInfo !== null && boundingInfo !== undefined) {
  88665. this.renderList.push(boundingInfo.boundingBox);
  88666. }
  88667. }
  88668. };
  88669. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  88670. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  88671. var boundingInfo = sourceMesh.getBoundingInfo();
  88672. this.renderList.push(boundingInfo.boundingBox);
  88673. }
  88674. };
  88675. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88676. if (this._colorShader) {
  88677. return;
  88678. }
  88679. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  88680. attributes: [BABYLON.VertexBuffer.PositionKind],
  88681. uniforms: ["world", "viewProjection", "color"]
  88682. });
  88683. var engine = this.scene.getEngine();
  88684. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88686. this._createIndexBuffer();
  88687. };
  88688. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88689. var engine = this.scene.getEngine();
  88690. 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]);
  88691. };
  88692. /**
  88693. * Rebuilds the elements related to this component in case of
  88694. * context lost for instance.
  88695. */
  88696. BoundingBoxRenderer.prototype.rebuild = function () {
  88697. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88698. if (vb) {
  88699. vb._rebuild();
  88700. }
  88701. this._createIndexBuffer();
  88702. };
  88703. BoundingBoxRenderer.prototype.reset = function () {
  88704. this.renderList.reset();
  88705. };
  88706. BoundingBoxRenderer.prototype.render = function () {
  88707. if (this.renderList.length === 0) {
  88708. return;
  88709. }
  88710. this._prepareRessources();
  88711. if (!this._colorShader.isReady()) {
  88712. return;
  88713. }
  88714. var engine = this.scene.getEngine();
  88715. engine.setDepthWrite(false);
  88716. this._colorShader._preBind();
  88717. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88718. var boundingBox = this.renderList.data[boundingBoxIndex];
  88719. var min = boundingBox.minimum;
  88720. var max = boundingBox.maximum;
  88721. var diff = max.subtract(min);
  88722. var median = min.add(diff.scale(0.5));
  88723. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88724. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88725. .multiply(boundingBox.getWorldMatrix());
  88726. // VBOs
  88727. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88728. if (this.showBackLines) {
  88729. // Back
  88730. engine.setDepthFunctionToGreaterOrEqual();
  88731. this.scene.resetCachedMaterial();
  88732. this._colorShader.setColor4("color", this.backColor.toColor4());
  88733. this._colorShader.bind(worldMatrix);
  88734. // Draw order
  88735. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88736. }
  88737. // Front
  88738. engine.setDepthFunctionToLess();
  88739. this.scene.resetCachedMaterial();
  88740. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88741. this._colorShader.bind(worldMatrix);
  88742. // Draw order
  88743. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88744. }
  88745. this._colorShader.unbind();
  88746. engine.setDepthFunctionToLessOrEqual();
  88747. engine.setDepthWrite(true);
  88748. };
  88749. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88750. this._prepareRessources();
  88751. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88752. return;
  88753. }
  88754. var engine = this.scene.getEngine();
  88755. engine.setDepthWrite(false);
  88756. engine.setColorWrite(false);
  88757. this._colorShader._preBind();
  88758. var boundingBox = mesh._boundingInfo.boundingBox;
  88759. var min = boundingBox.minimum;
  88760. var max = boundingBox.maximum;
  88761. var diff = max.subtract(min);
  88762. var median = min.add(diff.scale(0.5));
  88763. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88764. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88765. .multiply(boundingBox.getWorldMatrix());
  88766. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88767. engine.setDepthFunctionToLess();
  88768. this.scene.resetCachedMaterial();
  88769. this._colorShader.bind(worldMatrix);
  88770. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88771. this._colorShader.unbind();
  88772. engine.setDepthFunctionToLessOrEqual();
  88773. engine.setDepthWrite(true);
  88774. engine.setColorWrite(true);
  88775. };
  88776. BoundingBoxRenderer.prototype.dispose = function () {
  88777. if (!this._colorShader) {
  88778. return;
  88779. }
  88780. this.renderList.dispose();
  88781. this._colorShader.dispose();
  88782. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88783. if (buffer) {
  88784. buffer.dispose();
  88785. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88786. }
  88787. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  88788. };
  88789. return BoundingBoxRenderer;
  88790. }());
  88791. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88792. })(BABYLON || (BABYLON = {}));
  88793. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88794. var BABYLON;
  88795. (function (BABYLON) {
  88796. /**
  88797. * Renders a layer on top of an existing scene
  88798. */
  88799. var UtilityLayerRenderer = /** @class */ (function () {
  88800. /**
  88801. * Instantiates a UtilityLayerRenderer
  88802. * @param originalScene the original scene that will be rendered on top of
  88803. */
  88804. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88805. var _this = this;
  88806. this.originalScene = originalScene;
  88807. this._pointerCaptures = {};
  88808. this._lastPointerEvents = {};
  88809. /**
  88810. * If the utility layer should automatically be rendered on top of existing scene
  88811. */
  88812. this.shouldRender = true;
  88813. /**
  88814. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88815. */
  88816. this.onlyCheckPointerDownEvents = true;
  88817. /**
  88818. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88819. */
  88820. this.processAllEvents = false;
  88821. /**
  88822. * Observable raised when the pointer move from the utility layer scene to the main scene
  88823. */
  88824. this.onPointerOutObservable = new BABYLON.Observable();
  88825. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88826. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88827. originalScene.getEngine().scenes.pop();
  88828. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88829. this.utilityLayerScene.detachControl();
  88830. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88831. if (!_this.processAllEvents) {
  88832. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88833. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88834. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88835. return;
  88836. }
  88837. }
  88838. var pointerEvent = (prePointerInfo.event);
  88839. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88840. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88841. return;
  88842. }
  88843. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88844. if (!prePointerInfo.ray && utilityScenePick) {
  88845. prePointerInfo.ray = utilityScenePick.ray;
  88846. }
  88847. // always fire the prepointer oversvable
  88848. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88849. // allow every non pointer down event to flow to the utility layer
  88850. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88851. if (!prePointerInfo.skipOnPointerObservable) {
  88852. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88853. }
  88854. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88855. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88856. }
  88857. return;
  88858. }
  88859. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88860. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88861. if (utilityScenePick && utilityScenePick.hit) {
  88862. if (!prePointerInfo.skipOnPointerObservable) {
  88863. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88864. }
  88865. prePointerInfo.skipOnPointerObservable = true;
  88866. }
  88867. }
  88868. else {
  88869. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88870. var pointerEvent_1 = (prePointerInfo.event);
  88871. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88872. if (originalScenePick && utilityScenePick) {
  88873. // No pick in utility scene
  88874. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88875. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88876. // We touched an utility mesh present in the main scene
  88877. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88878. prePointerInfo.skipOnPointerObservable = true;
  88879. }
  88880. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88881. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88882. }
  88883. }
  88884. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88885. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88886. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88887. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88888. }
  88889. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88890. // We have a pick in both scenes but main is closer than utility
  88891. // We touched an utility mesh present in the main scene
  88892. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88893. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88894. prePointerInfo.skipOnPointerObservable = true;
  88895. }
  88896. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88897. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88898. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88899. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88900. }
  88901. }
  88902. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88903. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88904. }
  88905. }
  88906. }
  88907. });
  88908. // Render directly on top of existing scene without clearing
  88909. this.utilityLayerScene.autoClear = false;
  88910. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88911. if (_this.shouldRender) {
  88912. _this.render();
  88913. }
  88914. });
  88915. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88916. _this.dispose();
  88917. });
  88918. this._updateCamera();
  88919. }
  88920. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88921. get: function () {
  88922. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88923. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88924. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88925. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88926. });
  88927. }
  88928. return UtilityLayerRenderer._DefaultUtilityLayer;
  88929. },
  88930. enumerable: true,
  88931. configurable: true
  88932. });
  88933. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88934. if (!prePointerInfo.skipOnPointerObservable) {
  88935. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88936. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88937. }
  88938. };
  88939. /**
  88940. * Renders the utility layers scene on top of the original scene
  88941. */
  88942. UtilityLayerRenderer.prototype.render = function () {
  88943. this._updateCamera();
  88944. this.utilityLayerScene.render(false);
  88945. };
  88946. /**
  88947. * Disposes of the renderer
  88948. */
  88949. UtilityLayerRenderer.prototype.dispose = function () {
  88950. this.onPointerOutObservable.clear();
  88951. if (this._afterRenderObserver) {
  88952. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88953. }
  88954. if (this._sceneDisposeObserver) {
  88955. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88956. }
  88957. if (this._originalPointerObserver) {
  88958. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88959. }
  88960. this.utilityLayerScene.dispose();
  88961. };
  88962. UtilityLayerRenderer.prototype._updateCamera = function () {
  88963. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88964. };
  88965. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88966. return UtilityLayerRenderer;
  88967. }());
  88968. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88969. })(BABYLON || (BABYLON = {}));
  88970. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88971. //# sourceMappingURL=babylon.behavior.js.map
  88972. var BABYLON;
  88973. (function (BABYLON) {
  88974. /**
  88975. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88976. */
  88977. var PointerDragBehavior = /** @class */ (function () {
  88978. /**
  88979. * Creates a pointer drag behavior that can be attached to a mesh
  88980. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  88981. */
  88982. function PointerDragBehavior(options) {
  88983. this.options = options;
  88984. /**
  88985. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  88986. */
  88987. this.maxDragAngle = 0;
  88988. /**
  88989. * @hidden
  88990. */
  88991. this._useAlternatePickedPointAboveMaxDragAngle = false;
  88992. /**
  88993. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88994. */
  88995. this.currentDraggingPointerID = -1;
  88996. /**
  88997. * If the behavior is currently in a dragging state
  88998. */
  88999. this.dragging = false;
  89000. /**
  89001. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89002. */
  89003. this.dragDeltaRatio = 0.2;
  89004. /**
  89005. * If the drag plane orientation should be updated during the dragging (Default: true)
  89006. */
  89007. this.updateDragPlane = true;
  89008. // Debug mode will display drag planes to help visualize behavior
  89009. this._debugMode = false;
  89010. this._moving = false;
  89011. /**
  89012. * Fires each time the attached mesh is dragged with the pointer
  89013. * * delta between last drag position and current drag position in world space
  89014. * * dragDistance along the drag axis
  89015. * * dragPlaneNormal normal of the current drag plane used during the drag
  89016. * * dragPlanePoint in world space where the drag intersects the drag plane
  89017. */
  89018. this.onDragObservable = new BABYLON.Observable();
  89019. /**
  89020. * Fires each time a drag begins (eg. mouse down on mesh)
  89021. */
  89022. this.onDragStartObservable = new BABYLON.Observable();
  89023. /**
  89024. * Fires each time a drag ends (eg. mouse release after drag)
  89025. */
  89026. this.onDragEndObservable = new BABYLON.Observable();
  89027. /**
  89028. * If the attached mesh should be moved when dragged
  89029. */
  89030. this.moveAttached = true;
  89031. /**
  89032. * If the drag behavior will react to drag events (Default: true)
  89033. */
  89034. this.enabled = true;
  89035. /**
  89036. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  89037. */
  89038. this.useObjectOrienationForDragging = true;
  89039. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89040. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  89041. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  89042. // Variables to avoid instantiation in the below method
  89043. this._pointA = new BABYLON.Vector3(0, 0, 0);
  89044. this._pointB = new BABYLON.Vector3(0, 0, 0);
  89045. this._pointC = new BABYLON.Vector3(0, 0, 0);
  89046. this._lineA = new BABYLON.Vector3(0, 0, 0);
  89047. this._lineB = new BABYLON.Vector3(0, 0, 0);
  89048. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  89049. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  89050. var optionCount = 0;
  89051. if (options === undefined) {
  89052. options = {};
  89053. }
  89054. if (options.dragAxis) {
  89055. optionCount++;
  89056. }
  89057. if (options.dragPlaneNormal) {
  89058. optionCount++;
  89059. }
  89060. if (optionCount > 1) {
  89061. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  89062. }
  89063. }
  89064. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  89065. /**
  89066. * The name of the behavior
  89067. */
  89068. get: function () {
  89069. return "PointerDrag";
  89070. },
  89071. enumerable: true,
  89072. configurable: true
  89073. });
  89074. /**
  89075. * Initializes the behavior
  89076. */
  89077. PointerDragBehavior.prototype.init = function () { };
  89078. /**
  89079. * Attaches the drag behavior the passed in mesh
  89080. * @param ownerNode The mesh that will be dragged around once attached
  89081. */
  89082. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89083. var _this = this;
  89084. this._scene = ownerNode.getScene();
  89085. this._attachedNode = ownerNode;
  89086. // Initialize drag plane to not interfere with existing scene
  89087. if (!PointerDragBehavior._planeScene) {
  89088. if (this._debugMode) {
  89089. PointerDragBehavior._planeScene = this._scene;
  89090. }
  89091. else {
  89092. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89093. this._scene.getEngine().scenes.pop();
  89094. }
  89095. }
  89096. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89097. // State of the drag
  89098. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89099. var delta = new BABYLON.Vector3(0, 0, 0);
  89100. var dragLength = 0;
  89101. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89102. var pickPredicate = function (m) {
  89103. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89104. };
  89105. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89106. if (!_this.enabled) {
  89107. return;
  89108. }
  89109. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89110. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89111. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89112. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89113. if (pickedPoint) {
  89114. _this.dragging = true;
  89115. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89116. _this.lastDragPosition.copyFrom(pickedPoint);
  89117. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89118. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89119. }
  89120. }
  89121. }
  89122. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89123. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89124. _this.releaseDrag();
  89125. }
  89126. }
  89127. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89128. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89129. _this._moving = true;
  89130. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89131. if (pickedPoint) {
  89132. if (_this.updateDragPlane) {
  89133. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89134. }
  89135. // depending on the drag mode option drag accordingly
  89136. if (_this.options.dragAxis) {
  89137. // Convert local drag axis to world
  89138. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89139. // Project delta drag from the drag plane onto the drag axis
  89140. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89141. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89142. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89143. }
  89144. else {
  89145. dragLength = delta.length();
  89146. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89147. }
  89148. targetPosition.addInPlace(delta);
  89149. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89150. _this.lastDragPosition.copyFrom(pickedPoint);
  89151. }
  89152. }
  89153. }
  89154. });
  89155. this._scene.onBeforeRenderObservable.add(function () {
  89156. if (_this._moving && _this.moveAttached) {
  89157. // Slowly move mesh to avoid jitter
  89158. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89159. _this._tmpVector.scaleInPlace(0.2);
  89160. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89161. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89162. }
  89163. });
  89164. };
  89165. PointerDragBehavior.prototype.releaseDrag = function () {
  89166. this.dragging = false;
  89167. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89168. this.currentDraggingPointerID = -1;
  89169. this._moving = false;
  89170. };
  89171. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89172. var _this = this;
  89173. if (!ray) {
  89174. return null;
  89175. }
  89176. // Calculate angle between plane normal and ray
  89177. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89178. // Correct if ray is casted from oposite side
  89179. if (angle > Math.PI / 2) {
  89180. angle = Math.PI - angle;
  89181. }
  89182. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89183. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89184. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89185. // Invert ray direction along the towards object axis
  89186. this._tmpVector.copyFrom(ray.direction);
  89187. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89188. this._alternatePickedPoint.normalize();
  89189. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89190. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89191. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89192. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89193. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89194. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89195. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89196. return this._alternatePickedPoint;
  89197. }
  89198. else {
  89199. return null;
  89200. }
  89201. }
  89202. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89203. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89204. return pickResult.pickedPoint;
  89205. }
  89206. else {
  89207. return null;
  89208. }
  89209. };
  89210. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89211. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89212. this._pointA.copyFrom(dragPlanePosition);
  89213. if (this.options.dragAxis) {
  89214. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  89215. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89216. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89217. ray.origin.subtractToRef(this._pointA, this._pointC);
  89218. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89219. // Get perpendicular line from direction to camera and drag axis
  89220. this._pointB.subtractToRef(this._pointA, this._lineA);
  89221. this._pointC.subtractToRef(this._pointA, this._lineB);
  89222. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89223. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89224. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89225. this._lookAt.normalize();
  89226. this._dragPlane.position.copyFrom(this._pointA);
  89227. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89228. this._dragPlane.lookAt(this._lookAt);
  89229. }
  89230. else if (this.options.dragPlaneNormal) {
  89231. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  89232. this._dragPlane.position.copyFrom(this._pointA);
  89233. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89234. this._dragPlane.lookAt(this._lookAt);
  89235. }
  89236. else {
  89237. this._dragPlane.position.copyFrom(this._pointA);
  89238. this._dragPlane.lookAt(ray.origin);
  89239. }
  89240. this._dragPlane.computeWorldMatrix(true);
  89241. };
  89242. /**
  89243. * Detaches the behavior from the mesh
  89244. */
  89245. PointerDragBehavior.prototype.detach = function () {
  89246. if (this._pointerObserver) {
  89247. this._scene.onPointerObservable.remove(this._pointerObserver);
  89248. }
  89249. };
  89250. return PointerDragBehavior;
  89251. }());
  89252. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89253. })(BABYLON || (BABYLON = {}));
  89254. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89255. var BABYLON;
  89256. (function (BABYLON) {
  89257. /**
  89258. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89259. */
  89260. var MultiPointerScaleBehavior = /** @class */ (function () {
  89261. function MultiPointerScaleBehavior() {
  89262. this._startDistance = 0;
  89263. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89264. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89265. this._sceneRenderObserver = null;
  89266. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89267. this._dragBehaviorA.moveAttached = false;
  89268. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89269. this._dragBehaviorB.moveAttached = false;
  89270. }
  89271. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89272. /**
  89273. * The name of the behavior
  89274. */
  89275. get: function () {
  89276. return "MultiPointerScale";
  89277. },
  89278. enumerable: true,
  89279. configurable: true
  89280. });
  89281. /**
  89282. * Initializes the behavior
  89283. */
  89284. MultiPointerScaleBehavior.prototype.init = function () { };
  89285. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89286. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89287. };
  89288. /**
  89289. * Attaches the scale behavior the passed in mesh
  89290. * @param ownerNode The mesh that will be scaled around once attached
  89291. */
  89292. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89293. var _this = this;
  89294. this._ownerNode = ownerNode;
  89295. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89296. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89297. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89298. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89299. _this._dragBehaviorA.releaseDrag();
  89300. }
  89301. else {
  89302. _this._initialScale.copyFrom(ownerNode.scaling);
  89303. _this._startDistance = _this._getCurrentDistance();
  89304. }
  89305. }
  89306. });
  89307. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89308. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89309. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89310. _this._dragBehaviorB.releaseDrag();
  89311. }
  89312. else {
  89313. _this._initialScale.copyFrom(ownerNode.scaling);
  89314. _this._startDistance = _this._getCurrentDistance();
  89315. }
  89316. }
  89317. });
  89318. // Once both drag behaviors are active scale based on the distance between the two pointers
  89319. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89320. behavior.onDragObservable.add(function () {
  89321. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89322. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89323. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89324. }
  89325. });
  89326. });
  89327. ownerNode.addBehavior(this._dragBehaviorA);
  89328. ownerNode.addBehavior(this._dragBehaviorB);
  89329. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89330. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89331. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89332. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89333. if (change.length() > 0.01) {
  89334. ownerNode.scaling.addInPlace(change);
  89335. }
  89336. }
  89337. });
  89338. };
  89339. /**
  89340. * Detaches the behavior from the mesh
  89341. */
  89342. MultiPointerScaleBehavior.prototype.detach = function () {
  89343. var _this = this;
  89344. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89345. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89346. behavior.onDragStartObservable.clear();
  89347. behavior.onDragObservable.clear();
  89348. _this._ownerNode.removeBehavior(behavior);
  89349. });
  89350. };
  89351. return MultiPointerScaleBehavior;
  89352. }());
  89353. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89354. })(BABYLON || (BABYLON = {}));
  89355. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89356. var BABYLON;
  89357. (function (BABYLON) {
  89358. /**
  89359. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  89360. */
  89361. var SixDofDragBehavior = /** @class */ (function () {
  89362. function SixDofDragBehavior() {
  89363. this._sceneRenderObserver = null;
  89364. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89365. this._moving = false;
  89366. this._startingOrientation = new BABYLON.Quaternion();
  89367. /**
  89368. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  89369. */
  89370. this.zDragFactor = 5;
  89371. /**
  89372. * If the behavior is currently in a dragging state
  89373. */
  89374. this.dragging = false;
  89375. /**
  89376. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89377. */
  89378. this.dragDeltaRatio = 0.2;
  89379. /**
  89380. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89381. */
  89382. this.currentDraggingPointerID = -1;
  89383. }
  89384. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89385. /**
  89386. * The name of the behavior
  89387. */
  89388. get: function () {
  89389. return "SixDofDrag";
  89390. },
  89391. enumerable: true,
  89392. configurable: true
  89393. });
  89394. /**
  89395. * Initializes the behavior
  89396. */
  89397. SixDofDragBehavior.prototype.init = function () { };
  89398. /**
  89399. * Attaches the scale behavior the passed in mesh
  89400. * @param ownerNode The mesh that will be scaled around once attached
  89401. */
  89402. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89403. var _this = this;
  89404. this._ownerNode = ownerNode;
  89405. this._scene = this._ownerNode.getScene();
  89406. if (!SixDofDragBehavior._virtualScene) {
  89407. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89408. this._scene.getEngine().scenes.pop();
  89409. }
  89410. var pickedMesh = null;
  89411. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89412. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89413. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89414. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89415. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89416. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89417. var pickPredicate = function (m) {
  89418. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89419. };
  89420. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89421. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89422. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89423. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  89424. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89425. // Set position and orientation of the controller
  89426. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89427. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89428. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89429. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89430. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89431. if (!pickedMesh.rotationQuaternion) {
  89432. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89433. }
  89434. var oldParent = pickedMesh.parent;
  89435. pickedMesh.setParent(null);
  89436. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89437. pickedMesh.setParent(oldParent);
  89438. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89439. // Update state
  89440. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89441. _this.dragging = true;
  89442. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89443. }
  89444. }
  89445. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89446. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89447. _this.dragging = false;
  89448. _this._moving = false;
  89449. _this.currentDraggingPointerID = -1;
  89450. pickedMesh = null;
  89451. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89452. }
  89453. }
  89454. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89455. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89456. // Calculate controller drag distance in controller space
  89457. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89458. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89459. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  89460. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89461. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89462. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  89463. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  89464. if (_this._virtualDragMesh.position.z < 0) {
  89465. _this._virtualDragMesh.position.z = 0;
  89466. }
  89467. // Update the controller position
  89468. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89469. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89470. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89471. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89472. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89473. if (pickedMesh.parent) {
  89474. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89475. }
  89476. if (!_this._moving) {
  89477. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89478. }
  89479. _this._moving = true;
  89480. }
  89481. }
  89482. });
  89483. var tmpQuaternion = new BABYLON.Quaternion();
  89484. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89485. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89486. if (_this.dragging && _this._moving && pickedMesh) {
  89487. // Slowly move mesh to avoid jitter
  89488. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89489. // Get change in rotation
  89490. tmpQuaternion.copyFrom(_this._startingOrientation);
  89491. tmpQuaternion.x = -tmpQuaternion.x;
  89492. tmpQuaternion.y = -tmpQuaternion.y;
  89493. tmpQuaternion.z = -tmpQuaternion.z;
  89494. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89495. // Convert change in rotation to only y axis rotation
  89496. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89497. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89498. // Slowly move mesh to avoid jitter
  89499. var oldParent = pickedMesh.parent;
  89500. pickedMesh.setParent(null);
  89501. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89502. pickedMesh.setParent(oldParent);
  89503. }
  89504. });
  89505. };
  89506. /**
  89507. * Detaches the behavior from the mesh
  89508. */
  89509. SixDofDragBehavior.prototype.detach = function () {
  89510. this._scene.onPointerObservable.remove(this._pointerObserver);
  89511. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89512. this._virtualOriginMesh.dispose();
  89513. this._virtualDragMesh.dispose();
  89514. };
  89515. return SixDofDragBehavior;
  89516. }());
  89517. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89518. })(BABYLON || (BABYLON = {}));
  89519. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89520. var BABYLON;
  89521. (function (BABYLON) {
  89522. /**
  89523. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89524. */
  89525. var Gizmo = /** @class */ (function () {
  89526. /**
  89527. * Creates a gizmo
  89528. * @param gizmoLayer The utility layer the gizmo will be added to
  89529. */
  89530. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89531. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89532. var _this = this;
  89533. this.gizmoLayer = gizmoLayer;
  89534. this._scaleFactor = 3;
  89535. this._tmpMatrix = new BABYLON.Matrix();
  89536. /**
  89537. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89538. */
  89539. this.updateGizmoRotationToMatchAttachedMesh = true;
  89540. /**
  89541. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89542. */
  89543. this.updateGizmoPositionToMatchAttachedMesh = true;
  89544. /**
  89545. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89546. */
  89547. this._updateScale = true;
  89548. this._interactionsEnabled = true;
  89549. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89550. var tempVector = new BABYLON.Vector3();
  89551. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89552. if (_this.attachedMesh) {
  89553. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89554. if (!_this._rootMesh.rotationQuaternion) {
  89555. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89556. }
  89557. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89558. tempVector.copyFrom(_this.attachedMesh.scaling);
  89559. if (_this.attachedMesh.scaling.x < 0) {
  89560. _this.attachedMesh.scaling.x *= -1;
  89561. }
  89562. if (_this.attachedMesh.scaling.y < 0) {
  89563. _this.attachedMesh.scaling.y *= -1;
  89564. }
  89565. if (_this.attachedMesh.scaling.z < 0) {
  89566. _this.attachedMesh.scaling.z *= -1;
  89567. }
  89568. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89569. _this.attachedMesh.scaling.copyFrom(tempVector);
  89570. _this.attachedMesh.computeWorldMatrix();
  89571. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  89572. }
  89573. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89574. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89575. }
  89576. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89577. _this._rootMesh.position.subtractToRef(_this.gizmoLayer.utilityLayerScene.activeCamera.position, tempVector);
  89578. var dist = tempVector.length() / _this._scaleFactor;
  89579. _this._rootMesh.scaling.set(dist, dist, dist);
  89580. }
  89581. }
  89582. });
  89583. this.attachedMesh = null;
  89584. }
  89585. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89586. /**
  89587. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89588. * * When set, interactions will be enabled
  89589. */
  89590. get: function () {
  89591. return this._attachedMesh;
  89592. },
  89593. set: function (value) {
  89594. this._attachedMesh = value;
  89595. this._rootMesh.setEnabled(value ? true : false);
  89596. this._attachedMeshChanged(value);
  89597. },
  89598. enumerable: true,
  89599. configurable: true
  89600. });
  89601. Gizmo.prototype._attachedMeshChanged = function (value) {
  89602. };
  89603. /**
  89604. * Disposes of the gizmo
  89605. */
  89606. Gizmo.prototype.dispose = function () {
  89607. this._rootMesh.dispose();
  89608. if (this._beforeRenderObserver) {
  89609. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89610. }
  89611. };
  89612. return Gizmo;
  89613. }());
  89614. BABYLON.Gizmo = Gizmo;
  89615. })(BABYLON || (BABYLON = {}));
  89616. //# sourceMappingURL=babylon.gizmo.js.map
  89617. var BABYLON;
  89618. (function (BABYLON) {
  89619. /**
  89620. * Single axis drag gizmo
  89621. */
  89622. var AxisDragGizmo = /** @class */ (function (_super) {
  89623. __extends(AxisDragGizmo, _super);
  89624. /**
  89625. * Creates an AxisDragGizmo
  89626. * @param gizmoLayer The utility layer the gizmo will be added to
  89627. * @param dragAxis The axis which the gizmo will be able to drag on
  89628. * @param color The color of the gizmo
  89629. */
  89630. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89631. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89632. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89633. var _this = _super.call(this, gizmoLayer) || this;
  89634. _this._pointerObserver = null;
  89635. /**
  89636. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89637. */
  89638. _this.snapDistance = 0;
  89639. /**
  89640. * Event that fires each time the gizmo snaps to a new location.
  89641. * * snapDistance is the the change in distance
  89642. */
  89643. _this.onSnapObservable = new BABYLON.Observable();
  89644. // Create Material
  89645. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89646. coloredMaterial.disableLighting = true;
  89647. coloredMaterial.emissiveColor = color;
  89648. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89649. hoverMaterial.disableLighting = true;
  89650. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89651. // Build mesh on root node
  89652. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89653. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89654. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89655. arrow.addChild(arrowMesh);
  89656. arrow.addChild(arrowTail);
  89657. // Position arrow pointing in its drag axis
  89658. arrowMesh.scaling.scaleInPlace(0.05);
  89659. arrowMesh.material = coloredMaterial;
  89660. arrowMesh.rotation.x = Math.PI / 2;
  89661. arrowMesh.position.z += 0.3;
  89662. arrowTail.rotation.x = Math.PI / 2;
  89663. arrowTail.material = coloredMaterial;
  89664. arrowTail.position.z += 0.15;
  89665. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89666. _this._rootMesh.addChild(arrow);
  89667. var currentSnapDragDistance = 0;
  89668. var tmpVector = new BABYLON.Vector3();
  89669. var tmpSnapEvent = { snapDistance: 0 };
  89670. // Add drag behavior to handle events when the gizmo is dragged
  89671. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89672. _this.dragBehavior.moveAttached = false;
  89673. _this._rootMesh.addBehavior(_this.dragBehavior);
  89674. _this.dragBehavior.onDragObservable.add(function (event) {
  89675. if (_this.attachedMesh) {
  89676. // Snapping logic
  89677. if (_this.snapDistance == 0) {
  89678. _this.attachedMesh.position.addInPlace(event.delta);
  89679. }
  89680. else {
  89681. currentSnapDragDistance += event.dragDistance;
  89682. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89683. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89684. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89685. event.delta.normalizeToRef(tmpVector);
  89686. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89687. _this.attachedMesh.position.addInPlace(tmpVector);
  89688. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89689. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89690. }
  89691. }
  89692. }
  89693. });
  89694. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89695. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89696. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89697. m.material = hoverMaterial;
  89698. });
  89699. }
  89700. else {
  89701. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89702. m.material = coloredMaterial;
  89703. });
  89704. }
  89705. });
  89706. return _this;
  89707. }
  89708. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89709. if (this.dragBehavior) {
  89710. this.dragBehavior.enabled = value ? true : false;
  89711. }
  89712. };
  89713. /**
  89714. * Disposes of the gizmo
  89715. */
  89716. AxisDragGizmo.prototype.dispose = function () {
  89717. this.onSnapObservable.clear();
  89718. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89719. this.dragBehavior.detach();
  89720. _super.prototype.dispose.call(this);
  89721. };
  89722. return AxisDragGizmo;
  89723. }(BABYLON.Gizmo));
  89724. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89725. })(BABYLON || (BABYLON = {}));
  89726. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89727. var BABYLON;
  89728. (function (BABYLON) {
  89729. /**
  89730. * Single axis scale gizmo
  89731. */
  89732. var AxisScaleGizmo = /** @class */ (function (_super) {
  89733. __extends(AxisScaleGizmo, _super);
  89734. /**
  89735. * Creates an AxisScaleGizmo
  89736. * @param gizmoLayer The utility layer the gizmo will be added to
  89737. * @param dragAxis The axis which the gizmo will be able to scale on
  89738. * @param color The color of the gizmo
  89739. */
  89740. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89741. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89742. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89743. var _this = _super.call(this, gizmoLayer) || this;
  89744. _this._pointerObserver = null;
  89745. /**
  89746. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89747. */
  89748. _this.snapDistance = 0;
  89749. /**
  89750. * Event that fires each time the gizmo snaps to a new location.
  89751. * * snapDistance is the the change in distance
  89752. */
  89753. _this.onSnapObservable = new BABYLON.Observable();
  89754. // Create Material
  89755. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89756. coloredMaterial.disableLighting = true;
  89757. coloredMaterial.emissiveColor = color;
  89758. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89759. hoverMaterial.disableLighting = true;
  89760. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89761. // Build mesh on root node
  89762. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89763. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89764. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89765. arrow.addChild(arrowMesh);
  89766. arrow.addChild(arrowTail);
  89767. // Position arrow pointing in its drag axis
  89768. arrowMesh.scaling.scaleInPlace(0.1);
  89769. arrowMesh.material = coloredMaterial;
  89770. arrowMesh.rotation.x = Math.PI / 2;
  89771. arrowMesh.position.z += 0.3;
  89772. arrowTail.rotation.x = Math.PI / 2;
  89773. arrowTail.material = coloredMaterial;
  89774. arrowTail.position.z += 0.15;
  89775. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89776. _this._rootMesh.addChild(arrow);
  89777. // Add drag behavior to handle events when the gizmo is dragged
  89778. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89779. _this.dragBehavior.moveAttached = false;
  89780. _this._rootMesh.addBehavior(_this.dragBehavior);
  89781. var currentSnapDragDistance = 0;
  89782. var tmpVector = new BABYLON.Vector3();
  89783. var tmpSnapEvent = { snapDistance: 0 };
  89784. _this.dragBehavior.onDragObservable.add(function (event) {
  89785. if (_this.attachedMesh) {
  89786. // Snapping logic
  89787. var snapped = false;
  89788. var dragSteps = 0;
  89789. if (_this.snapDistance == 0) {
  89790. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89791. }
  89792. else {
  89793. currentSnapDragDistance += event.dragDistance;
  89794. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89795. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89796. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89797. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89798. snapped = true;
  89799. }
  89800. else {
  89801. tmpVector.scaleInPlace(0);
  89802. }
  89803. }
  89804. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89805. if (snapped) {
  89806. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89807. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89808. }
  89809. }
  89810. });
  89811. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89812. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89813. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89814. m.material = hoverMaterial;
  89815. });
  89816. }
  89817. else {
  89818. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89819. m.material = coloredMaterial;
  89820. });
  89821. }
  89822. });
  89823. return _this;
  89824. }
  89825. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89826. if (this.dragBehavior) {
  89827. this.dragBehavior.enabled = value ? true : false;
  89828. }
  89829. };
  89830. /**
  89831. * Disposes of the gizmo
  89832. */
  89833. AxisScaleGizmo.prototype.dispose = function () {
  89834. this.onSnapObservable.clear();
  89835. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89836. this.dragBehavior.detach();
  89837. _super.prototype.dispose.call(this);
  89838. };
  89839. return AxisScaleGizmo;
  89840. }(BABYLON.Gizmo));
  89841. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89842. })(BABYLON || (BABYLON = {}));
  89843. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89844. var BABYLON;
  89845. (function (BABYLON) {
  89846. /**
  89847. * Single plane rotation gizmo
  89848. */
  89849. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89850. __extends(PlaneRotationGizmo, _super);
  89851. /**
  89852. * Creates a PlaneRotationGizmo
  89853. * @param gizmoLayer The utility layer the gizmo will be added to
  89854. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89855. * @param color The color of the gizmo
  89856. */
  89857. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89858. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89859. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89860. var _this = _super.call(this, gizmoLayer) || this;
  89861. _this._pointerObserver = null;
  89862. /**
  89863. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89864. */
  89865. _this.snapDistance = 0;
  89866. /**
  89867. * Event that fires each time the gizmo snaps to a new location.
  89868. * * snapDistance is the the change in distance
  89869. */
  89870. _this.onSnapObservable = new BABYLON.Observable();
  89871. // Create Material
  89872. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89873. coloredMaterial.disableLighting = true;
  89874. coloredMaterial.emissiveColor = color;
  89875. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89876. hoverMaterial.disableLighting = true;
  89877. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89878. // Build mesh on root node
  89879. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89880. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89881. // Position arrow pointing in its drag axis
  89882. rotationMesh.scaling.scaleInPlace(0.1);
  89883. rotationMesh.material = coloredMaterial;
  89884. rotationMesh.rotation.x = Math.PI / 2;
  89885. parentMesh.addChild(rotationMesh);
  89886. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89887. _this._rootMesh.addChild(parentMesh);
  89888. // Add drag behavior to handle events when the gizmo is dragged
  89889. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89890. _this.dragBehavior.moveAttached = false;
  89891. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  89892. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  89893. _this._rootMesh.addBehavior(_this.dragBehavior);
  89894. var lastDragPosition = new BABYLON.Vector3();
  89895. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89896. if (_this.attachedMesh) {
  89897. lastDragPosition.copyFrom(e.dragPlanePoint);
  89898. }
  89899. });
  89900. var rotationMatrix = new BABYLON.Matrix();
  89901. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89902. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89903. var tmpSnapEvent = { snapDistance: 0 };
  89904. var currentSnapDragDistance = 0;
  89905. _this.dragBehavior.onDragObservable.add(function (event) {
  89906. if (_this.attachedMesh) {
  89907. if (!_this.attachedMesh.rotationQuaternion) {
  89908. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89909. }
  89910. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89911. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89912. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89913. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89914. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89915. var angle = Math.atan2(cross.length(), dot);
  89916. planeNormalTowardsCamera.copyFrom(planeNormal);
  89917. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89918. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89919. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89920. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89921. }
  89922. // Flip up vector depending on which side the camera is on
  89923. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89924. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89925. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89926. planeNormalTowardsCamera.scaleInPlace(-1);
  89927. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89928. }
  89929. }
  89930. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89931. if (halfCircleSide)
  89932. angle = -angle;
  89933. // Snapping logic
  89934. var snapped = false;
  89935. if (_this.snapDistance != 0) {
  89936. currentSnapDragDistance += angle;
  89937. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89938. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89939. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89940. angle = _this.snapDistance * dragSteps;
  89941. snapped = true;
  89942. }
  89943. else {
  89944. angle = 0;
  89945. }
  89946. }
  89947. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89948. var quaternionCoefficient = Math.sin(angle / 2);
  89949. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89950. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89951. // Rotate selected mesh quaternion over fixed axis
  89952. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89953. }
  89954. else {
  89955. // Rotate selected mesh quaternion over rotated axis
  89956. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  89957. }
  89958. lastDragPosition.copyFrom(event.dragPlanePoint);
  89959. if (snapped) {
  89960. tmpSnapEvent.snapDistance = angle;
  89961. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89962. }
  89963. }
  89964. });
  89965. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89966. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89967. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89968. m.material = hoverMaterial;
  89969. });
  89970. }
  89971. else {
  89972. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89973. m.material = coloredMaterial;
  89974. });
  89975. }
  89976. });
  89977. return _this;
  89978. }
  89979. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89980. if (this.dragBehavior) {
  89981. this.dragBehavior.enabled = value ? true : false;
  89982. }
  89983. };
  89984. /**
  89985. * Disposes of the gizmo
  89986. */
  89987. PlaneRotationGizmo.prototype.dispose = function () {
  89988. this.onSnapObservable.clear();
  89989. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89990. this.dragBehavior.detach();
  89991. _super.prototype.dispose.call(this);
  89992. };
  89993. return PlaneRotationGizmo;
  89994. }(BABYLON.Gizmo));
  89995. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89996. })(BABYLON || (BABYLON = {}));
  89997. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89998. var BABYLON;
  89999. (function (BABYLON) {
  90000. /**
  90001. * Gizmo that enables dragging a mesh along 3 axis
  90002. */
  90003. var PositionGizmo = /** @class */ (function (_super) {
  90004. __extends(PositionGizmo, _super);
  90005. /**
  90006. * Creates a PositionGizmo
  90007. * @param gizmoLayer The utility layer the gizmo will be added to
  90008. */
  90009. function PositionGizmo(gizmoLayer) {
  90010. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90011. var _this = _super.call(this, gizmoLayer) || this;
  90012. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90013. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90014. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90015. _this.attachedMesh = null;
  90016. return _this;
  90017. }
  90018. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  90019. set: function (mesh) {
  90020. if (this.xGizmo) {
  90021. this.xGizmo.attachedMesh = mesh;
  90022. this.yGizmo.attachedMesh = mesh;
  90023. this.zGizmo.attachedMesh = mesh;
  90024. }
  90025. },
  90026. enumerable: true,
  90027. configurable: true
  90028. });
  90029. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90030. get: function () {
  90031. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90032. },
  90033. set: function (value) {
  90034. if (this.xGizmo) {
  90035. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90036. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90037. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90038. }
  90039. },
  90040. enumerable: true,
  90041. configurable: true
  90042. });
  90043. /**
  90044. * Disposes of the gizmo
  90045. */
  90046. PositionGizmo.prototype.dispose = function () {
  90047. this.xGizmo.dispose();
  90048. this.yGizmo.dispose();
  90049. this.zGizmo.dispose();
  90050. };
  90051. return PositionGizmo;
  90052. }(BABYLON.Gizmo));
  90053. BABYLON.PositionGizmo = PositionGizmo;
  90054. })(BABYLON || (BABYLON = {}));
  90055. //# sourceMappingURL=babylon.positionGizmo.js.map
  90056. var BABYLON;
  90057. (function (BABYLON) {
  90058. /**
  90059. * Gizmo that enables rotating a mesh along 3 axis
  90060. */
  90061. var RotationGizmo = /** @class */ (function (_super) {
  90062. __extends(RotationGizmo, _super);
  90063. /**
  90064. * Creates a RotationGizmo
  90065. * @param gizmoLayer The utility layer the gizmo will be added to
  90066. */
  90067. function RotationGizmo(gizmoLayer) {
  90068. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90069. var _this = _super.call(this, gizmoLayer) || this;
  90070. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90071. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90072. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90073. _this.attachedMesh = null;
  90074. return _this;
  90075. }
  90076. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  90077. set: function (mesh) {
  90078. if (this.xGizmo) {
  90079. this.xGizmo.attachedMesh = mesh;
  90080. this.yGizmo.attachedMesh = mesh;
  90081. this.zGizmo.attachedMesh = mesh;
  90082. }
  90083. },
  90084. enumerable: true,
  90085. configurable: true
  90086. });
  90087. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90088. get: function () {
  90089. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90090. },
  90091. set: function (value) {
  90092. if (this.xGizmo) {
  90093. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90094. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90095. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90096. }
  90097. },
  90098. enumerable: true,
  90099. configurable: true
  90100. });
  90101. /**
  90102. * Disposes of the gizmo
  90103. */
  90104. RotationGizmo.prototype.dispose = function () {
  90105. this.xGizmo.dispose();
  90106. this.yGizmo.dispose();
  90107. this.zGizmo.dispose();
  90108. };
  90109. return RotationGizmo;
  90110. }(BABYLON.Gizmo));
  90111. BABYLON.RotationGizmo = RotationGizmo;
  90112. })(BABYLON || (BABYLON = {}));
  90113. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90114. var BABYLON;
  90115. (function (BABYLON) {
  90116. /**
  90117. * Gizmo that enables scaling a mesh along 3 axis
  90118. */
  90119. var ScaleGizmo = /** @class */ (function (_super) {
  90120. __extends(ScaleGizmo, _super);
  90121. /**
  90122. * Creates a ScaleGizmo
  90123. * @param gizmoLayer The utility layer the gizmo will be added to
  90124. */
  90125. function ScaleGizmo(gizmoLayer) {
  90126. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90127. var _this = _super.call(this, gizmoLayer) || this;
  90128. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90129. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90130. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90131. _this.attachedMesh = null;
  90132. return _this;
  90133. }
  90134. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90135. set: function (mesh) {
  90136. if (this.xGizmo) {
  90137. this.xGizmo.attachedMesh = mesh;
  90138. this.yGizmo.attachedMesh = mesh;
  90139. this.zGizmo.attachedMesh = mesh;
  90140. }
  90141. },
  90142. enumerable: true,
  90143. configurable: true
  90144. });
  90145. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90146. get: function () {
  90147. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90148. },
  90149. set: function (value) {
  90150. if (this.xGizmo) {
  90151. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90152. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90153. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90154. }
  90155. },
  90156. enumerable: true,
  90157. configurable: true
  90158. });
  90159. /**
  90160. * Disposes of the gizmo
  90161. */
  90162. ScaleGizmo.prototype.dispose = function () {
  90163. this.xGizmo.dispose();
  90164. this.yGizmo.dispose();
  90165. this.zGizmo.dispose();
  90166. };
  90167. return ScaleGizmo;
  90168. }(BABYLON.Gizmo));
  90169. BABYLON.ScaleGizmo = ScaleGizmo;
  90170. })(BABYLON || (BABYLON = {}));
  90171. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90172. var BABYLON;
  90173. (function (BABYLON) {
  90174. /**
  90175. * Bounding box gizmo
  90176. */
  90177. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90178. __extends(BoundingBoxGizmo, _super);
  90179. /**
  90180. * Creates an BoundingBoxGizmo
  90181. * @param gizmoLayer The utility layer the gizmo will be added to
  90182. * @param color The color of the gizmo
  90183. */
  90184. function BoundingBoxGizmo(color, gizmoLayer) {
  90185. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90186. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90187. var _this = _super.call(this, gizmoLayer) || this;
  90188. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90189. _this._renderObserver = null;
  90190. _this._pointerObserver = null;
  90191. _this._scaleDragSpeed = 0.2;
  90192. _this._tmpQuaternion = new BABYLON.Quaternion();
  90193. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90194. /**
  90195. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90196. */
  90197. _this.rotationSphereSize = 0.1;
  90198. /**
  90199. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90200. */
  90201. _this.scaleBoxSize = 0.1;
  90202. /**
  90203. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  90204. */
  90205. _this.fixedDragMeshScreenSize = false;
  90206. /**
  90207. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90208. */
  90209. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90210. /**
  90211. * Fired when a rotation sphere or scale box is dragged
  90212. */
  90213. _this.onDragStartObservable = new BABYLON.Observable();
  90214. /**
  90215. * Fired when a rotation sphere or scale box drag is started
  90216. */
  90217. _this.onDragObservable = new BABYLON.Observable();
  90218. /**
  90219. * Fired when a rotation sphere or scale box drag is needed
  90220. */
  90221. _this.onDragEndObservable = new BABYLON.Observable();
  90222. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90223. _this._updateScale = false;
  90224. // Create Materials
  90225. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90226. coloredMaterial.disableLighting = true;
  90227. coloredMaterial.emissiveColor = color;
  90228. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90229. hoverColoredMaterial.disableLighting = true;
  90230. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90231. // Build bounding box out of lines
  90232. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90233. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90234. var lines = [];
  90235. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90236. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90237. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90238. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90239. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90240. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90241. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90242. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90243. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90244. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90245. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90246. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90247. lines.forEach(function (l) {
  90248. l.color = color;
  90249. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90250. l.isPickable = false;
  90251. _this._lineBoundingBox.addChild(l);
  90252. });
  90253. _this._rootMesh.addChild(_this._lineBoundingBox);
  90254. // Create rotation spheres
  90255. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90256. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90257. var _loop_1 = function (i_1) {
  90258. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90259. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90260. sphere.material = coloredMaterial;
  90261. // Drag behavior
  90262. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90263. _dragBehavior.moveAttached = false;
  90264. _dragBehavior.updateDragPlane = false;
  90265. sphere.addBehavior(_dragBehavior);
  90266. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90267. var totalTurnAmountOfDrag = 0;
  90268. _dragBehavior.onDragStartObservable.add(function (event) {
  90269. startingTurnDirection.copyFrom(sphere.forward);
  90270. totalTurnAmountOfDrag = 0;
  90271. });
  90272. _dragBehavior.onDragObservable.add(function (event) {
  90273. _this.onDragObservable.notifyObservers({});
  90274. if (_this.attachedMesh) {
  90275. var worldDragDirection = startingTurnDirection;
  90276. // Project the world right on to the drag plane
  90277. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90278. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90279. // project drag delta on to the resulting drag axis and rotate based on that
  90280. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90281. // Rotate based on axis
  90282. if (!_this.attachedMesh.rotationQuaternion) {
  90283. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90284. }
  90285. // Do not allow the object to turn more than a full circle
  90286. totalTurnAmountOfDrag += projectDist;
  90287. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90288. if (i_1 >= 8) {
  90289. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90290. }
  90291. else if (i_1 >= 4) {
  90292. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90293. }
  90294. else {
  90295. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90296. }
  90297. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  90298. }
  90299. }
  90300. });
  90301. // Selection/deselection
  90302. _dragBehavior.onDragStartObservable.add(function () {
  90303. _this.onDragStartObservable.notifyObservers({});
  90304. _this._selectNode(sphere);
  90305. });
  90306. _dragBehavior.onDragEndObservable.add(function () {
  90307. _this.onDragEndObservable.notifyObservers({});
  90308. _this._selectNode(null);
  90309. });
  90310. this_1._rotateSpheresParent.addChild(sphere);
  90311. };
  90312. var this_1 = this, _dragBehavior;
  90313. for (var i_1 = 0; i_1 < 12; i_1++) {
  90314. _loop_1(i_1);
  90315. }
  90316. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90317. // Create scale cubes
  90318. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90319. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90320. for (var i = 0; i < 2; i++) {
  90321. for (var j = 0; j < 2; j++) {
  90322. var _loop_2 = function () {
  90323. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90324. box.material = coloredMaterial;
  90325. // Dragging logic
  90326. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90327. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90328. _dragBehavior.moveAttached = false;
  90329. box.addBehavior(_dragBehavior);
  90330. _dragBehavior.onDragObservable.add(function (event) {
  90331. _this.onDragObservable.notifyObservers({});
  90332. if (_this.attachedMesh) {
  90333. // Current boudning box dimensions
  90334. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  90335. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  90336. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  90337. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90338. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90339. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  90340. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  90341. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  90342. // Update scale and position
  90343. _this.attachedMesh.scaling.addInPlace(deltaScale);
  90344. if (_this.attachedMesh.scaling.x < 0 || _this.attachedMesh.scaling.y < 0 || _this.attachedMesh.scaling.z < 0) {
  90345. _this.attachedMesh.scaling.subtractInPlace(deltaScale);
  90346. }
  90347. else {
  90348. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  90349. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  90350. }
  90351. }
  90352. });
  90353. // Selection/deselection
  90354. _dragBehavior.onDragStartObservable.add(function () {
  90355. _this.onDragStartObservable.notifyObservers({});
  90356. _this._selectNode(box);
  90357. });
  90358. _dragBehavior.onDragEndObservable.add(function () {
  90359. _this.onDragEndObservable.notifyObservers({});
  90360. _this._selectNode(null);
  90361. });
  90362. this_2._scaleBoxesParent.addChild(box);
  90363. };
  90364. var this_2 = this, _dragBehavior;
  90365. for (var k = 0; k < 2; k++) {
  90366. _loop_2();
  90367. }
  90368. }
  90369. }
  90370. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90371. // Hover color change
  90372. var pointerIds = new Array();
  90373. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90374. if (!pointerIds[pointerInfo.event.pointerId]) {
  90375. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90376. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90377. pointerIds[pointerInfo.event.pointerId] = mesh;
  90378. mesh.material = hoverColoredMaterial;
  90379. }
  90380. });
  90381. }
  90382. else {
  90383. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90384. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90385. delete pointerIds[pointerInfo.event.pointerId];
  90386. }
  90387. }
  90388. });
  90389. // Update bounding box positions
  90390. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90391. _this._updateBoundingBox();
  90392. });
  90393. _this._updateBoundingBox();
  90394. return _this;
  90395. }
  90396. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90397. this._rotateSpheresParent.getChildMeshes()
  90398. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90399. m.isVisible = (!selectedMesh || m == selectedMesh);
  90400. });
  90401. };
  90402. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90403. if (this.attachedMesh) {
  90404. // Update bounding dimensions/positions
  90405. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  90406. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  90407. this._boundingDimensions.copyFrom(boundBoxDimensions);
  90408. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90409. }
  90410. // Update rotation sphere locations
  90411. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90412. for (var i = 0; i < 3; i++) {
  90413. for (var j = 0; j < 2; j++) {
  90414. for (var k = 0; k < 2; k++) {
  90415. var index = ((i * 4) + (j * 2)) + k;
  90416. if (i == 0) {
  90417. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90418. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90419. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90420. }
  90421. if (i == 1) {
  90422. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90423. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90424. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90425. }
  90426. if (i == 2) {
  90427. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90428. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90429. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90430. }
  90431. if (this.fixedDragMeshScreenSize) {
  90432. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90433. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90434. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90435. }
  90436. else {
  90437. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90438. }
  90439. }
  90440. }
  90441. }
  90442. // Update scale box locations
  90443. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90444. for (var i = 0; i < 2; i++) {
  90445. for (var j = 0; j < 2; j++) {
  90446. for (var k = 0; k < 2; k++) {
  90447. var index = ((i * 4) + (j * 2)) + k;
  90448. if (scaleBoxes[index]) {
  90449. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90450. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90451. if (this.fixedDragMeshScreenSize) {
  90452. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90453. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90454. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90455. }
  90456. else {
  90457. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90458. }
  90459. }
  90460. }
  90461. }
  90462. }
  90463. };
  90464. /**
  90465. * Enables rotation on the specified axis and disables rotation on the others
  90466. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90467. */
  90468. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90469. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90470. if (i < 4) {
  90471. m.setEnabled(axis.indexOf("x") != -1);
  90472. }
  90473. else if (i < 8) {
  90474. m.setEnabled(axis.indexOf("y") != -1);
  90475. }
  90476. else {
  90477. m.setEnabled(axis.indexOf("z") != -1);
  90478. }
  90479. });
  90480. };
  90481. /**
  90482. * Disposes of the gizmo
  90483. */
  90484. BoundingBoxGizmo.prototype.dispose = function () {
  90485. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90486. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90487. this._lineBoundingBox.dispose();
  90488. this._rotateSpheresParent.dispose();
  90489. this._scaleBoxesParent.dispose();
  90490. _super.prototype.dispose.call(this);
  90491. };
  90492. return BoundingBoxGizmo;
  90493. }(BABYLON.Gizmo));
  90494. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90495. })(BABYLON || (BABYLON = {}));
  90496. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90497. var BABYLON;
  90498. (function (BABYLON) {
  90499. /**
  90500. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90501. */
  90502. var GizmoManager = /** @class */ (function () {
  90503. /**
  90504. * Instatiates a gizmo manager
  90505. * @param scene the scene to overlay the gizmos on top of
  90506. * @param options If only a single gizmo should exist at one time
  90507. */
  90508. function GizmoManager(scene, options) {
  90509. var _this = this;
  90510. this.scene = scene;
  90511. // Set of gizmos that are currently in the scene for each mesh
  90512. this._gizmoSet = {};
  90513. this._pointerObserver = null;
  90514. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  90515. // Options parsing
  90516. if (!options) {
  90517. options = {};
  90518. }
  90519. if (options.singleGizmo === undefined) {
  90520. options.singleGizmo = true;
  90521. }
  90522. // Instatiate/dispose gizmos based on pointer actions
  90523. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90524. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90525. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90526. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  90527. if (options.singleGizmo) {
  90528. _this._clearGizmos();
  90529. }
  90530. // Enable gizmo when mesh is selected
  90531. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  90532. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90533. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90534. }
  90535. else {
  90536. if (!options.singleGizmo) {
  90537. // Disable gizmo when clicked again
  90538. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  90539. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  90540. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  90541. }
  90542. }
  90543. }
  90544. else {
  90545. if (options.singleGizmo) {
  90546. // Disable gizmo when clicked away
  90547. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90548. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  90549. if (gizmoPick && !gizmoPick.hit) {
  90550. _this._clearGizmos();
  90551. }
  90552. }
  90553. }
  90554. }
  90555. }
  90556. });
  90557. }
  90558. /**
  90559. * Disposes of the gizmo manager
  90560. */
  90561. GizmoManager.prototype.dispose = function () {
  90562. this.scene.onPointerObservable.remove(this._pointerObserver);
  90563. this._clearGizmos();
  90564. this._gizmoLayer.dispose();
  90565. };
  90566. GizmoManager.prototype._clearGizmos = function () {
  90567. for (var key in this._gizmoSet) {
  90568. if (this._gizmoSet.hasOwnProperty(key)) {
  90569. this._gizmoSet[key].positionGizmo.dispose();
  90570. this._gizmoSet[key].rotationGizmo.dispose();
  90571. delete this._gizmoSet[key];
  90572. }
  90573. }
  90574. };
  90575. return GizmoManager;
  90576. }());
  90577. BABYLON.GizmoManager = GizmoManager;
  90578. })(BABYLON || (BABYLON = {}));
  90579. //# sourceMappingURL=babylon.gizmoManager.js.map
  90580. var BABYLON;
  90581. (function (BABYLON) {
  90582. /**
  90583. * Defines a target to use with MorphTargetManager
  90584. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90585. */
  90586. var MorphTarget = /** @class */ (function () {
  90587. /**
  90588. * Creates a new MorphTarget
  90589. * @param name defines the name of the target
  90590. * @param influence defines the influence to use
  90591. */
  90592. function MorphTarget(
  90593. /** defines the name of the target */
  90594. name, influence, scene) {
  90595. if (influence === void 0) { influence = 0; }
  90596. if (scene === void 0) { scene = null; }
  90597. this.name = name;
  90598. /**
  90599. * Gets or sets the list of animations
  90600. */
  90601. this.animations = new Array();
  90602. this._positions = null;
  90603. this._normals = null;
  90604. this._tangents = null;
  90605. /**
  90606. * Observable raised when the influence changes
  90607. */
  90608. this.onInfluenceChanged = new BABYLON.Observable();
  90609. this._animationPropertiesOverride = null;
  90610. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90611. this.influence = influence;
  90612. }
  90613. Object.defineProperty(MorphTarget.prototype, "influence", {
  90614. /**
  90615. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90616. */
  90617. get: function () {
  90618. return this._influence;
  90619. },
  90620. set: function (influence) {
  90621. if (this._influence === influence) {
  90622. return;
  90623. }
  90624. var previous = this._influence;
  90625. this._influence = influence;
  90626. if (this.onInfluenceChanged.hasObservers) {
  90627. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90628. }
  90629. },
  90630. enumerable: true,
  90631. configurable: true
  90632. });
  90633. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90634. /**
  90635. * Gets or sets the animation properties override
  90636. */
  90637. get: function () {
  90638. if (!this._animationPropertiesOverride && this._scene) {
  90639. return this._scene.animationPropertiesOverride;
  90640. }
  90641. return this._animationPropertiesOverride;
  90642. },
  90643. set: function (value) {
  90644. this._animationPropertiesOverride = value;
  90645. },
  90646. enumerable: true,
  90647. configurable: true
  90648. });
  90649. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90650. /**
  90651. * Gets a boolean defining if the target contains position data
  90652. */
  90653. get: function () {
  90654. return !!this._positions;
  90655. },
  90656. enumerable: true,
  90657. configurable: true
  90658. });
  90659. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90660. /**
  90661. * Gets a boolean defining if the target contains normal data
  90662. */
  90663. get: function () {
  90664. return !!this._normals;
  90665. },
  90666. enumerable: true,
  90667. configurable: true
  90668. });
  90669. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90670. /**
  90671. * Gets a boolean defining if the target contains tangent data
  90672. */
  90673. get: function () {
  90674. return !!this._tangents;
  90675. },
  90676. enumerable: true,
  90677. configurable: true
  90678. });
  90679. /**
  90680. * Affects position data to this target
  90681. * @param data defines the position data to use
  90682. */
  90683. MorphTarget.prototype.setPositions = function (data) {
  90684. this._positions = data;
  90685. };
  90686. /**
  90687. * Gets the position data stored in this target
  90688. * @returns a FloatArray containing the position data (or null if not present)
  90689. */
  90690. MorphTarget.prototype.getPositions = function () {
  90691. return this._positions;
  90692. };
  90693. /**
  90694. * Affects normal data to this target
  90695. * @param data defines the normal data to use
  90696. */
  90697. MorphTarget.prototype.setNormals = function (data) {
  90698. this._normals = data;
  90699. };
  90700. /**
  90701. * Gets the normal data stored in this target
  90702. * @returns a FloatArray containing the normal data (or null if not present)
  90703. */
  90704. MorphTarget.prototype.getNormals = function () {
  90705. return this._normals;
  90706. };
  90707. /**
  90708. * Affects tangent data to this target
  90709. * @param data defines the tangent data to use
  90710. */
  90711. MorphTarget.prototype.setTangents = function (data) {
  90712. this._tangents = data;
  90713. };
  90714. /**
  90715. * Gets the tangent data stored in this target
  90716. * @returns a FloatArray containing the tangent data (or null if not present)
  90717. */
  90718. MorphTarget.prototype.getTangents = function () {
  90719. return this._tangents;
  90720. };
  90721. /**
  90722. * Serializes the current target into a Serialization object
  90723. * @returns the serialized object
  90724. */
  90725. MorphTarget.prototype.serialize = function () {
  90726. var serializationObject = {};
  90727. serializationObject.name = this.name;
  90728. serializationObject.influence = this.influence;
  90729. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90730. if (this.hasNormals) {
  90731. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90732. }
  90733. if (this.hasTangents) {
  90734. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90735. }
  90736. // Animations
  90737. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90738. return serializationObject;
  90739. };
  90740. // Statics
  90741. /**
  90742. * Creates a new target from serialized data
  90743. * @param serializationObject defines the serialized data to use
  90744. * @returns a new MorphTarget
  90745. */
  90746. MorphTarget.Parse = function (serializationObject) {
  90747. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90748. result.setPositions(serializationObject.positions);
  90749. if (serializationObject.normals) {
  90750. result.setNormals(serializationObject.normals);
  90751. }
  90752. if (serializationObject.tangents) {
  90753. result.setTangents(serializationObject.tangents);
  90754. }
  90755. // Animations
  90756. if (serializationObject.animations) {
  90757. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90758. var parsedAnimation = serializationObject.animations[animationIndex];
  90759. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90760. }
  90761. }
  90762. return result;
  90763. };
  90764. /**
  90765. * Creates a MorphTarget from mesh data
  90766. * @param mesh defines the source mesh
  90767. * @param name defines the name to use for the new target
  90768. * @param influence defines the influence to attach to the target
  90769. * @returns a new MorphTarget
  90770. */
  90771. MorphTarget.FromMesh = function (mesh, name, influence) {
  90772. if (!name) {
  90773. name = mesh.name;
  90774. }
  90775. var result = new MorphTarget(name, influence, mesh.getScene());
  90776. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90777. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90778. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90779. }
  90780. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90781. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90782. }
  90783. return result;
  90784. };
  90785. return MorphTarget;
  90786. }());
  90787. BABYLON.MorphTarget = MorphTarget;
  90788. })(BABYLON || (BABYLON = {}));
  90789. //# sourceMappingURL=babylon.morphTarget.js.map
  90790. var BABYLON;
  90791. (function (BABYLON) {
  90792. /**
  90793. * This class is used to deform meshes using morphing between different targets
  90794. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90795. */
  90796. var MorphTargetManager = /** @class */ (function () {
  90797. /**
  90798. * Creates a new MorphTargetManager
  90799. * @param scene defines the current scene
  90800. */
  90801. function MorphTargetManager(scene) {
  90802. if (scene === void 0) { scene = null; }
  90803. this._targets = new Array();
  90804. this._targetObservable = new Array();
  90805. this._activeTargets = new BABYLON.SmartArray(16);
  90806. this._supportsNormals = false;
  90807. this._supportsTangents = false;
  90808. this._vertexCount = 0;
  90809. this._uniqueId = 0;
  90810. this._tempInfluences = new Array();
  90811. if (!scene) {
  90812. scene = BABYLON.Engine.LastCreatedScene;
  90813. }
  90814. this._scene = scene;
  90815. if (this._scene) {
  90816. this._scene.morphTargetManagers.push(this);
  90817. this._uniqueId = this._scene.getUniqueId();
  90818. }
  90819. }
  90820. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90821. /**
  90822. * Gets the unique ID of this manager
  90823. */
  90824. get: function () {
  90825. return this._uniqueId;
  90826. },
  90827. enumerable: true,
  90828. configurable: true
  90829. });
  90830. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90831. /**
  90832. * Gets the number of vertices handled by this manager
  90833. */
  90834. get: function () {
  90835. return this._vertexCount;
  90836. },
  90837. enumerable: true,
  90838. configurable: true
  90839. });
  90840. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90841. /**
  90842. * Gets a boolean indicating if this manager supports morphing of normals
  90843. */
  90844. get: function () {
  90845. return this._supportsNormals;
  90846. },
  90847. enumerable: true,
  90848. configurable: true
  90849. });
  90850. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90851. /**
  90852. * Gets a boolean indicating if this manager supports morphing of tangents
  90853. */
  90854. get: function () {
  90855. return this._supportsTangents;
  90856. },
  90857. enumerable: true,
  90858. configurable: true
  90859. });
  90860. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90861. /**
  90862. * Gets the number of targets stored in this manager
  90863. */
  90864. get: function () {
  90865. return this._targets.length;
  90866. },
  90867. enumerable: true,
  90868. configurable: true
  90869. });
  90870. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90871. /**
  90872. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90873. */
  90874. get: function () {
  90875. return this._activeTargets.length;
  90876. },
  90877. enumerable: true,
  90878. configurable: true
  90879. });
  90880. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90881. /**
  90882. * Gets the list of influences (one per target)
  90883. */
  90884. get: function () {
  90885. return this._influences;
  90886. },
  90887. enumerable: true,
  90888. configurable: true
  90889. });
  90890. /**
  90891. * Gets the active target at specified index. An active target is a target with an influence > 0
  90892. * @param index defines the index to check
  90893. * @returns the requested target
  90894. */
  90895. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90896. return this._activeTargets.data[index];
  90897. };
  90898. /**
  90899. * Gets the target at specified index
  90900. * @param index defines the index to check
  90901. * @returns the requested target
  90902. */
  90903. MorphTargetManager.prototype.getTarget = function (index) {
  90904. return this._targets[index];
  90905. };
  90906. /**
  90907. * Add a new target to this manager
  90908. * @param target defines the target to add
  90909. */
  90910. MorphTargetManager.prototype.addTarget = function (target) {
  90911. var _this = this;
  90912. this._targets.push(target);
  90913. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90914. _this._syncActiveTargets(needUpdate);
  90915. }));
  90916. this._syncActiveTargets(true);
  90917. };
  90918. /**
  90919. * Removes a target from the manager
  90920. * @param target defines the target to remove
  90921. */
  90922. MorphTargetManager.prototype.removeTarget = function (target) {
  90923. var index = this._targets.indexOf(target);
  90924. if (index >= 0) {
  90925. this._targets.splice(index, 1);
  90926. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90927. this._syncActiveTargets(true);
  90928. }
  90929. };
  90930. /**
  90931. * Serializes the current manager into a Serialization object
  90932. * @returns the serialized object
  90933. */
  90934. MorphTargetManager.prototype.serialize = function () {
  90935. var serializationObject = {};
  90936. serializationObject.id = this.uniqueId;
  90937. serializationObject.targets = [];
  90938. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90939. var target = _a[_i];
  90940. serializationObject.targets.push(target.serialize());
  90941. }
  90942. return serializationObject;
  90943. };
  90944. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90945. var influenceCount = 0;
  90946. this._activeTargets.reset();
  90947. this._supportsNormals = true;
  90948. this._supportsTangents = true;
  90949. this._vertexCount = 0;
  90950. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90951. var target = _a[_i];
  90952. this._activeTargets.push(target);
  90953. this._tempInfluences[influenceCount++] = target.influence;
  90954. var positions = target.getPositions();
  90955. if (positions) {
  90956. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90957. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90958. var vertexCount = positions.length / 3;
  90959. if (this._vertexCount === 0) {
  90960. this._vertexCount = vertexCount;
  90961. }
  90962. else if (this._vertexCount !== vertexCount) {
  90963. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90964. return;
  90965. }
  90966. }
  90967. }
  90968. if (!this._influences || this._influences.length !== influenceCount) {
  90969. this._influences = new Float32Array(influenceCount);
  90970. }
  90971. for (var index = 0; index < influenceCount; index++) {
  90972. this._influences[index] = this._tempInfluences[index];
  90973. }
  90974. if (needUpdate) {
  90975. this.synchronize();
  90976. }
  90977. };
  90978. /**
  90979. * Syncrhonize the targets with all the meshes using this morph target manager
  90980. */
  90981. MorphTargetManager.prototype.synchronize = function () {
  90982. if (!this._scene) {
  90983. return;
  90984. }
  90985. // Flag meshes as dirty to resync with the active targets
  90986. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90987. var mesh = _a[_i];
  90988. if (mesh.morphTargetManager === this) {
  90989. mesh._syncGeometryWithMorphTargetManager();
  90990. }
  90991. }
  90992. };
  90993. // Statics
  90994. /**
  90995. * Creates a new MorphTargetManager from serialized data
  90996. * @param serializationObject defines the serialized data
  90997. * @param scene defines the hosting scene
  90998. * @returns the new MorphTargetManager
  90999. */
  91000. MorphTargetManager.Parse = function (serializationObject, scene) {
  91001. var result = new MorphTargetManager(scene);
  91002. result._uniqueId = serializationObject.id;
  91003. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  91004. var targetData = _a[_i];
  91005. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  91006. }
  91007. return result;
  91008. };
  91009. return MorphTargetManager;
  91010. }());
  91011. BABYLON.MorphTargetManager = MorphTargetManager;
  91012. })(BABYLON || (BABYLON = {}));
  91013. //# sourceMappingURL=babylon.morphTargetManager.js.map
  91014. var BABYLON;
  91015. (function (BABYLON) {
  91016. var Octree = /** @class */ (function () {
  91017. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  91018. if (maxDepth === void 0) { maxDepth = 2; }
  91019. this.maxDepth = maxDepth;
  91020. this.dynamicContent = new Array();
  91021. this._maxBlockCapacity = maxBlockCapacity || 64;
  91022. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  91023. this._creationFunc = creationFunc;
  91024. }
  91025. // Methods
  91026. Octree.prototype.update = function (worldMin, worldMax, entries) {
  91027. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  91028. };
  91029. Octree.prototype.addMesh = function (entry) {
  91030. for (var index = 0; index < this.blocks.length; index++) {
  91031. var block = this.blocks[index];
  91032. block.addEntry(entry);
  91033. }
  91034. };
  91035. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  91036. this._selectionContent.reset();
  91037. for (var index = 0; index < this.blocks.length; index++) {
  91038. var block = this.blocks[index];
  91039. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  91040. }
  91041. if (allowDuplicate) {
  91042. this._selectionContent.concat(this.dynamicContent);
  91043. }
  91044. else {
  91045. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91046. }
  91047. return this._selectionContent;
  91048. };
  91049. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  91050. this._selectionContent.reset();
  91051. for (var index = 0; index < this.blocks.length; index++) {
  91052. var block = this.blocks[index];
  91053. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91054. }
  91055. if (allowDuplicate) {
  91056. this._selectionContent.concat(this.dynamicContent);
  91057. }
  91058. else {
  91059. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91060. }
  91061. return this._selectionContent;
  91062. };
  91063. Octree.prototype.intersectsRay = function (ray) {
  91064. this._selectionContent.reset();
  91065. for (var index = 0; index < this.blocks.length; index++) {
  91066. var block = this.blocks[index];
  91067. block.intersectsRay(ray, this._selectionContent);
  91068. }
  91069. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91070. return this._selectionContent;
  91071. };
  91072. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91073. target.blocks = new Array();
  91074. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91075. // Segmenting space
  91076. for (var x = 0; x < 2; x++) {
  91077. for (var y = 0; y < 2; y++) {
  91078. for (var z = 0; z < 2; z++) {
  91079. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91080. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91081. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91082. block.addEntries(entries);
  91083. target.blocks.push(block);
  91084. }
  91085. }
  91086. }
  91087. };
  91088. Octree.CreationFuncForMeshes = function (entry, block) {
  91089. var boundingInfo = entry.getBoundingInfo();
  91090. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91091. block.entries.push(entry);
  91092. }
  91093. };
  91094. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91095. var boundingInfo = entry.getBoundingInfo();
  91096. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91097. block.entries.push(entry);
  91098. }
  91099. };
  91100. return Octree;
  91101. }());
  91102. BABYLON.Octree = Octree;
  91103. })(BABYLON || (BABYLON = {}));
  91104. //# sourceMappingURL=babylon.octree.js.map
  91105. var BABYLON;
  91106. (function (BABYLON) {
  91107. var OctreeBlock = /** @class */ (function () {
  91108. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91109. this.entries = new Array();
  91110. this._boundingVectors = new Array();
  91111. this._capacity = capacity;
  91112. this._depth = depth;
  91113. this._maxDepth = maxDepth;
  91114. this._creationFunc = creationFunc;
  91115. this._minPoint = minPoint;
  91116. this._maxPoint = maxPoint;
  91117. this._boundingVectors.push(minPoint.clone());
  91118. this._boundingVectors.push(maxPoint.clone());
  91119. this._boundingVectors.push(minPoint.clone());
  91120. this._boundingVectors[2].x = maxPoint.x;
  91121. this._boundingVectors.push(minPoint.clone());
  91122. this._boundingVectors[3].y = maxPoint.y;
  91123. this._boundingVectors.push(minPoint.clone());
  91124. this._boundingVectors[4].z = maxPoint.z;
  91125. this._boundingVectors.push(maxPoint.clone());
  91126. this._boundingVectors[5].z = minPoint.z;
  91127. this._boundingVectors.push(maxPoint.clone());
  91128. this._boundingVectors[6].x = minPoint.x;
  91129. this._boundingVectors.push(maxPoint.clone());
  91130. this._boundingVectors[7].y = minPoint.y;
  91131. }
  91132. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91133. // Property
  91134. get: function () {
  91135. return this._capacity;
  91136. },
  91137. enumerable: true,
  91138. configurable: true
  91139. });
  91140. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91141. get: function () {
  91142. return this._minPoint;
  91143. },
  91144. enumerable: true,
  91145. configurable: true
  91146. });
  91147. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91148. get: function () {
  91149. return this._maxPoint;
  91150. },
  91151. enumerable: true,
  91152. configurable: true
  91153. });
  91154. // Methods
  91155. OctreeBlock.prototype.addEntry = function (entry) {
  91156. if (this.blocks) {
  91157. for (var index = 0; index < this.blocks.length; index++) {
  91158. var block = this.blocks[index];
  91159. block.addEntry(entry);
  91160. }
  91161. return;
  91162. }
  91163. this._creationFunc(entry, this);
  91164. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91165. this.createInnerBlocks();
  91166. }
  91167. };
  91168. OctreeBlock.prototype.addEntries = function (entries) {
  91169. for (var index = 0; index < entries.length; index++) {
  91170. var mesh = entries[index];
  91171. this.addEntry(mesh);
  91172. }
  91173. };
  91174. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91175. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91176. if (this.blocks) {
  91177. for (var index = 0; index < this.blocks.length; index++) {
  91178. var block = this.blocks[index];
  91179. block.select(frustumPlanes, selection, allowDuplicate);
  91180. }
  91181. return;
  91182. }
  91183. if (allowDuplicate) {
  91184. selection.concat(this.entries);
  91185. }
  91186. else {
  91187. selection.concatWithNoDuplicate(this.entries);
  91188. }
  91189. }
  91190. };
  91191. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91192. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91193. if (this.blocks) {
  91194. for (var index = 0; index < this.blocks.length; index++) {
  91195. var block = this.blocks[index];
  91196. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91197. }
  91198. return;
  91199. }
  91200. if (allowDuplicate) {
  91201. selection.concat(this.entries);
  91202. }
  91203. else {
  91204. selection.concatWithNoDuplicate(this.entries);
  91205. }
  91206. }
  91207. };
  91208. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91209. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91210. if (this.blocks) {
  91211. for (var index = 0; index < this.blocks.length; index++) {
  91212. var block = this.blocks[index];
  91213. block.intersectsRay(ray, selection);
  91214. }
  91215. return;
  91216. }
  91217. selection.concatWithNoDuplicate(this.entries);
  91218. }
  91219. };
  91220. OctreeBlock.prototype.createInnerBlocks = function () {
  91221. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91222. };
  91223. return OctreeBlock;
  91224. }());
  91225. BABYLON.OctreeBlock = OctreeBlock;
  91226. })(BABYLON || (BABYLON = {}));
  91227. //# sourceMappingURL=babylon.octreeBlock.js.map
  91228. var BABYLON;
  91229. (function (BABYLON) {
  91230. /**
  91231. * Postprocess used to generate anaglyphic rendering
  91232. */
  91233. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91234. __extends(AnaglyphPostProcess, _super);
  91235. /**
  91236. * Creates a new AnaglyphPostProcess
  91237. * @param name defines postprocess name
  91238. * @param options defines creation options or target ratio scale
  91239. * @param rigCameras defines cameras using this postprocess
  91240. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91241. * @param engine defines hosting engine
  91242. * @param reusable defines if the postprocess will be reused multiple times per frame
  91243. */
  91244. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91245. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91246. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91247. _this.onApplyObservable.add(function (effect) {
  91248. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91249. });
  91250. return _this;
  91251. }
  91252. return AnaglyphPostProcess;
  91253. }(BABYLON.PostProcess));
  91254. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91255. })(BABYLON || (BABYLON = {}));
  91256. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91257. var BABYLON;
  91258. (function (BABYLON) {
  91259. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91260. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91261. });
  91262. /**
  91263. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91264. */
  91265. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91266. __extends(AnaglyphArcRotateCamera, _super);
  91267. /**
  91268. * Creates a new AnaglyphArcRotateCamera
  91269. * @param name defines camera name
  91270. * @param alpha defines alpha angle (in radians)
  91271. * @param beta defines beta angle (in radians)
  91272. * @param radius defines radius
  91273. * @param target defines camera target
  91274. * @param interaxialDistance defines distance between each color axis
  91275. * @param scene defines the hosting scene
  91276. */
  91277. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91278. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91279. _this.interaxialDistance = interaxialDistance;
  91280. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91281. return _this;
  91282. }
  91283. /**
  91284. * Gets camera class name
  91285. * @returns AnaglyphArcRotateCamera
  91286. */
  91287. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91288. return "AnaglyphArcRotateCamera";
  91289. };
  91290. return AnaglyphArcRotateCamera;
  91291. }(BABYLON.ArcRotateCamera));
  91292. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91293. })(BABYLON || (BABYLON = {}));
  91294. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  91295. var BABYLON;
  91296. (function (BABYLON) {
  91297. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  91298. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91299. });
  91300. /**
  91301. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91302. */
  91303. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91304. __extends(AnaglyphFreeCamera, _super);
  91305. /**
  91306. * Creates a new AnaglyphFreeCamera
  91307. * @param name defines camera name
  91308. * @param position defines initial position
  91309. * @param interaxialDistance defines distance between each color axis
  91310. * @param scene defines the hosting scene
  91311. */
  91312. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91313. var _this = _super.call(this, name, position, scene) || this;
  91314. _this.interaxialDistance = interaxialDistance;
  91315. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91316. return _this;
  91317. }
  91318. /**
  91319. * Gets camera class name
  91320. * @returns AnaglyphFreeCamera
  91321. */
  91322. AnaglyphFreeCamera.prototype.getClassName = function () {
  91323. return "AnaglyphFreeCamera";
  91324. };
  91325. return AnaglyphFreeCamera;
  91326. }(BABYLON.FreeCamera));
  91327. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91328. })(BABYLON || (BABYLON = {}));
  91329. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  91330. var BABYLON;
  91331. (function (BABYLON) {
  91332. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  91333. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91334. });
  91335. /**
  91336. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91337. */
  91338. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91339. __extends(AnaglyphGamepadCamera, _super);
  91340. /**
  91341. * Creates a new AnaglyphGamepadCamera
  91342. * @param name defines camera name
  91343. * @param position defines initial position
  91344. * @param interaxialDistance defines distance between each color axis
  91345. * @param scene defines the hosting scene
  91346. */
  91347. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91348. var _this = _super.call(this, name, position, scene) || this;
  91349. _this.interaxialDistance = interaxialDistance;
  91350. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91351. return _this;
  91352. }
  91353. /**
  91354. * Gets camera class name
  91355. * @returns AnaglyphGamepadCamera
  91356. */
  91357. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91358. return "AnaglyphGamepadCamera";
  91359. };
  91360. return AnaglyphGamepadCamera;
  91361. }(BABYLON.GamepadCamera));
  91362. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91363. })(BABYLON || (BABYLON = {}));
  91364. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  91365. var BABYLON;
  91366. (function (BABYLON) {
  91367. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  91368. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91369. });
  91370. /**
  91371. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91372. */
  91373. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91374. __extends(AnaglyphUniversalCamera, _super);
  91375. /**
  91376. * Creates a new AnaglyphUniversalCamera
  91377. * @param name defines camera name
  91378. * @param position defines initial position
  91379. * @param interaxialDistance defines distance between each color axis
  91380. * @param scene defines the hosting scene
  91381. */
  91382. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91383. var _this = _super.call(this, name, position, scene) || this;
  91384. _this.interaxialDistance = interaxialDistance;
  91385. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91386. return _this;
  91387. }
  91388. /**
  91389. * Gets camera class name
  91390. * @returns AnaglyphUniversalCamera
  91391. */
  91392. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91393. return "AnaglyphUniversalCamera";
  91394. };
  91395. return AnaglyphUniversalCamera;
  91396. }(BABYLON.UniversalCamera));
  91397. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91398. })(BABYLON || (BABYLON = {}));
  91399. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  91400. var BABYLON;
  91401. (function (BABYLON) {
  91402. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  91403. __extends(VRDistortionCorrectionPostProcess, _super);
  91404. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  91405. var _this = _super.call(this, name, "vrDistortionCorrection", [
  91406. 'LensCenter',
  91407. 'Scale',
  91408. 'ScaleIn',
  91409. 'HmdWarpParam'
  91410. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  91411. _this._isRightEye = isRightEye;
  91412. _this._distortionFactors = vrMetrics.distortionK;
  91413. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  91414. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  91415. _this.adaptScaleToCurrentViewport = true;
  91416. _this.onSizeChangedObservable.add(function () {
  91417. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  91418. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  91419. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  91420. });
  91421. _this.onApplyObservable.add(function (effect) {
  91422. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  91423. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  91424. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  91425. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  91426. });
  91427. return _this;
  91428. }
  91429. return VRDistortionCorrectionPostProcess;
  91430. }(BABYLON.PostProcess));
  91431. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  91432. })(BABYLON || (BABYLON = {}));
  91433. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  91434. var BABYLON;
  91435. (function (BABYLON) {
  91436. /**
  91437. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  91438. * Screen rotation is taken into account.
  91439. */
  91440. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  91441. function FreeCameraDeviceOrientationInput() {
  91442. var _this = this;
  91443. this._screenOrientationAngle = 0;
  91444. this._screenQuaternion = new BABYLON.Quaternion();
  91445. this._alpha = 0;
  91446. this._beta = 0;
  91447. this._gamma = 0;
  91448. this._orientationChanged = function () {
  91449. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  91450. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  91451. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  91452. };
  91453. this._deviceOrientation = function (evt) {
  91454. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  91455. _this._beta = evt.beta !== null ? evt.beta : 0;
  91456. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  91457. };
  91458. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91459. this._orientationChanged();
  91460. }
  91461. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91462. get: function () {
  91463. return this._camera;
  91464. },
  91465. set: function (camera) {
  91466. this._camera = camera;
  91467. if (this._camera != null && !this._camera.rotationQuaternion) {
  91468. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91469. }
  91470. },
  91471. enumerable: true,
  91472. configurable: true
  91473. });
  91474. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91475. window.addEventListener("orientationchange", this._orientationChanged);
  91476. window.addEventListener("deviceorientation", this._deviceOrientation);
  91477. //In certain cases, the attach control is called AFTER orientation was changed,
  91478. //So this is needed.
  91479. this._orientationChanged();
  91480. };
  91481. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91482. window.removeEventListener("orientationchange", this._orientationChanged);
  91483. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91484. };
  91485. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91486. //if no device orientation provided, don't update the rotation.
  91487. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91488. if (!this._alpha)
  91489. return;
  91490. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91491. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91492. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91493. //Mirror on XY Plane
  91494. this._camera.rotationQuaternion.z *= -1;
  91495. this._camera.rotationQuaternion.w *= -1;
  91496. };
  91497. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91498. return "FreeCameraDeviceOrientationInput";
  91499. };
  91500. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91501. return "deviceOrientation";
  91502. };
  91503. return FreeCameraDeviceOrientationInput;
  91504. }());
  91505. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91506. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91507. })(BABYLON || (BABYLON = {}));
  91508. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91509. var BABYLON;
  91510. (function (BABYLON) {
  91511. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91512. function ArcRotateCameraVRDeviceOrientationInput() {
  91513. this.alphaCorrection = 1;
  91514. this.betaCorrection = 1;
  91515. this.gammaCorrection = 1;
  91516. this._alpha = 0;
  91517. this._gamma = 0;
  91518. this._dirty = false;
  91519. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91520. }
  91521. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91522. this.camera.attachControl(element, noPreventDefault);
  91523. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91524. };
  91525. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91526. if (evt.alpha !== null) {
  91527. this._alpha = +evt.alpha | 0;
  91528. }
  91529. if (evt.gamma !== null) {
  91530. this._gamma = +evt.gamma | 0;
  91531. }
  91532. this._dirty = true;
  91533. };
  91534. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91535. if (this._dirty) {
  91536. this._dirty = false;
  91537. if (this._gamma < 0) {
  91538. this._gamma = 180 + this._gamma;
  91539. }
  91540. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91541. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91542. }
  91543. };
  91544. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91545. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91546. };
  91547. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91548. return "ArcRotateCameraVRDeviceOrientationInput";
  91549. };
  91550. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91551. return "VRDeviceOrientation";
  91552. };
  91553. return ArcRotateCameraVRDeviceOrientationInput;
  91554. }());
  91555. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91556. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91557. })(BABYLON || (BABYLON = {}));
  91558. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91559. var BABYLON;
  91560. (function (BABYLON) {
  91561. var VRCameraMetrics = /** @class */ (function () {
  91562. function VRCameraMetrics() {
  91563. this.compensateDistortion = true;
  91564. }
  91565. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91566. get: function () {
  91567. return this.hResolution / (2 * this.vResolution);
  91568. },
  91569. enumerable: true,
  91570. configurable: true
  91571. });
  91572. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91573. get: function () {
  91574. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91575. },
  91576. enumerable: true,
  91577. configurable: true
  91578. });
  91579. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91580. get: function () {
  91581. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91582. var h = (4 * meters) / this.hScreenSize;
  91583. return BABYLON.Matrix.Translation(h, 0, 0);
  91584. },
  91585. enumerable: true,
  91586. configurable: true
  91587. });
  91588. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91589. get: function () {
  91590. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91591. var h = (4 * meters) / this.hScreenSize;
  91592. return BABYLON.Matrix.Translation(-h, 0, 0);
  91593. },
  91594. enumerable: true,
  91595. configurable: true
  91596. });
  91597. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91598. get: function () {
  91599. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91600. },
  91601. enumerable: true,
  91602. configurable: true
  91603. });
  91604. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91605. get: function () {
  91606. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91607. },
  91608. enumerable: true,
  91609. configurable: true
  91610. });
  91611. VRCameraMetrics.GetDefault = function () {
  91612. var result = new VRCameraMetrics();
  91613. result.hResolution = 1280;
  91614. result.vResolution = 800;
  91615. result.hScreenSize = 0.149759993;
  91616. result.vScreenSize = 0.0935999975;
  91617. result.vScreenCenter = 0.0467999987;
  91618. result.eyeToScreenDistance = 0.0410000011;
  91619. result.lensSeparationDistance = 0.0635000020;
  91620. result.interpupillaryDistance = 0.0640000030;
  91621. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91622. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91623. result.postProcessScaleFactor = 1.714605507808412;
  91624. result.lensCenterOffset = 0.151976421;
  91625. return result;
  91626. };
  91627. return VRCameraMetrics;
  91628. }());
  91629. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91630. })(BABYLON || (BABYLON = {}));
  91631. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91632. var BABYLON;
  91633. (function (BABYLON) {
  91634. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  91635. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91636. });
  91637. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  91638. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91639. });
  91640. /**
  91641. * This represents a WebVR camera.
  91642. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91643. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91644. */
  91645. var WebVRFreeCamera = /** @class */ (function (_super) {
  91646. __extends(WebVRFreeCamera, _super);
  91647. /**
  91648. * Instantiates a WebVRFreeCamera.
  91649. * @param name The name of the WebVRFreeCamera
  91650. * @param position The starting anchor position for the camera
  91651. * @param scene The scene the camera belongs to
  91652. * @param webVROptions a set of customizable options for the webVRCamera
  91653. */
  91654. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91655. if (webVROptions === void 0) { webVROptions = {}; }
  91656. var _this = _super.call(this, name, position, scene) || this;
  91657. _this.webVROptions = webVROptions;
  91658. /**
  91659. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  91660. */
  91661. _this._vrDevice = null;
  91662. /**
  91663. * The rawPose of the vrDevice.
  91664. */
  91665. _this.rawPose = null;
  91666. _this._specsVersion = "1.1";
  91667. _this._attached = false;
  91668. _this._descendants = [];
  91669. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  91670. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  91671. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  91672. _this._standingMatrix = null;
  91673. /**
  91674. * Represents device position in babylon space.
  91675. */
  91676. _this.devicePosition = BABYLON.Vector3.Zero();
  91677. /**
  91678. * Represents device rotation in babylon space.
  91679. */
  91680. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  91681. /**
  91682. * The scale of the device to be used when translating from device space to babylon space.
  91683. */
  91684. _this.deviceScaleFactor = 1;
  91685. _this._deviceToWorld = BABYLON.Matrix.Identity();
  91686. _this._worldToDevice = BABYLON.Matrix.Identity();
  91687. /**
  91688. * References to the webVR controllers for the vrDevice.
  91689. */
  91690. _this.controllers = [];
  91691. /**
  91692. * Emits an event when a controller is attached.
  91693. */
  91694. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91695. /**
  91696. * Emits an event when a controller's mesh has been loaded;
  91697. */
  91698. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91699. /**
  91700. * If the rig cameras be used as parent instead of this camera.
  91701. */
  91702. _this.rigParenting = true;
  91703. _this._defaultHeight = undefined;
  91704. _this._workingVector = BABYLON.Vector3.Zero();
  91705. _this._oneVector = BABYLON.Vector3.One();
  91706. _this._workingMatrix = BABYLON.Matrix.Identity();
  91707. _this._cache.position = BABYLON.Vector3.Zero();
  91708. if (webVROptions.defaultHeight) {
  91709. _this._defaultHeight = webVROptions.defaultHeight;
  91710. _this.position.y = _this._defaultHeight;
  91711. }
  91712. _this.minZ = 0.1;
  91713. //legacy support - the compensation boolean was removed.
  91714. if (arguments.length === 5) {
  91715. _this.webVROptions = arguments[4];
  91716. }
  91717. // default webVR options
  91718. if (_this.webVROptions.trackPosition == undefined) {
  91719. _this.webVROptions.trackPosition = true;
  91720. }
  91721. if (_this.webVROptions.controllerMeshes == undefined) {
  91722. _this.webVROptions.controllerMeshes = true;
  91723. }
  91724. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91725. _this.webVROptions.defaultLightingOnControllers = true;
  91726. }
  91727. _this.rotationQuaternion = new BABYLON.Quaternion();
  91728. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91729. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91730. }
  91731. //enable VR
  91732. var engine = _this.getEngine();
  91733. _this._onVREnabled = function (success) { if (success) {
  91734. _this.initControllers();
  91735. } };
  91736. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91737. engine.initWebVR().add(function (event) {
  91738. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91739. return;
  91740. }
  91741. _this._vrDevice = event.vrDisplay;
  91742. //reset the rig parameters.
  91743. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91744. if (_this._attached) {
  91745. _this.getEngine().enableVR();
  91746. }
  91747. });
  91748. if (typeof (VRFrameData) !== "undefined")
  91749. _this._frameData = new VRFrameData();
  91750. /**
  91751. * The idea behind the following lines:
  91752. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91753. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91754. * the second will not show it correctly.
  91755. *
  91756. * To solve this - each object that has the camera as parent will be added to a protected array.
  91757. * When the rig camera renders, it will take this array and set all of those to be its children.
  91758. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91759. * Amazing!
  91760. */
  91761. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91762. if (camera.parent === _this && _this.rigParenting) {
  91763. _this._descendants = _this.getDescendants(true, function (n) {
  91764. // don't take the cameras or the controllers!
  91765. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91766. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91767. return !isController && !isRigCamera;
  91768. });
  91769. _this._descendants.forEach(function (node) {
  91770. node.parent = camera;
  91771. });
  91772. }
  91773. });
  91774. scene.onAfterCameraRenderObservable.add(function (camera) {
  91775. if (camera.parent === _this && _this.rigParenting) {
  91776. _this._descendants.forEach(function (node) {
  91777. node.parent = _this;
  91778. });
  91779. }
  91780. });
  91781. return _this;
  91782. }
  91783. /**
  91784. * Gets the device distance from the ground in meters.
  91785. * @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.
  91786. */
  91787. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91788. if (this._standingMatrix) {
  91789. // Add standing matrix offset to get real offset from ground in room
  91790. this._standingMatrix.getTranslationToRef(this._workingVector);
  91791. return this._deviceRoomPosition.y + this._workingVector.y;
  91792. }
  91793. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91794. return this._defaultHeight || 0;
  91795. };
  91796. /**
  91797. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91798. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91799. */
  91800. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91801. var _this = this;
  91802. if (callback === void 0) { callback = function (bool) { }; }
  91803. // Use standing matrix if available
  91804. this.getEngine().initWebVRAsync().then(function (result) {
  91805. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91806. callback(false);
  91807. }
  91808. else {
  91809. _this._standingMatrix = new BABYLON.Matrix();
  91810. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91811. if (!_this.getScene().useRightHandedSystem) {
  91812. [2, 6, 8, 9, 14].forEach(function (num) {
  91813. if (_this._standingMatrix) {
  91814. _this._standingMatrix.m[num] *= -1;
  91815. }
  91816. });
  91817. }
  91818. callback(true);
  91819. }
  91820. });
  91821. };
  91822. /**
  91823. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91824. * @returns A promise with a boolean set to if the standing matrix is supported.
  91825. */
  91826. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91827. var _this = this;
  91828. return new Promise(function (res, rej) {
  91829. _this.useStandingMatrix(function (supported) {
  91830. res(supported);
  91831. });
  91832. });
  91833. };
  91834. /**
  91835. * Disposes the camera
  91836. */
  91837. WebVRFreeCamera.prototype.dispose = function () {
  91838. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91839. _super.prototype.dispose.call(this);
  91840. };
  91841. /**
  91842. * Gets a vrController by name.
  91843. * @param name The name of the controller to retreive
  91844. * @returns the controller matching the name specified or null if not found
  91845. */
  91846. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91847. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91848. var gp = _a[_i];
  91849. if (gp.hand === name) {
  91850. return gp;
  91851. }
  91852. }
  91853. return null;
  91854. };
  91855. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91856. /**
  91857. * The controller corrisponding to the users left hand.
  91858. */
  91859. get: function () {
  91860. if (!this._leftController) {
  91861. this._leftController = this.getControllerByName("left");
  91862. }
  91863. return this._leftController;
  91864. },
  91865. enumerable: true,
  91866. configurable: true
  91867. });
  91868. ;
  91869. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91870. /**
  91871. * The controller corrisponding to the users right hand.
  91872. */
  91873. get: function () {
  91874. if (!this._rightController) {
  91875. this._rightController = this.getControllerByName("right");
  91876. }
  91877. return this._rightController;
  91878. },
  91879. enumerable: true,
  91880. configurable: true
  91881. });
  91882. ;
  91883. /**
  91884. * Casts a ray forward from the vrCamera's gaze.
  91885. * @param length Length of the ray (default: 100)
  91886. * @returns the ray corrisponding to the gaze
  91887. */
  91888. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91889. if (length === void 0) { length = 100; }
  91890. if (this.leftCamera) {
  91891. // Use left eye to avoid computation to compute center on every call
  91892. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91893. }
  91894. else {
  91895. return _super.prototype.getForwardRay.call(this, length);
  91896. }
  91897. };
  91898. /**
  91899. * Updates the camera based on device's frame data
  91900. */
  91901. WebVRFreeCamera.prototype._checkInputs = function () {
  91902. if (this._vrDevice && this._vrDevice.isPresenting) {
  91903. this._vrDevice.getFrameData(this._frameData);
  91904. this.updateFromDevice(this._frameData.pose);
  91905. }
  91906. _super.prototype._checkInputs.call(this);
  91907. };
  91908. /**
  91909. * Updates the poseControlled values based on the input device pose.
  91910. * @param poseData Pose coming from the device
  91911. */
  91912. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91913. if (poseData && poseData.orientation) {
  91914. this.rawPose = poseData;
  91915. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91916. if (this.getScene().useRightHandedSystem) {
  91917. this._deviceRoomRotationQuaternion.z *= -1;
  91918. this._deviceRoomRotationQuaternion.w *= -1;
  91919. }
  91920. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91921. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91922. if (this.getScene().useRightHandedSystem) {
  91923. this._deviceRoomPosition.z *= -1;
  91924. }
  91925. }
  91926. }
  91927. };
  91928. /**
  91929. * WebVR's attach control will start broadcasting frames to the device.
  91930. * Note that in certain browsers (chrome for example) this function must be called
  91931. * within a user-interaction callback. Example:
  91932. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91933. *
  91934. * @param element html element to attach the vrDevice to
  91935. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91936. */
  91937. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91938. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91939. this._attached = true;
  91940. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91941. if (this._vrDevice) {
  91942. this.getEngine().enableVR();
  91943. }
  91944. };
  91945. /**
  91946. * Detaches the camera from the html element and disables VR
  91947. *
  91948. * @param element html element to detach from
  91949. */
  91950. WebVRFreeCamera.prototype.detachControl = function (element) {
  91951. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91952. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91953. _super.prototype.detachControl.call(this, element);
  91954. this._attached = false;
  91955. this.getEngine().disableVR();
  91956. };
  91957. /**
  91958. * @returns the name of this class
  91959. */
  91960. WebVRFreeCamera.prototype.getClassName = function () {
  91961. return "WebVRFreeCamera";
  91962. };
  91963. /**
  91964. * Calls resetPose on the vrDisplay
  91965. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91966. */
  91967. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91968. //uses the vrDisplay's "resetPose()".
  91969. //pitch and roll won't be affected.
  91970. this._vrDevice.resetPose();
  91971. };
  91972. /**
  91973. * Updates the rig cameras (left and right eye)
  91974. */
  91975. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91976. var camLeft = this._rigCameras[0];
  91977. var camRight = this._rigCameras[1];
  91978. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91979. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91980. camLeft.position.copyFrom(this._deviceRoomPosition);
  91981. camRight.position.copyFrom(this._deviceRoomPosition);
  91982. };
  91983. /**
  91984. * Updates the cached values of the camera
  91985. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91986. */
  91987. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91988. var _this = this;
  91989. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91990. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91991. if (!this.updateCacheCalled) {
  91992. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91993. this.updateCacheCalled = true;
  91994. this.update();
  91995. }
  91996. // Set working vector to the device position in room space rotated by the new rotation
  91997. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91998. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91999. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92000. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92001. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92002. // Add translation from anchor position
  92003. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92004. this._workingVector.addInPlace(this.position);
  92005. this._workingVector.subtractInPlace(this._cache.position);
  92006. this._deviceToWorld.setTranslation(this._workingVector);
  92007. // Set an inverted matrix to be used when updating the camera
  92008. this._deviceToWorld.invertToRef(this._worldToDevice);
  92009. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92010. this.controllers.forEach(function (controller) {
  92011. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92012. controller.update();
  92013. });
  92014. }
  92015. if (!ignoreParentClass) {
  92016. _super.prototype._updateCache.call(this);
  92017. }
  92018. this.updateCacheCalled = false;
  92019. };
  92020. /**
  92021. * Updates the current device position and rotation in the babylon world
  92022. */
  92023. WebVRFreeCamera.prototype.update = function () {
  92024. // Get current device position in babylon world
  92025. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  92026. // Get current device rotation in babylon world
  92027. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  92028. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  92029. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  92030. _super.prototype.update.call(this);
  92031. };
  92032. /**
  92033. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  92034. * @returns an identity matrix
  92035. */
  92036. WebVRFreeCamera.prototype._getViewMatrix = function () {
  92037. return BABYLON.Matrix.Identity();
  92038. };
  92039. /**
  92040. * This function is called by the two RIG cameras.
  92041. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  92042. */
  92043. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  92044. var _this = this;
  92045. // Update the parent camera prior to using a child camera to avoid desynchronization
  92046. var parentCamera = this._cameraRigParams["parentCamera"];
  92047. parentCamera._updateCache();
  92048. //WebVR 1.1
  92049. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  92050. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  92051. if (!this.getScene().useRightHandedSystem) {
  92052. [2, 6, 8, 9, 14].forEach(function (num) {
  92053. _this._webvrViewMatrix.m[num] *= -1;
  92054. });
  92055. }
  92056. // update the camera rotation matrix
  92057. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  92058. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  92059. // Computing target and final matrix
  92060. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  92061. // should the view matrix be updated with scale and position offset?
  92062. if (parentCamera.deviceScaleFactor !== 1) {
  92063. this._webvrViewMatrix.invert();
  92064. // scale the position, if set
  92065. if (parentCamera.deviceScaleFactor) {
  92066. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  92067. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  92068. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  92069. }
  92070. this._webvrViewMatrix.invert();
  92071. }
  92072. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  92073. // Compute global position
  92074. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  92075. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  92076. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  92077. this._workingMatrix.getTranslationToRef(this._globalPosition);
  92078. this._markSyncedWithParent();
  92079. return this._webvrViewMatrix;
  92080. };
  92081. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  92082. var _this = this;
  92083. var parentCamera = this.parent;
  92084. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  92085. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  92086. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  92087. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  92088. //babylon compatible matrix
  92089. if (!this.getScene().useRightHandedSystem) {
  92090. [8, 9, 10, 11].forEach(function (num) {
  92091. _this._projectionMatrix.m[num] *= -1;
  92092. });
  92093. }
  92094. return this._projectionMatrix;
  92095. };
  92096. /**
  92097. * Initializes the controllers and their meshes
  92098. */
  92099. WebVRFreeCamera.prototype.initControllers = function () {
  92100. var _this = this;
  92101. this.controllers = [];
  92102. var manager = this.getScene().gamepadManager;
  92103. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  92104. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92105. var webVrController = gamepad;
  92106. if (webVrController.defaultModel) {
  92107. webVrController.defaultModel.setEnabled(false);
  92108. }
  92109. if (webVrController.hand === "right") {
  92110. _this._rightController = null;
  92111. }
  92112. if (webVrController.hand === "left") {
  92113. _this._leftController = null;
  92114. }
  92115. var controllerIndex = _this.controllers.indexOf(webVrController);
  92116. if (controllerIndex !== -1) {
  92117. _this.controllers.splice(controllerIndex, 1);
  92118. }
  92119. }
  92120. });
  92121. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  92122. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92123. var webVrController_1 = gamepad;
  92124. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  92125. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  92126. if (_this.webVROptions.controllerMeshes) {
  92127. if (webVrController_1.defaultModel) {
  92128. webVrController_1.defaultModel.setEnabled(true);
  92129. }
  92130. else {
  92131. // Load the meshes
  92132. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  92133. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  92134. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  92135. if (_this.webVROptions.defaultLightingOnControllers) {
  92136. if (!_this._lightOnControllers) {
  92137. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  92138. }
  92139. var activateLightOnSubMeshes_1 = function (mesh, light) {
  92140. var children = mesh.getChildren();
  92141. if (children.length !== 0) {
  92142. children.forEach(function (mesh) {
  92143. light.includedOnlyMeshes.push(mesh);
  92144. activateLightOnSubMeshes_1(mesh, light);
  92145. });
  92146. }
  92147. };
  92148. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  92149. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  92150. }
  92151. });
  92152. }
  92153. }
  92154. webVrController_1.attachToPoseControlledCamera(_this);
  92155. // since this is async - sanity check. Is the controller already stored?
  92156. if (_this.controllers.indexOf(webVrController_1) === -1) {
  92157. //add to the controllers array
  92158. _this.controllers.push(webVrController_1);
  92159. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  92160. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  92161. // So we're overriding setting left & right manually to be sure
  92162. var firstViveWandDetected = false;
  92163. for (var i = 0; i < _this.controllers.length; i++) {
  92164. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92165. if (!firstViveWandDetected) {
  92166. firstViveWandDetected = true;
  92167. _this.controllers[i].hand = "left";
  92168. }
  92169. else {
  92170. _this.controllers[i].hand = "right";
  92171. }
  92172. }
  92173. }
  92174. //did we find enough controllers? Great! let the developer know.
  92175. if (_this.controllers.length >= 2) {
  92176. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  92177. }
  92178. }
  92179. }
  92180. });
  92181. };
  92182. return WebVRFreeCamera;
  92183. }(BABYLON.FreeCamera));
  92184. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  92185. })(BABYLON || (BABYLON = {}));
  92186. //# sourceMappingURL=babylon.webVRCamera.js.map
  92187. var BABYLON;
  92188. (function (BABYLON) {
  92189. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  92190. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  92191. });
  92192. // We're mainly based on the logic defined into the FreeCamera code
  92193. /**
  92194. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  92195. * being tilted forward or back and left or right.
  92196. */
  92197. var DeviceOrientationCamera = /** @class */ (function (_super) {
  92198. __extends(DeviceOrientationCamera, _super);
  92199. /**
  92200. * Creates a new device orientation camera
  92201. * @param name The name of the camera
  92202. * @param position The start position camera
  92203. * @param scene The scene the camera belongs to
  92204. */
  92205. function DeviceOrientationCamera(name, position, scene) {
  92206. var _this = _super.call(this, name, position, scene) || this;
  92207. _this._quaternionCache = new BABYLON.Quaternion();
  92208. _this.inputs.addDeviceOrientation();
  92209. return _this;
  92210. }
  92211. /**
  92212. * Gets the current instance class name ("DeviceOrientationCamera").
  92213. * This helps avoiding instanceof at run time.
  92214. * @returns the class name
  92215. */
  92216. DeviceOrientationCamera.prototype.getClassName = function () {
  92217. return "DeviceOrientationCamera";
  92218. };
  92219. /**
  92220. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  92221. */
  92222. DeviceOrientationCamera.prototype._checkInputs = function () {
  92223. _super.prototype._checkInputs.call(this);
  92224. this._quaternionCache.copyFrom(this.rotationQuaternion);
  92225. if (this._initialQuaternion) {
  92226. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92227. }
  92228. };
  92229. /**
  92230. * Reset the camera to its default orientation on the specified axis only.
  92231. * @param axis The axis to reset
  92232. */
  92233. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  92234. var _this = this;
  92235. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  92236. //can only work if this camera has a rotation quaternion already.
  92237. if (!this.rotationQuaternion)
  92238. return;
  92239. if (!this._initialQuaternion) {
  92240. this._initialQuaternion = new BABYLON.Quaternion();
  92241. }
  92242. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  92243. ['x', 'y', 'z'].forEach(function (axisName) {
  92244. if (!axis[axisName]) {
  92245. _this._initialQuaternion[axisName] = 0;
  92246. }
  92247. else {
  92248. _this._initialQuaternion[axisName] *= -1;
  92249. }
  92250. });
  92251. this._initialQuaternion.normalize();
  92252. //force rotation update
  92253. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92254. };
  92255. return DeviceOrientationCamera;
  92256. }(BABYLON.FreeCamera));
  92257. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  92258. })(BABYLON || (BABYLON = {}));
  92259. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  92260. var BABYLON;
  92261. (function (BABYLON) {
  92262. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92263. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92264. });
  92265. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  92266. __extends(VRDeviceOrientationFreeCamera, _super);
  92267. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92268. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92269. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92270. var _this = _super.call(this, name, position, scene) || this;
  92271. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92272. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92273. return _this;
  92274. }
  92275. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  92276. return "VRDeviceOrientationFreeCamera";
  92277. };
  92278. return VRDeviceOrientationFreeCamera;
  92279. }(BABYLON.DeviceOrientationCamera));
  92280. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  92281. })(BABYLON || (BABYLON = {}));
  92282. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  92283. var BABYLON;
  92284. (function (BABYLON) {
  92285. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92286. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  92287. });
  92288. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  92289. __extends(VRDeviceOrientationArcRotateCamera, _super);
  92290. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  92291. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92292. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92293. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92294. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92295. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92296. _this.inputs.addVRDeviceOrientation();
  92297. return _this;
  92298. }
  92299. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  92300. return "VRDeviceOrientationArcRotateCamera";
  92301. };
  92302. return VRDeviceOrientationArcRotateCamera;
  92303. }(BABYLON.ArcRotateCamera));
  92304. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  92305. })(BABYLON || (BABYLON = {}));
  92306. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  92307. var BABYLON;
  92308. (function (BABYLON) {
  92309. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  92310. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  92311. });
  92312. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  92313. __extends(VRDeviceOrientationGamepadCamera, _super);
  92314. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92315. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92316. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92317. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  92318. _this.inputs.addGamepad();
  92319. return _this;
  92320. }
  92321. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  92322. return "VRDeviceOrientationGamepadCamera";
  92323. };
  92324. return VRDeviceOrientationGamepadCamera;
  92325. }(BABYLON.VRDeviceOrientationFreeCamera));
  92326. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  92327. })(BABYLON || (BABYLON = {}));
  92328. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  92329. var BABYLON;
  92330. (function (BABYLON) {
  92331. var VRExperienceHelperGazer = /** @class */ (function () {
  92332. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92333. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92334. this.scene = scene;
  92335. this._pointerDownOnMeshAsked = false;
  92336. this._isActionableMesh = false;
  92337. this._teleportationRequestInitiated = false;
  92338. this._teleportationBackRequestInitiated = false;
  92339. this._rotationRightAsked = false;
  92340. this._rotationLeftAsked = false;
  92341. this._dpadPressed = true;
  92342. this._activePointer = false;
  92343. this._id = VRExperienceHelperGazer._idCounter++;
  92344. // Gaze tracker
  92345. if (!gazeTrackerToClone) {
  92346. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92347. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92348. this._gazeTracker.isPickable = false;
  92349. this._gazeTracker.isVisible = false;
  92350. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92351. targetMat.specularColor = BABYLON.Color3.Black();
  92352. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92353. targetMat.backFaceCulling = false;
  92354. this._gazeTracker.material = targetMat;
  92355. }
  92356. else {
  92357. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92358. }
  92359. }
  92360. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92361. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92362. };
  92363. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92364. this._pointerDownOnMeshAsked = true;
  92365. if (this._currentHit) {
  92366. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92367. }
  92368. };
  92369. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92370. if (this._currentHit) {
  92371. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92372. }
  92373. this._pointerDownOnMeshAsked = false;
  92374. };
  92375. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92376. this._activePointer = true;
  92377. };
  92378. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92379. this._activePointer = false;
  92380. };
  92381. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92382. if (distance === void 0) { distance = 100; }
  92383. };
  92384. VRExperienceHelperGazer.prototype.dispose = function () {
  92385. this._interactionsEnabled = false;
  92386. this._teleportationEnabled = false;
  92387. if (this._gazeTracker) {
  92388. this._gazeTracker.dispose();
  92389. }
  92390. };
  92391. VRExperienceHelperGazer._idCounter = 0;
  92392. return VRExperienceHelperGazer;
  92393. }());
  92394. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92395. __extends(VRExperienceHelperControllerGazer, _super);
  92396. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92397. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92398. _this.webVRController = webVRController;
  92399. // Laser pointer
  92400. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92401. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92402. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92403. laserPointerMaterial.alpha = 0.6;
  92404. _this._laserPointer.material = laserPointerMaterial;
  92405. _this._laserPointer.rotation.x = Math.PI / 2;
  92406. _this._laserPointer.position.z = -0.5;
  92407. _this._laserPointer.isVisible = false;
  92408. _this._laserPointer.isPickable = false;
  92409. if (!webVRController.mesh) {
  92410. // Create an empty mesh that is used prior to loading the high quality model
  92411. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92412. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92413. preloadPointerPose.rotation.x = -0.7;
  92414. preloadMesh.addChild(preloadPointerPose);
  92415. webVRController.attachToMesh(preloadMesh);
  92416. }
  92417. _this._setLaserPointerParent(webVRController.mesh);
  92418. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92419. _this._setLaserPointerParent(mesh);
  92420. });
  92421. return _this;
  92422. }
  92423. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92424. return this.webVRController.getForwardRay(length);
  92425. };
  92426. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92427. _super.prototype._activatePointer.call(this);
  92428. this._laserPointer.isVisible = true;
  92429. };
  92430. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92431. _super.prototype._deactivatePointer.call(this);
  92432. this._laserPointer.isVisible = false;
  92433. };
  92434. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92435. this._laserPointer.material.emissiveColor = color;
  92436. };
  92437. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92438. var makeNotPick = function (root) {
  92439. root.name += " laserPointer";
  92440. root.isPickable = false;
  92441. root.getChildMeshes().forEach(function (c) {
  92442. makeNotPick(c);
  92443. });
  92444. };
  92445. makeNotPick(mesh);
  92446. var childMeshes = mesh.getChildMeshes();
  92447. this.webVRController._pointingPoseNode = null;
  92448. for (var i = 0; i < childMeshes.length; i++) {
  92449. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92450. mesh = childMeshes[i];
  92451. this.webVRController._pointingPoseNode = mesh;
  92452. break;
  92453. }
  92454. }
  92455. this._laserPointer.parent = mesh;
  92456. };
  92457. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92458. if (distance === void 0) { distance = 100; }
  92459. this._laserPointer.scaling.y = distance;
  92460. this._laserPointer.position.z = -distance / 2;
  92461. };
  92462. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92463. _super.prototype.dispose.call(this);
  92464. this._laserPointer.dispose();
  92465. if (this._meshAttachedObserver) {
  92466. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92467. }
  92468. };
  92469. return VRExperienceHelperControllerGazer;
  92470. }(VRExperienceHelperGazer));
  92471. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92472. __extends(VRExperienceHelperCameraGazer, _super);
  92473. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92474. var _this = _super.call(this, scene) || this;
  92475. _this.getCamera = getCamera;
  92476. return _this;
  92477. }
  92478. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92479. var camera = this.getCamera();
  92480. if (camera) {
  92481. return camera.getForwardRay(length);
  92482. }
  92483. else {
  92484. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92485. }
  92486. };
  92487. return VRExperienceHelperCameraGazer;
  92488. }(VRExperienceHelperGazer));
  92489. /**
  92490. * Helps to quickly add VR support to an existing scene.
  92491. * See http://doc.babylonjs.com/how_to/webvr_helper
  92492. */
  92493. var VRExperienceHelper = /** @class */ (function () {
  92494. /**
  92495. * Instantiates a VRExperienceHelper.
  92496. * Helps to quickly add VR support to an existing scene.
  92497. * @param scene The scene the VRExperienceHelper belongs to.
  92498. * @param webVROptions Options to modify the vr experience helper's behavior.
  92499. */
  92500. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92501. if (webVROptions === void 0) { webVROptions = {}; }
  92502. var _this = this;
  92503. this.webVROptions = webVROptions;
  92504. // Can the system support WebVR, even if a headset isn't plugged in?
  92505. this._webVRsupported = false;
  92506. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92507. this._webVRready = false;
  92508. // Are we waiting for the requestPresent callback to complete?
  92509. this._webVRrequesting = false;
  92510. // Are we presenting to the headset right now?
  92511. this._webVRpresenting = false;
  92512. // Are we presenting in the fullscreen fallback?
  92513. this._fullscreenVRpresenting = false;
  92514. /**
  92515. * Observable raised when entering VR.
  92516. */
  92517. this.onEnteringVRObservable = new BABYLON.Observable();
  92518. /**
  92519. * Observable raised when exiting VR.
  92520. */
  92521. this.onExitingVRObservable = new BABYLON.Observable();
  92522. /**
  92523. * Observable raised when controller mesh is loaded.
  92524. */
  92525. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92526. this._useCustomVRButton = false;
  92527. this._teleportationRequested = false;
  92528. this._teleportActive = false;
  92529. this._floorMeshesCollection = [];
  92530. this._rotationAllowed = true;
  92531. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92532. this._isDefaultTeleportationTarget = true;
  92533. this._teleportationFillColor = "#444444";
  92534. this._teleportationBorderColor = "#FFFFFF";
  92535. this._rotationAngle = 0;
  92536. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92537. this._padSensibilityUp = 0.65;
  92538. this._padSensibilityDown = 0.35;
  92539. this.leftController = null;
  92540. this.rightController = null;
  92541. /**
  92542. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92543. */
  92544. this.onNewMeshSelected = new BABYLON.Observable();
  92545. /**
  92546. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92547. */
  92548. this.onNewMeshPicked = new BABYLON.Observable();
  92549. /**
  92550. * Observable raised before camera teleportation
  92551. */
  92552. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92553. /**
  92554. * Observable raised after camera teleportation
  92555. */
  92556. this.onAfterCameraTeleport = new BABYLON.Observable();
  92557. /**
  92558. * Observable raised when current selected mesh gets unselected
  92559. */
  92560. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92561. /**
  92562. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92563. */
  92564. this.teleportationEnabled = true;
  92565. this._teleportationInitialized = false;
  92566. this._interactionsEnabled = false;
  92567. this._interactionsRequested = false;
  92568. this._displayGaze = true;
  92569. this._displayLaserPointer = true;
  92570. this._onResize = function () {
  92571. _this.moveButtonToBottomRight();
  92572. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92573. _this.exitVR();
  92574. }
  92575. };
  92576. this._onFullscreenChange = function () {
  92577. if (document.fullscreen !== undefined) {
  92578. _this._fullscreenVRpresenting = document.fullscreen;
  92579. }
  92580. else if (document.mozFullScreen !== undefined) {
  92581. _this._fullscreenVRpresenting = document.mozFullScreen;
  92582. }
  92583. else if (document.webkitIsFullScreen !== undefined) {
  92584. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92585. }
  92586. else if (document.msIsFullScreen !== undefined) {
  92587. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92588. }
  92589. else if (document.msFullscreenElement !== undefined) {
  92590. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92591. }
  92592. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92593. _this.exitVR();
  92594. if (!_this._useCustomVRButton) {
  92595. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92596. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92597. }
  92598. }
  92599. };
  92600. this.beforeRender = function () {
  92601. if (_this.leftController && _this.leftController._activePointer) {
  92602. _this._castRayAndSelectObject(_this.leftController);
  92603. }
  92604. if (_this.rightController && _this.rightController._activePointer) {
  92605. _this._castRayAndSelectObject(_this.rightController);
  92606. }
  92607. if (_this._noControllerIsActive) {
  92608. _this._castRayAndSelectObject(_this._cameraGazer);
  92609. }
  92610. else {
  92611. _this._cameraGazer._gazeTracker.isVisible = false;
  92612. }
  92613. };
  92614. this._onNewGamepadConnected = function (gamepad) {
  92615. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92616. if (gamepad.leftStick) {
  92617. gamepad.onleftstickchanged(function (stickValues) {
  92618. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92619. // Listening to classic/xbox gamepad only if no VR controller is active
  92620. if ((!_this.leftController && !_this.rightController) ||
  92621. ((_this.leftController && !_this.leftController._activePointer) &&
  92622. (_this.rightController && !_this.rightController._activePointer))) {
  92623. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92624. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92625. }
  92626. }
  92627. });
  92628. }
  92629. if (gamepad.rightStick) {
  92630. gamepad.onrightstickchanged(function (stickValues) {
  92631. if (_this._teleportationInitialized) {
  92632. _this._checkRotate(stickValues, _this._cameraGazer);
  92633. }
  92634. });
  92635. }
  92636. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92637. gamepad.onbuttondown(function (buttonPressed) {
  92638. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92639. _this._cameraGazer._selectionPointerDown();
  92640. }
  92641. });
  92642. gamepad.onbuttonup(function (buttonPressed) {
  92643. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92644. _this._cameraGazer._selectionPointerUp();
  92645. }
  92646. });
  92647. }
  92648. }
  92649. else {
  92650. var webVRController = gamepad;
  92651. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92652. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92653. _this.rightController = controller;
  92654. }
  92655. else {
  92656. _this.leftController = controller;
  92657. }
  92658. _this._tryEnableInteractionOnController(controller);
  92659. }
  92660. };
  92661. // 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
  92662. this._tryEnableInteractionOnController = function (controller) {
  92663. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92664. _this._enableInteractionOnController(controller);
  92665. }
  92666. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92667. _this._enableTeleportationOnController(controller);
  92668. }
  92669. };
  92670. this._onNewGamepadDisconnected = function (gamepad) {
  92671. if (gamepad instanceof BABYLON.WebVRController) {
  92672. if (gamepad.hand === "left" && _this.leftController != null) {
  92673. _this.leftController.dispose();
  92674. _this.leftController = null;
  92675. }
  92676. if (gamepad.hand === "right" && _this.rightController != null) {
  92677. _this.rightController.dispose();
  92678. _this.rightController = null;
  92679. }
  92680. }
  92681. };
  92682. this._workingVector = BABYLON.Vector3.Zero();
  92683. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92684. this._workingMatrix = BABYLON.Matrix.Identity();
  92685. this._scene = scene;
  92686. this._canvas = scene.getEngine().getRenderingCanvas();
  92687. // Parse options
  92688. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92689. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92690. }
  92691. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92692. webVROptions.createDeviceOrientationCamera = true;
  92693. }
  92694. if (webVROptions.laserToggle === undefined) {
  92695. webVROptions.laserToggle = true;
  92696. }
  92697. if (webVROptions.defaultHeight === undefined) {
  92698. webVROptions.defaultHeight = 1.7;
  92699. }
  92700. if (webVROptions.useCustomVRButton) {
  92701. this._useCustomVRButton = true;
  92702. if (webVROptions.customVRButton) {
  92703. this._btnVR = webVROptions.customVRButton;
  92704. }
  92705. }
  92706. if (webVROptions.rayLength) {
  92707. this._rayLength = webVROptions.rayLength;
  92708. }
  92709. this._defaultHeight = webVROptions.defaultHeight;
  92710. if (webVROptions.positionScale) {
  92711. this._rayLength *= webVROptions.positionScale;
  92712. this._defaultHeight *= webVROptions.positionScale;
  92713. }
  92714. // Set position
  92715. if (this._scene.activeCamera) {
  92716. this._position = this._scene.activeCamera.position.clone();
  92717. }
  92718. else {
  92719. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92720. }
  92721. // Set non-vr camera
  92722. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92723. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92724. // Copy data from existing camera
  92725. if (this._scene.activeCamera) {
  92726. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92727. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92728. // Set rotation from previous camera
  92729. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92730. var targetCamera = this._scene.activeCamera;
  92731. if (targetCamera.rotationQuaternion) {
  92732. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92733. }
  92734. else {
  92735. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92736. }
  92737. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92738. }
  92739. }
  92740. this._scene.activeCamera = this._deviceOrientationCamera;
  92741. if (this._canvas) {
  92742. this._scene.activeCamera.attachControl(this._canvas);
  92743. }
  92744. }
  92745. else {
  92746. this._existingCamera = this._scene.activeCamera;
  92747. }
  92748. // Create VR cameras
  92749. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92750. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92751. }
  92752. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92753. this._webVRCamera.useStandingMatrix();
  92754. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92755. // Create default button
  92756. if (!this._useCustomVRButton) {
  92757. this._btnVR = document.createElement("BUTTON");
  92758. this._btnVR.className = "babylonVRicon";
  92759. this._btnVR.id = "babylonVRiconbtn";
  92760. this._btnVR.title = "Click to switch to VR";
  92761. 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) }";
  92762. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92763. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92764. // css += ".babylonVRicon.vrdisplaysupported { }";
  92765. // css += ".babylonVRicon.vrdisplayready { }";
  92766. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92767. var style = document.createElement('style');
  92768. style.appendChild(document.createTextNode(css));
  92769. document.getElementsByTagName('head')[0].appendChild(style);
  92770. this.moveButtonToBottomRight();
  92771. }
  92772. // VR button click event
  92773. if (this._btnVR) {
  92774. this._btnVR.addEventListener("click", function () {
  92775. if (!_this.isInVRMode) {
  92776. _this.enterVR();
  92777. }
  92778. else {
  92779. _this.exitVR();
  92780. }
  92781. });
  92782. }
  92783. // Window events
  92784. window.addEventListener("resize", this._onResize);
  92785. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92786. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92787. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92788. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92789. document.onmsfullscreenchange = this._onFullscreenChange;
  92790. // Display vr button when headset is connected
  92791. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92792. this.displayVRButton();
  92793. }
  92794. else {
  92795. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92796. if (e.vrDisplay) {
  92797. _this.displayVRButton();
  92798. }
  92799. });
  92800. }
  92801. // Exiting VR mode using 'ESC' key on desktop
  92802. this._onKeyDown = function (event) {
  92803. if (event.keyCode === 27 && _this.isInVRMode) {
  92804. _this.exitVR();
  92805. }
  92806. };
  92807. document.addEventListener("keydown", this._onKeyDown);
  92808. // Exiting VR mode double tapping the touch screen
  92809. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92810. if (_this.isInVRMode) {
  92811. _this.exitVR();
  92812. if (_this._fullscreenVRpresenting) {
  92813. _this._scene.getEngine().switchFullscreen(true);
  92814. }
  92815. }
  92816. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92817. // Listen for WebVR display changes
  92818. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92819. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92820. this._onVRRequestPresentStart = function () {
  92821. _this._webVRrequesting = true;
  92822. _this.updateButtonVisibility();
  92823. };
  92824. this._onVRRequestPresentComplete = function (success) {
  92825. _this._webVRrequesting = false;
  92826. _this.updateButtonVisibility();
  92827. };
  92828. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92829. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92830. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92831. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92832. scene.onDisposeObservable.add(function () {
  92833. _this.dispose();
  92834. });
  92835. // Gamepad connection events
  92836. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92837. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92838. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92839. this.updateButtonVisibility();
  92840. //create easing functions
  92841. this._circleEase = new BABYLON.CircleEase();
  92842. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92843. if (this.webVROptions.floorMeshes) {
  92844. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92845. }
  92846. }
  92847. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92848. /** Return this.onEnteringVRObservable
  92849. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92850. */
  92851. get: function () {
  92852. return this.onEnteringVRObservable;
  92853. },
  92854. enumerable: true,
  92855. configurable: true
  92856. });
  92857. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92858. /** Return this.onExitingVRObservable
  92859. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92860. */
  92861. get: function () {
  92862. return this.onExitingVRObservable;
  92863. },
  92864. enumerable: true,
  92865. configurable: true
  92866. });
  92867. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92868. /** Return this.onControllerMeshLoadedObservable
  92869. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92870. */
  92871. get: function () {
  92872. return this.onControllerMeshLoadedObservable;
  92873. },
  92874. enumerable: true,
  92875. configurable: true
  92876. });
  92877. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92878. /**
  92879. * The mesh used to display where the user is going to teleport.
  92880. */
  92881. get: function () {
  92882. return this._teleportationTarget;
  92883. },
  92884. /**
  92885. * Sets the mesh to be used to display where the user is going to teleport.
  92886. */
  92887. set: function (value) {
  92888. if (value) {
  92889. value.name = "teleportationTarget";
  92890. this._isDefaultTeleportationTarget = false;
  92891. this._teleportationTarget = value;
  92892. }
  92893. },
  92894. enumerable: true,
  92895. configurable: true
  92896. });
  92897. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92898. /**
  92899. * The mesh used to display where the user is selecting,
  92900. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92901. * See http://doc.babylonjs.com/resources/baking_transformations
  92902. */
  92903. get: function () {
  92904. return this._cameraGazer._gazeTracker;
  92905. },
  92906. set: function (value) {
  92907. if (value) {
  92908. this._cameraGazer._gazeTracker = value;
  92909. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92910. this._cameraGazer._gazeTracker.isPickable = false;
  92911. this._cameraGazer._gazeTracker.isVisible = false;
  92912. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92913. if (this.leftController) {
  92914. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92915. }
  92916. if (this.rightController) {
  92917. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92918. }
  92919. }
  92920. },
  92921. enumerable: true,
  92922. configurable: true
  92923. });
  92924. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92925. /**
  92926. * If the ray of the gaze should be displayed.
  92927. */
  92928. get: function () {
  92929. return this._displayGaze;
  92930. },
  92931. /**
  92932. * Sets if the ray of the gaze should be displayed.
  92933. */
  92934. set: function (value) {
  92935. this._displayGaze = value;
  92936. if (!value) {
  92937. this._cameraGazer._gazeTracker.isVisible = false;
  92938. if (this.leftController) {
  92939. this.leftController._gazeTracker.isVisible = false;
  92940. }
  92941. if (this.rightController) {
  92942. this.rightController._gazeTracker.isVisible = false;
  92943. }
  92944. }
  92945. },
  92946. enumerable: true,
  92947. configurable: true
  92948. });
  92949. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92950. /**
  92951. * If the ray of the LaserPointer should be displayed.
  92952. */
  92953. get: function () {
  92954. return this._displayLaserPointer;
  92955. },
  92956. /**
  92957. * Sets if the ray of the LaserPointer should be displayed.
  92958. */
  92959. set: function (value) {
  92960. this._displayLaserPointer = value;
  92961. if (!value) {
  92962. if (this.rightController) {
  92963. this.rightController._deactivatePointer();
  92964. this.rightController._gazeTracker.isVisible = false;
  92965. }
  92966. if (this.leftController) {
  92967. this.leftController._deactivatePointer();
  92968. this.leftController._gazeTracker.isVisible = false;
  92969. }
  92970. }
  92971. else {
  92972. if (this.rightController) {
  92973. this.rightController._activatePointer();
  92974. }
  92975. if (this.leftController) {
  92976. this.leftController._activatePointer();
  92977. }
  92978. }
  92979. },
  92980. enumerable: true,
  92981. configurable: true
  92982. });
  92983. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92984. /**
  92985. * The deviceOrientationCamera used as the camera when not in VR.
  92986. */
  92987. get: function () {
  92988. return this._deviceOrientationCamera;
  92989. },
  92990. enumerable: true,
  92991. configurable: true
  92992. });
  92993. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92994. /**
  92995. * Based on the current WebVR support, returns the current VR camera used.
  92996. */
  92997. get: function () {
  92998. if (this._webVRready) {
  92999. return this._webVRCamera;
  93000. }
  93001. else {
  93002. return this._scene.activeCamera;
  93003. }
  93004. },
  93005. enumerable: true,
  93006. configurable: true
  93007. });
  93008. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93009. /**
  93010. * The webVRCamera which is used when in VR.
  93011. */
  93012. get: function () {
  93013. return this._webVRCamera;
  93014. },
  93015. enumerable: true,
  93016. configurable: true
  93017. });
  93018. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93019. /**
  93020. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93021. */
  93022. get: function () {
  93023. return this._vrDeviceOrientationCamera;
  93024. },
  93025. enumerable: true,
  93026. configurable: true
  93027. });
  93028. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93029. get: function () {
  93030. var result = this._cameraGazer._teleportationRequestInitiated
  93031. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93032. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93033. return result;
  93034. },
  93035. enumerable: true,
  93036. configurable: true
  93037. });
  93038. // Raised when one of the controller has loaded successfully its associated default mesh
  93039. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93040. if (this.leftController && this.leftController.webVRController == webVRController) {
  93041. if (webVRController.mesh) {
  93042. this.leftController._setLaserPointerParent(webVRController.mesh);
  93043. }
  93044. }
  93045. if (this.rightController && this.rightController.webVRController == webVRController) {
  93046. if (webVRController.mesh) {
  93047. this.rightController._setLaserPointerParent(webVRController.mesh);
  93048. }
  93049. }
  93050. try {
  93051. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93052. }
  93053. catch (err) {
  93054. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93055. }
  93056. };
  93057. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93058. /**
  93059. * Gets a value indicating if we are currently in VR mode.
  93060. */
  93061. get: function () {
  93062. return this._webVRpresenting || this._fullscreenVRpresenting;
  93063. },
  93064. enumerable: true,
  93065. configurable: true
  93066. });
  93067. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93068. var vrDisplay = this._scene.getEngine().getVRDevice();
  93069. if (vrDisplay) {
  93070. var wasPresenting = this._webVRpresenting;
  93071. // A VR display is connected
  93072. this._webVRpresenting = vrDisplay.isPresenting;
  93073. if (wasPresenting && !this._webVRpresenting)
  93074. this.exitVR();
  93075. }
  93076. else {
  93077. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93078. }
  93079. this.updateButtonVisibility();
  93080. };
  93081. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93082. this._webVRsupported = eventArgs.vrSupported;
  93083. this._webVRready = !!eventArgs.vrDisplay;
  93084. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93085. this.updateButtonVisibility();
  93086. };
  93087. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93088. if (this._canvas && !this._useCustomVRButton) {
  93089. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93090. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93091. }
  93092. };
  93093. VRExperienceHelper.prototype.displayVRButton = function () {
  93094. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93095. document.body.appendChild(this._btnVR);
  93096. this._btnVRDisplayed = true;
  93097. }
  93098. };
  93099. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93100. if (!this._btnVR || this._useCustomVRButton) {
  93101. return;
  93102. }
  93103. this._btnVR.className = "babylonVRicon";
  93104. if (this.isInVRMode) {
  93105. this._btnVR.className += " vrdisplaypresenting";
  93106. }
  93107. else {
  93108. if (this._webVRready)
  93109. this._btnVR.className += " vrdisplayready";
  93110. if (this._webVRsupported)
  93111. this._btnVR.className += " vrdisplaysupported";
  93112. if (this._webVRrequesting)
  93113. this._btnVR.className += " vrdisplayrequesting";
  93114. }
  93115. };
  93116. /**
  93117. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93118. * Otherwise, will use the fullscreen API.
  93119. */
  93120. VRExperienceHelper.prototype.enterVR = function () {
  93121. if (this.onEnteringVRObservable) {
  93122. try {
  93123. this.onEnteringVRObservable.notifyObservers(this);
  93124. }
  93125. catch (err) {
  93126. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93127. }
  93128. }
  93129. if (this._scene.activeCamera) {
  93130. this._position = this._scene.activeCamera.position.clone();
  93131. // make sure that we return to the last active camera
  93132. this._existingCamera = this._scene.activeCamera;
  93133. }
  93134. if (this._webVRrequesting)
  93135. return;
  93136. // If WebVR is supported and a headset is connected
  93137. if (this._webVRready) {
  93138. if (!this._webVRpresenting) {
  93139. this._webVRCamera.position = this._position;
  93140. this._scene.activeCamera = this._webVRCamera;
  93141. }
  93142. }
  93143. else if (this._vrDeviceOrientationCamera) {
  93144. this._vrDeviceOrientationCamera.position = this._position;
  93145. if (this._scene.activeCamera) {
  93146. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93147. }
  93148. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93149. this._scene.getEngine().switchFullscreen(true);
  93150. this.updateButtonVisibility();
  93151. }
  93152. if (this._scene.activeCamera && this._canvas) {
  93153. this._scene.activeCamera.attachControl(this._canvas);
  93154. }
  93155. if (this._interactionsEnabled) {
  93156. this._scene.registerBeforeRender(this.beforeRender);
  93157. }
  93158. };
  93159. /**
  93160. * Attempt to exit VR, or fullscreen.
  93161. */
  93162. VRExperienceHelper.prototype.exitVR = function () {
  93163. if (this.onExitingVRObservable) {
  93164. try {
  93165. this.onExitingVRObservable.notifyObservers(this);
  93166. }
  93167. catch (err) {
  93168. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93169. }
  93170. }
  93171. if (this._webVRpresenting) {
  93172. this._scene.getEngine().disableVR();
  93173. }
  93174. if (this._scene.activeCamera) {
  93175. this._position = this._scene.activeCamera.position.clone();
  93176. }
  93177. if (this._deviceOrientationCamera) {
  93178. this._deviceOrientationCamera.position = this._position;
  93179. this._scene.activeCamera = this._deviceOrientationCamera;
  93180. if (this._canvas) {
  93181. this._scene.activeCamera.attachControl(this._canvas);
  93182. }
  93183. }
  93184. else if (this._existingCamera) {
  93185. this._existingCamera.position = this._position;
  93186. this._scene.activeCamera = this._existingCamera;
  93187. }
  93188. this.updateButtonVisibility();
  93189. if (this._interactionsEnabled) {
  93190. this._scene.unregisterBeforeRender(this.beforeRender);
  93191. }
  93192. // resize to update width and height when exiting vr exits fullscreen
  93193. this._scene.getEngine().resize();
  93194. };
  93195. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  93196. /**
  93197. * The position of the vr experience helper.
  93198. */
  93199. get: function () {
  93200. return this._position;
  93201. },
  93202. /**
  93203. * Sets the position of the vr experience helper.
  93204. */
  93205. set: function (value) {
  93206. this._position = value;
  93207. if (this._scene.activeCamera) {
  93208. this._scene.activeCamera.position = value;
  93209. }
  93210. },
  93211. enumerable: true,
  93212. configurable: true
  93213. });
  93214. /**
  93215. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  93216. */
  93217. VRExperienceHelper.prototype.enableInteractions = function () {
  93218. var _this = this;
  93219. if (!this._interactionsEnabled) {
  93220. this._interactionsRequested = true;
  93221. if (this.leftController) {
  93222. this._enableInteractionOnController(this.leftController);
  93223. }
  93224. if (this.rightController) {
  93225. this._enableInteractionOnController(this.rightController);
  93226. }
  93227. this.raySelectionPredicate = function (mesh) {
  93228. return mesh.isVisible;
  93229. };
  93230. this.meshSelectionPredicate = function (mesh) {
  93231. return true;
  93232. };
  93233. this._raySelectionPredicate = function (mesh) {
  93234. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  93235. && mesh.name.indexOf("teleportationTarget") === -1
  93236. && mesh.name.indexOf("torusTeleportation") === -1
  93237. && mesh.name.indexOf("laserPointer") === -1)) {
  93238. return _this.raySelectionPredicate(mesh);
  93239. }
  93240. return false;
  93241. };
  93242. this._interactionsEnabled = true;
  93243. }
  93244. };
  93245. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93246. get: function () {
  93247. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93248. },
  93249. enumerable: true,
  93250. configurable: true
  93251. });
  93252. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93253. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93254. if (this._floorMeshesCollection[i].id === mesh.id) {
  93255. return true;
  93256. }
  93257. }
  93258. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93259. return true;
  93260. }
  93261. return false;
  93262. };
  93263. /**
  93264. * Adds a floor mesh to be used for teleportation.
  93265. * @param floorMesh the mesh to be used for teleportation.
  93266. */
  93267. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93268. if (!this._floorMeshesCollection) {
  93269. return;
  93270. }
  93271. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93272. return;
  93273. }
  93274. this._floorMeshesCollection.push(floorMesh);
  93275. };
  93276. /**
  93277. * Removes a floor mesh from being used for teleportation.
  93278. * @param floorMesh the mesh to be removed.
  93279. */
  93280. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93281. if (!this._floorMeshesCollection) {
  93282. return;
  93283. }
  93284. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93285. if (meshIndex !== -1) {
  93286. this._floorMeshesCollection.splice(meshIndex, 1);
  93287. }
  93288. };
  93289. /**
  93290. * Enables interactions and teleportation using the VR controllers and gaze.
  93291. * @param vrTeleportationOptions options to modify teleportation behavior.
  93292. */
  93293. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93294. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93295. if (!this._teleportationInitialized) {
  93296. this._teleportationRequested = true;
  93297. this.enableInteractions();
  93298. if (vrTeleportationOptions.floorMeshName) {
  93299. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93300. }
  93301. if (vrTeleportationOptions.floorMeshes) {
  93302. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93303. }
  93304. if (this.leftController != null) {
  93305. this._enableTeleportationOnController(this.leftController);
  93306. }
  93307. if (this.rightController != null) {
  93308. this._enableTeleportationOnController(this.rightController);
  93309. }
  93310. // Creates an image processing post process for the vignette not relying
  93311. // on the main scene configuration for image processing to reduce setup and spaces
  93312. // (gamma/linear) conflicts.
  93313. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93314. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93315. imageProcessingConfiguration.vignetteEnabled = true;
  93316. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93317. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93318. this._teleportationInitialized = true;
  93319. if (this._isDefaultTeleportationTarget) {
  93320. this._createTeleportationCircles();
  93321. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93322. }
  93323. }
  93324. };
  93325. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93326. var _this = this;
  93327. var controllerMesh = controller.webVRController.mesh;
  93328. if (controllerMesh) {
  93329. controller._interactionsEnabled = true;
  93330. controller._activatePointer();
  93331. if (this.webVROptions.laserToggle) {
  93332. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93333. // Enabling / disabling laserPointer
  93334. if (_this._displayLaserPointer && stateObject.value === 1) {
  93335. if (controller._activePointer) {
  93336. controller._deactivatePointer();
  93337. }
  93338. else {
  93339. controller._activatePointer();
  93340. }
  93341. if (_this.displayGaze) {
  93342. controller._gazeTracker.isVisible = controller._activePointer;
  93343. }
  93344. }
  93345. });
  93346. }
  93347. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93348. var gazer = controller;
  93349. if (_this._noControllerIsActive) {
  93350. gazer = _this._cameraGazer;
  93351. }
  93352. if (!gazer._pointerDownOnMeshAsked) {
  93353. if (stateObject.value > _this._padSensibilityUp) {
  93354. gazer._selectionPointerDown();
  93355. }
  93356. }
  93357. else if (stateObject.value < _this._padSensibilityDown) {
  93358. gazer._selectionPointerUp();
  93359. }
  93360. });
  93361. }
  93362. };
  93363. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93364. // Dont teleport if another gaze already requested teleportation
  93365. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93366. return;
  93367. }
  93368. if (!gazer._teleportationRequestInitiated) {
  93369. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93370. gazer._activatePointer();
  93371. gazer._teleportationRequestInitiated = true;
  93372. }
  93373. }
  93374. else {
  93375. // Listening to the proper controller values changes to confirm teleportation
  93376. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93377. if (this._teleportActive) {
  93378. this._teleportCamera(this._haloCenter);
  93379. }
  93380. gazer._teleportationRequestInitiated = false;
  93381. }
  93382. }
  93383. };
  93384. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93385. // Only rotate when user is not currently selecting a teleportation location
  93386. if (gazer._teleportationRequestInitiated) {
  93387. return;
  93388. }
  93389. if (!gazer._rotationLeftAsked) {
  93390. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93391. gazer._rotationLeftAsked = true;
  93392. if (this._rotationAllowed) {
  93393. this._rotateCamera(false);
  93394. }
  93395. }
  93396. }
  93397. else {
  93398. if (stateObject.x > -this._padSensibilityDown) {
  93399. gazer._rotationLeftAsked = false;
  93400. }
  93401. }
  93402. if (!gazer._rotationRightAsked) {
  93403. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93404. gazer._rotationRightAsked = true;
  93405. if (this._rotationAllowed) {
  93406. this._rotateCamera(true);
  93407. }
  93408. }
  93409. }
  93410. else {
  93411. if (stateObject.x < this._padSensibilityDown) {
  93412. gazer._rotationRightAsked = false;
  93413. }
  93414. }
  93415. };
  93416. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93417. // Only teleport backwards when user is not currently selecting a teleportation location
  93418. if (gazer._teleportationRequestInitiated) {
  93419. return;
  93420. }
  93421. // Teleport backwards
  93422. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93423. if (!gazer._teleportationBackRequestInitiated) {
  93424. if (!this.currentVRCamera) {
  93425. return;
  93426. }
  93427. // Get rotation and position of the current camera
  93428. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93429. var position = this.currentVRCamera.position;
  93430. // If the camera has device position, use that instead
  93431. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93432. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93433. position = this.currentVRCamera.devicePosition;
  93434. }
  93435. // Get matrix with only the y rotation of the device rotation
  93436. rotation.toEulerAnglesToRef(this._workingVector);
  93437. this._workingVector.z = 0;
  93438. this._workingVector.x = 0;
  93439. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93440. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93441. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93442. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93443. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93444. var ray = new BABYLON.Ray(position, this._workingVector);
  93445. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93446. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93447. this._teleportCamera(hit.pickedPoint);
  93448. }
  93449. gazer._teleportationBackRequestInitiated = true;
  93450. }
  93451. }
  93452. else {
  93453. gazer._teleportationBackRequestInitiated = false;
  93454. }
  93455. };
  93456. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93457. var _this = this;
  93458. var controllerMesh = controller.webVRController.mesh;
  93459. if (controllerMesh) {
  93460. if (!controller._interactionsEnabled) {
  93461. this._enableInteractionOnController(controller);
  93462. }
  93463. controller._interactionsEnabled = true;
  93464. controller._teleportationEnabled = true;
  93465. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93466. controller._dpadPressed = false;
  93467. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93468. controller._dpadPressed = stateObject.pressed;
  93469. if (!controller._dpadPressed) {
  93470. controller._rotationLeftAsked = false;
  93471. controller._rotationRightAsked = false;
  93472. controller._teleportationBackRequestInitiated = false;
  93473. }
  93474. });
  93475. }
  93476. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93477. if (_this.teleportationEnabled) {
  93478. _this._checkTeleportBackwards(stateObject, controller);
  93479. _this._checkTeleportWithRay(stateObject, controller);
  93480. }
  93481. _this._checkRotate(stateObject, controller);
  93482. });
  93483. }
  93484. };
  93485. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93486. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93487. this._teleportationTarget.isPickable = false;
  93488. var length = 512;
  93489. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93490. dynamicTexture.hasAlpha = true;
  93491. var context = dynamicTexture.getContext();
  93492. var centerX = length / 2;
  93493. var centerY = length / 2;
  93494. var radius = 200;
  93495. context.beginPath();
  93496. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93497. context.fillStyle = this._teleportationFillColor;
  93498. context.fill();
  93499. context.lineWidth = 10;
  93500. context.strokeStyle = this._teleportationBorderColor;
  93501. context.stroke();
  93502. context.closePath();
  93503. dynamicTexture.update();
  93504. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93505. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93506. this._teleportationTarget.material = teleportationCircleMaterial;
  93507. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93508. torus.isPickable = false;
  93509. torus.parent = this._teleportationTarget;
  93510. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93511. var keys = [];
  93512. keys.push({
  93513. frame: 0,
  93514. value: 0
  93515. });
  93516. keys.push({
  93517. frame: 30,
  93518. value: 0.4
  93519. });
  93520. keys.push({
  93521. frame: 60,
  93522. value: 0
  93523. });
  93524. animationInnerCircle.setKeys(keys);
  93525. var easingFunction = new BABYLON.SineEase();
  93526. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93527. animationInnerCircle.setEasingFunction(easingFunction);
  93528. torus.animations = [];
  93529. torus.animations.push(animationInnerCircle);
  93530. this._scene.beginAnimation(torus, 0, 60, true);
  93531. this._hideTeleportationTarget();
  93532. };
  93533. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93534. this._teleportActive = true;
  93535. if (this._teleportationInitialized) {
  93536. this._teleportationTarget.isVisible = true;
  93537. if (this._isDefaultTeleportationTarget) {
  93538. this._teleportationTarget.getChildren()[0].isVisible = true;
  93539. }
  93540. }
  93541. };
  93542. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93543. this._teleportActive = false;
  93544. if (this._teleportationInitialized) {
  93545. this._teleportationTarget.isVisible = false;
  93546. if (this._isDefaultTeleportationTarget) {
  93547. this._teleportationTarget.getChildren()[0].isVisible = false;
  93548. }
  93549. }
  93550. };
  93551. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93552. var _this = this;
  93553. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93554. return;
  93555. }
  93556. if (right) {
  93557. this._rotationAngle++;
  93558. }
  93559. else {
  93560. this._rotationAngle--;
  93561. }
  93562. this.currentVRCamera.animations = [];
  93563. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93564. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93565. var animationRotationKeys = [];
  93566. animationRotationKeys.push({
  93567. frame: 0,
  93568. value: this.currentVRCamera.rotationQuaternion
  93569. });
  93570. animationRotationKeys.push({
  93571. frame: 6,
  93572. value: target
  93573. });
  93574. animationRotation.setKeys(animationRotationKeys);
  93575. animationRotation.setEasingFunction(this._circleEase);
  93576. this.currentVRCamera.animations.push(animationRotation);
  93577. this._postProcessMove.animations = [];
  93578. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93579. var vignetteWeightKeys = [];
  93580. vignetteWeightKeys.push({
  93581. frame: 0,
  93582. value: 0
  93583. });
  93584. vignetteWeightKeys.push({
  93585. frame: 3,
  93586. value: 4
  93587. });
  93588. vignetteWeightKeys.push({
  93589. frame: 6,
  93590. value: 0
  93591. });
  93592. animationPP.setKeys(vignetteWeightKeys);
  93593. animationPP.setEasingFunction(this._circleEase);
  93594. this._postProcessMove.animations.push(animationPP);
  93595. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93596. var vignetteStretchKeys = [];
  93597. vignetteStretchKeys.push({
  93598. frame: 0,
  93599. value: 0
  93600. });
  93601. vignetteStretchKeys.push({
  93602. frame: 3,
  93603. value: 10
  93604. });
  93605. vignetteStretchKeys.push({
  93606. frame: 6,
  93607. value: 0
  93608. });
  93609. animationPP2.setKeys(vignetteStretchKeys);
  93610. animationPP2.setEasingFunction(this._circleEase);
  93611. this._postProcessMove.animations.push(animationPP2);
  93612. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93613. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93614. this._postProcessMove.samples = 4;
  93615. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93616. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93617. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93618. });
  93619. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93620. };
  93621. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93622. if (hit.pickedPoint) {
  93623. if (gazer._teleportationRequestInitiated) {
  93624. this._displayTeleportationTarget();
  93625. this._haloCenter.copyFrom(hit.pickedPoint);
  93626. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93627. }
  93628. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93629. if (pickNormal) {
  93630. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93631. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93632. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93633. }
  93634. this._teleportationTarget.position.y += 0.1;
  93635. }
  93636. };
  93637. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93638. var _this = this;
  93639. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93640. return;
  93641. }
  93642. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93643. // offset of the headset from the anchor.
  93644. if (this.webVRCamera.leftCamera) {
  93645. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93646. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93647. location.subtractToRef(this._workingVector, this._workingVector);
  93648. }
  93649. else {
  93650. this._workingVector.copyFrom(location);
  93651. }
  93652. // Add height to account for user's height offset
  93653. if (this.isInVRMode) {
  93654. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93655. }
  93656. else {
  93657. this._workingVector.y += this._defaultHeight;
  93658. }
  93659. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93660. // Create animation from the camera's position to the new location
  93661. this.currentVRCamera.animations = [];
  93662. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93663. var animationCameraTeleportationKeys = [{
  93664. frame: 0,
  93665. value: this.currentVRCamera.position
  93666. },
  93667. {
  93668. frame: 11,
  93669. value: this._workingVector
  93670. }
  93671. ];
  93672. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93673. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93674. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93675. this._postProcessMove.animations = [];
  93676. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93677. var vignetteWeightKeys = [];
  93678. vignetteWeightKeys.push({
  93679. frame: 0,
  93680. value: 0
  93681. });
  93682. vignetteWeightKeys.push({
  93683. frame: 5,
  93684. value: 8
  93685. });
  93686. vignetteWeightKeys.push({
  93687. frame: 11,
  93688. value: 0
  93689. });
  93690. animationPP.setKeys(vignetteWeightKeys);
  93691. this._postProcessMove.animations.push(animationPP);
  93692. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93693. var vignetteStretchKeys = [];
  93694. vignetteStretchKeys.push({
  93695. frame: 0,
  93696. value: 0
  93697. });
  93698. vignetteStretchKeys.push({
  93699. frame: 5,
  93700. value: 10
  93701. });
  93702. vignetteStretchKeys.push({
  93703. frame: 11,
  93704. value: 0
  93705. });
  93706. animationPP2.setKeys(vignetteStretchKeys);
  93707. this._postProcessMove.animations.push(animationPP2);
  93708. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93709. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93710. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93711. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93712. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93713. });
  93714. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93715. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93716. });
  93717. this._hideTeleportationTarget();
  93718. };
  93719. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93720. if (normal) {
  93721. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93722. if (angle < Math.PI / 2) {
  93723. normal.scaleInPlace(-1);
  93724. }
  93725. }
  93726. return normal;
  93727. };
  93728. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93729. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93730. return;
  93731. }
  93732. var ray = gazer._getForwardRay(this._rayLength);
  93733. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93734. if (hit) {
  93735. // Populate the contrllers mesh that can be used for drag/drop
  93736. if (gazer._laserPointer) {
  93737. hit.originMesh = gazer._laserPointer.parent;
  93738. }
  93739. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93740. }
  93741. gazer._currentHit = hit;
  93742. // Moving the gazeTracker on the mesh face targetted
  93743. if (hit && hit.pickedPoint) {
  93744. if (this._displayGaze) {
  93745. var multiplier = 1;
  93746. gazer._gazeTracker.isVisible = true;
  93747. if (gazer._isActionableMesh) {
  93748. multiplier = 3;
  93749. }
  93750. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93751. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93752. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93753. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93754. // To avoid z-fighting
  93755. var deltaFighting = 0.002;
  93756. if (pickNormal) {
  93757. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93758. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93759. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93760. }
  93761. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93762. if (gazer._gazeTracker.position.x < 0) {
  93763. gazer._gazeTracker.position.x += deltaFighting;
  93764. }
  93765. else {
  93766. gazer._gazeTracker.position.x -= deltaFighting;
  93767. }
  93768. if (gazer._gazeTracker.position.y < 0) {
  93769. gazer._gazeTracker.position.y += deltaFighting;
  93770. }
  93771. else {
  93772. gazer._gazeTracker.position.y -= deltaFighting;
  93773. }
  93774. if (gazer._gazeTracker.position.z < 0) {
  93775. gazer._gazeTracker.position.z += deltaFighting;
  93776. }
  93777. else {
  93778. gazer._gazeTracker.position.z -= deltaFighting;
  93779. }
  93780. }
  93781. // Changing the size of the laser pointer based on the distance from the targetted point
  93782. gazer._updatePointerDistance(hit.distance);
  93783. }
  93784. else {
  93785. gazer._updatePointerDistance();
  93786. gazer._gazeTracker.isVisible = false;
  93787. }
  93788. if (hit && hit.pickedMesh) {
  93789. // The object selected is the floor, we're in a teleportation scenario
  93790. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93791. // Moving the teleportation area to this targetted point
  93792. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93793. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93794. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93795. }
  93796. gazer._currentMeshSelected = null;
  93797. if (gazer._teleportationRequestInitiated) {
  93798. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93799. }
  93800. return;
  93801. }
  93802. // If not, we're in a selection scenario
  93803. //this._teleportationAllowed = false;
  93804. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93805. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93806. this.onNewMeshPicked.notifyObservers(hit);
  93807. gazer._currentMeshSelected = hit.pickedMesh;
  93808. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93809. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93810. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93811. gazer._isActionableMesh = true;
  93812. }
  93813. else {
  93814. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93815. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93816. gazer._isActionableMesh = false;
  93817. }
  93818. try {
  93819. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93820. }
  93821. catch (err) {
  93822. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93823. }
  93824. }
  93825. else {
  93826. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93827. gazer._currentMeshSelected = null;
  93828. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93829. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93830. }
  93831. }
  93832. }
  93833. else {
  93834. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93835. gazer._currentMeshSelected = null;
  93836. //this._teleportationAllowed = false;
  93837. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93838. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93839. }
  93840. };
  93841. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93842. if (mesh) {
  93843. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93844. }
  93845. };
  93846. /**
  93847. * Sets the color of the laser ray from the vr controllers.
  93848. * @param color new color for the ray.
  93849. */
  93850. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93851. if (this.leftController) {
  93852. this.leftController._setLaserPointerColor(color);
  93853. }
  93854. if (this.rightController) {
  93855. this.rightController._setLaserPointerColor(color);
  93856. }
  93857. };
  93858. /**
  93859. * Sets the color of the ray from the vr headsets gaze.
  93860. * @param color new color for the ray.
  93861. */
  93862. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93863. if (!this._cameraGazer._gazeTracker.material) {
  93864. return;
  93865. }
  93866. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93867. if (this.leftController) {
  93868. this.leftController._gazeTracker.material.emissiveColor = color;
  93869. }
  93870. if (this.rightController) {
  93871. this.rightController._gazeTracker.material.emissiveColor = color;
  93872. }
  93873. };
  93874. /**
  93875. * Exits VR and disposes of the vr experience helper
  93876. */
  93877. VRExperienceHelper.prototype.dispose = function () {
  93878. if (this.isInVRMode) {
  93879. this.exitVR();
  93880. }
  93881. if (this._postProcessMove) {
  93882. this._postProcessMove.dispose();
  93883. }
  93884. if (this._webVRCamera) {
  93885. this._webVRCamera.dispose();
  93886. }
  93887. if (this._vrDeviceOrientationCamera) {
  93888. this._vrDeviceOrientationCamera.dispose();
  93889. }
  93890. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93891. document.body.removeChild(this._btnVR);
  93892. }
  93893. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93894. this._deviceOrientationCamera.dispose();
  93895. }
  93896. if (this._cameraGazer) {
  93897. this._cameraGazer.dispose();
  93898. }
  93899. if (this.leftController) {
  93900. this.leftController.dispose();
  93901. }
  93902. if (this.rightController) {
  93903. this.rightController.dispose();
  93904. }
  93905. if (this._teleportationTarget) {
  93906. this._teleportationTarget.dispose();
  93907. }
  93908. this._floorMeshesCollection = [];
  93909. document.removeEventListener("keydown", this._onKeyDown);
  93910. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93911. window.removeEventListener("resize", this._onResize);
  93912. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93913. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93914. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93915. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93916. document.onmsfullscreenchange = null;
  93917. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93918. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93919. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93920. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93921. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93922. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93923. this._scene.unregisterBeforeRender(this.beforeRender);
  93924. };
  93925. /**
  93926. * Gets the name of the VRExperienceHelper class
  93927. * @returns "VRExperienceHelper"
  93928. */
  93929. VRExperienceHelper.prototype.getClassName = function () {
  93930. return "VRExperienceHelper";
  93931. };
  93932. return VRExperienceHelper;
  93933. }());
  93934. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93935. })(BABYLON || (BABYLON = {}));
  93936. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93937. // Mainly based on these 2 articles :
  93938. // 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
  93939. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93940. var BABYLON;
  93941. (function (BABYLON) {
  93942. /**
  93943. * Defines the potential axis of a Joystick
  93944. */
  93945. var JoystickAxis;
  93946. (function (JoystickAxis) {
  93947. /** X axis */
  93948. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93949. /** Y axis */
  93950. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93951. /** Z axis */
  93952. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93953. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93954. /**
  93955. * Class used to define virtual joystick (used in touch mode)
  93956. */
  93957. var VirtualJoystick = /** @class */ (function () {
  93958. /**
  93959. * Creates a new virtual joystick
  93960. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93961. */
  93962. function VirtualJoystick(leftJoystick) {
  93963. var _this = this;
  93964. if (leftJoystick) {
  93965. this._leftJoystick = true;
  93966. }
  93967. else {
  93968. this._leftJoystick = false;
  93969. }
  93970. VirtualJoystick._globalJoystickIndex++;
  93971. // By default left & right arrow keys are moving the X
  93972. // and up & down keys are moving the Y
  93973. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93974. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93975. this.reverseLeftRight = false;
  93976. this.reverseUpDown = false;
  93977. // collections of pointers
  93978. this._touches = new BABYLON.StringDictionary();
  93979. this.deltaPosition = BABYLON.Vector3.Zero();
  93980. this._joystickSensibility = 25;
  93981. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93982. this._onResize = function (evt) {
  93983. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93984. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93985. if (VirtualJoystick.vjCanvas) {
  93986. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93987. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93988. }
  93989. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93990. };
  93991. // injecting a canvas element on top of the canvas 3D game
  93992. if (!VirtualJoystick.vjCanvas) {
  93993. window.addEventListener("resize", this._onResize, false);
  93994. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93995. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93996. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93997. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93998. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93999. VirtualJoystick.vjCanvas.style.width = "100%";
  94000. VirtualJoystick.vjCanvas.style.height = "100%";
  94001. VirtualJoystick.vjCanvas.style.position = "absolute";
  94002. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94003. VirtualJoystick.vjCanvas.style.top = "0px";
  94004. VirtualJoystick.vjCanvas.style.left = "0px";
  94005. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94006. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94007. // Support for jQuery PEP polyfill
  94008. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94009. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94010. if (!context) {
  94011. throw new Error("Unable to create canvas for virtual joystick");
  94012. }
  94013. VirtualJoystick.vjCanvasContext = context;
  94014. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94015. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94016. document.body.appendChild(VirtualJoystick.vjCanvas);
  94017. }
  94018. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94019. this.pressed = false;
  94020. // default joystick color
  94021. this._joystickColor = "cyan";
  94022. this._joystickPointerID = -1;
  94023. // current joystick position
  94024. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94025. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94026. // origin joystick position
  94027. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94028. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94029. this._onPointerDownHandlerRef = function (evt) {
  94030. _this._onPointerDown(evt);
  94031. };
  94032. this._onPointerMoveHandlerRef = function (evt) {
  94033. _this._onPointerMove(evt);
  94034. };
  94035. this._onPointerUpHandlerRef = function (evt) {
  94036. _this._onPointerUp(evt);
  94037. };
  94038. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94039. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94040. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94041. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94042. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94043. evt.preventDefault(); // Disables system menu
  94044. }, false);
  94045. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94046. }
  94047. /**
  94048. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94049. * @param newJoystickSensibility defines the new sensibility
  94050. */
  94051. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94052. this._joystickSensibility = newJoystickSensibility;
  94053. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94054. };
  94055. VirtualJoystick.prototype._onPointerDown = function (e) {
  94056. var positionOnScreenCondition;
  94057. e.preventDefault();
  94058. if (this._leftJoystick === true) {
  94059. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94060. }
  94061. else {
  94062. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94063. }
  94064. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94065. // First contact will be dedicated to the virtual joystick
  94066. this._joystickPointerID = e.pointerId;
  94067. this._joystickPointerStartPos.x = e.clientX;
  94068. this._joystickPointerStartPos.y = e.clientY;
  94069. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94070. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94071. this._deltaJoystickVector.x = 0;
  94072. this._deltaJoystickVector.y = 0;
  94073. this.pressed = true;
  94074. this._touches.add(e.pointerId.toString(), e);
  94075. }
  94076. else {
  94077. // You can only trigger the action buttons with a joystick declared
  94078. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94079. this._action();
  94080. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94081. }
  94082. }
  94083. };
  94084. VirtualJoystick.prototype._onPointerMove = function (e) {
  94085. // If the current pointer is the one associated to the joystick (first touch contact)
  94086. if (this._joystickPointerID == e.pointerId) {
  94087. this._joystickPointerPos.x = e.clientX;
  94088. this._joystickPointerPos.y = e.clientY;
  94089. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94090. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94091. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94092. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94093. switch (this._axisTargetedByLeftAndRight) {
  94094. case JoystickAxis.X:
  94095. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94096. break;
  94097. case JoystickAxis.Y:
  94098. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94099. break;
  94100. case JoystickAxis.Z:
  94101. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94102. break;
  94103. }
  94104. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94105. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94106. switch (this._axisTargetedByUpAndDown) {
  94107. case JoystickAxis.X:
  94108. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94109. break;
  94110. case JoystickAxis.Y:
  94111. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94112. break;
  94113. case JoystickAxis.Z:
  94114. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94115. break;
  94116. }
  94117. }
  94118. else {
  94119. var data = this._touches.get(e.pointerId.toString());
  94120. if (data) {
  94121. data.x = e.clientX;
  94122. data.y = e.clientY;
  94123. }
  94124. }
  94125. };
  94126. VirtualJoystick.prototype._onPointerUp = function (e) {
  94127. if (this._joystickPointerID == e.pointerId) {
  94128. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94129. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94130. this._joystickPointerID = -1;
  94131. this.pressed = false;
  94132. }
  94133. else {
  94134. var touch = this._touches.get(e.pointerId.toString());
  94135. if (touch) {
  94136. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94137. }
  94138. }
  94139. this._deltaJoystickVector.x = 0;
  94140. this._deltaJoystickVector.y = 0;
  94141. this._touches.remove(e.pointerId.toString());
  94142. };
  94143. /**
  94144. * Change the color of the virtual joystick
  94145. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94146. */
  94147. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94148. this._joystickColor = newColor;
  94149. };
  94150. /**
  94151. * Defines a callback to call when the joystick is touched
  94152. * @param action defines the callback
  94153. */
  94154. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94155. this._action = action;
  94156. };
  94157. /**
  94158. * Defines which axis you'd like to control for left & right
  94159. * @param axis defines the axis to use
  94160. */
  94161. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94162. switch (axis) {
  94163. case JoystickAxis.X:
  94164. case JoystickAxis.Y:
  94165. case JoystickAxis.Z:
  94166. this._axisTargetedByLeftAndRight = axis;
  94167. break;
  94168. default:
  94169. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94170. break;
  94171. }
  94172. };
  94173. /**
  94174. * Defines which axis you'd like to control for up & down
  94175. * @param axis defines the axis to use
  94176. */
  94177. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  94178. switch (axis) {
  94179. case JoystickAxis.X:
  94180. case JoystickAxis.Y:
  94181. case JoystickAxis.Z:
  94182. this._axisTargetedByUpAndDown = axis;
  94183. break;
  94184. default:
  94185. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94186. break;
  94187. }
  94188. };
  94189. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  94190. var _this = this;
  94191. if (this.pressed) {
  94192. this._touches.forEach(function (key, touch) {
  94193. if (touch.pointerId === _this._joystickPointerID) {
  94194. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  94195. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  94196. VirtualJoystick.vjCanvasContext.beginPath();
  94197. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94198. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94199. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  94200. VirtualJoystick.vjCanvasContext.stroke();
  94201. VirtualJoystick.vjCanvasContext.closePath();
  94202. VirtualJoystick.vjCanvasContext.beginPath();
  94203. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94204. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94205. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  94206. VirtualJoystick.vjCanvasContext.stroke();
  94207. VirtualJoystick.vjCanvasContext.closePath();
  94208. VirtualJoystick.vjCanvasContext.beginPath();
  94209. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94210. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  94211. VirtualJoystick.vjCanvasContext.stroke();
  94212. VirtualJoystick.vjCanvasContext.closePath();
  94213. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  94214. }
  94215. else {
  94216. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94217. VirtualJoystick.vjCanvasContext.beginPath();
  94218. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  94219. VirtualJoystick.vjCanvasContext.beginPath();
  94220. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  94221. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94222. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  94223. VirtualJoystick.vjCanvasContext.stroke();
  94224. VirtualJoystick.vjCanvasContext.closePath();
  94225. touch.prevX = touch.x;
  94226. touch.prevY = touch.y;
  94227. }
  94228. ;
  94229. });
  94230. }
  94231. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94232. };
  94233. /**
  94234. * Release internal HTML canvas
  94235. */
  94236. VirtualJoystick.prototype.releaseCanvas = function () {
  94237. if (VirtualJoystick.vjCanvas) {
  94238. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  94239. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  94240. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  94241. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94242. window.removeEventListener("resize", this._onResize);
  94243. document.body.removeChild(VirtualJoystick.vjCanvas);
  94244. VirtualJoystick.vjCanvas = null;
  94245. }
  94246. };
  94247. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94248. VirtualJoystick._globalJoystickIndex = 0;
  94249. return VirtualJoystick;
  94250. }());
  94251. BABYLON.VirtualJoystick = VirtualJoystick;
  94252. })(BABYLON || (BABYLON = {}));
  94253. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94254. var BABYLON;
  94255. (function (BABYLON) {
  94256. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  94257. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  94258. });
  94259. // We're mainly based on the logic defined into the FreeCamera code
  94260. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94261. __extends(VirtualJoysticksCamera, _super);
  94262. function VirtualJoysticksCamera(name, position, scene) {
  94263. var _this = _super.call(this, name, position, scene) || this;
  94264. _this.inputs.addVirtualJoystick();
  94265. return _this;
  94266. }
  94267. VirtualJoysticksCamera.prototype.getClassName = function () {
  94268. return "VirtualJoysticksCamera";
  94269. };
  94270. return VirtualJoysticksCamera;
  94271. }(BABYLON.FreeCamera));
  94272. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94273. })(BABYLON || (BABYLON = {}));
  94274. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94275. var BABYLON;
  94276. (function (BABYLON) {
  94277. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94278. function FreeCameraVirtualJoystickInput() {
  94279. }
  94280. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94281. return this._leftjoystick;
  94282. };
  94283. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94284. return this._rightjoystick;
  94285. };
  94286. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94287. if (this._leftjoystick) {
  94288. var camera = this.camera;
  94289. var speed = camera._computeLocalCameraSpeed() * 50;
  94290. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94291. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94292. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94293. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94294. if (!this._leftjoystick.pressed) {
  94295. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94296. }
  94297. if (!this._rightjoystick.pressed) {
  94298. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94299. }
  94300. }
  94301. };
  94302. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94303. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94304. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94305. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94306. this._leftjoystick.setJoystickSensibility(0.15);
  94307. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94308. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94309. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94310. this._rightjoystick.reverseUpDown = true;
  94311. this._rightjoystick.setJoystickSensibility(0.05);
  94312. this._rightjoystick.setJoystickColor("yellow");
  94313. };
  94314. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94315. this._leftjoystick.releaseCanvas();
  94316. this._rightjoystick.releaseCanvas();
  94317. };
  94318. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94319. return "FreeCameraVirtualJoystickInput";
  94320. };
  94321. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94322. return "virtualJoystick";
  94323. };
  94324. return FreeCameraVirtualJoystickInput;
  94325. }());
  94326. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94327. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94328. })(BABYLON || (BABYLON = {}));
  94329. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94330. var BABYLON;
  94331. (function (BABYLON) {
  94332. var SimplificationSettings = /** @class */ (function () {
  94333. function SimplificationSettings(quality, distance, optimizeMesh) {
  94334. this.quality = quality;
  94335. this.distance = distance;
  94336. this.optimizeMesh = optimizeMesh;
  94337. }
  94338. return SimplificationSettings;
  94339. }());
  94340. BABYLON.SimplificationSettings = SimplificationSettings;
  94341. var SimplificationQueue = /** @class */ (function () {
  94342. function SimplificationQueue() {
  94343. this.running = false;
  94344. this._simplificationArray = [];
  94345. }
  94346. SimplificationQueue.prototype.addTask = function (task) {
  94347. this._simplificationArray.push(task);
  94348. };
  94349. SimplificationQueue.prototype.executeNext = function () {
  94350. var task = this._simplificationArray.pop();
  94351. if (task) {
  94352. this.running = true;
  94353. this.runSimplification(task);
  94354. }
  94355. else {
  94356. this.running = false;
  94357. }
  94358. };
  94359. SimplificationQueue.prototype.runSimplification = function (task) {
  94360. var _this = this;
  94361. if (task.parallelProcessing) {
  94362. //parallel simplifier
  94363. task.settings.forEach(function (setting) {
  94364. var simplifier = _this.getSimplifier(task);
  94365. simplifier.simplify(setting, function (newMesh) {
  94366. task.mesh.addLODLevel(setting.distance, newMesh);
  94367. newMesh.isVisible = true;
  94368. //check if it is the last
  94369. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94370. //all done, run the success callback.
  94371. task.successCallback();
  94372. }
  94373. _this.executeNext();
  94374. });
  94375. });
  94376. }
  94377. else {
  94378. //single simplifier.
  94379. var simplifier = this.getSimplifier(task);
  94380. var runDecimation = function (setting, callback) {
  94381. simplifier.simplify(setting, function (newMesh) {
  94382. task.mesh.addLODLevel(setting.distance, newMesh);
  94383. newMesh.isVisible = true;
  94384. //run the next quality level
  94385. callback();
  94386. });
  94387. };
  94388. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94389. runDecimation(task.settings[loop.index], function () {
  94390. loop.executeNext();
  94391. });
  94392. }, function () {
  94393. //execution ended, run the success callback.
  94394. if (task.successCallback) {
  94395. task.successCallback();
  94396. }
  94397. _this.executeNext();
  94398. });
  94399. }
  94400. };
  94401. SimplificationQueue.prototype.getSimplifier = function (task) {
  94402. switch (task.simplificationType) {
  94403. case SimplificationType.QUADRATIC:
  94404. default:
  94405. return new QuadraticErrorSimplification(task.mesh);
  94406. }
  94407. };
  94408. return SimplificationQueue;
  94409. }());
  94410. BABYLON.SimplificationQueue = SimplificationQueue;
  94411. /**
  94412. * The implemented types of simplification
  94413. * At the moment only Quadratic Error Decimation is implemented
  94414. */
  94415. var SimplificationType;
  94416. (function (SimplificationType) {
  94417. /** Quadratic error decimation */
  94418. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94419. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94420. var DecimationTriangle = /** @class */ (function () {
  94421. function DecimationTriangle(vertices) {
  94422. this.vertices = vertices;
  94423. this.error = new Array(4);
  94424. this.deleted = false;
  94425. this.isDirty = false;
  94426. this.deletePending = false;
  94427. this.borderFactor = 0;
  94428. }
  94429. return DecimationTriangle;
  94430. }());
  94431. BABYLON.DecimationTriangle = DecimationTriangle;
  94432. var DecimationVertex = /** @class */ (function () {
  94433. function DecimationVertex(position, id) {
  94434. this.position = position;
  94435. this.id = id;
  94436. this.isBorder = true;
  94437. this.q = new QuadraticMatrix();
  94438. this.triangleCount = 0;
  94439. this.triangleStart = 0;
  94440. this.originalOffsets = [];
  94441. }
  94442. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94443. this.position.copyFrom(newPosition);
  94444. };
  94445. return DecimationVertex;
  94446. }());
  94447. BABYLON.DecimationVertex = DecimationVertex;
  94448. var QuadraticMatrix = /** @class */ (function () {
  94449. function QuadraticMatrix(data) {
  94450. this.data = new Array(10);
  94451. for (var i = 0; i < 10; ++i) {
  94452. if (data && data[i]) {
  94453. this.data[i] = data[i];
  94454. }
  94455. else {
  94456. this.data[i] = 0;
  94457. }
  94458. }
  94459. }
  94460. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94461. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94462. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94463. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94464. return det;
  94465. };
  94466. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94467. for (var i = 0; i < 10; ++i) {
  94468. this.data[i] += matrix.data[i];
  94469. }
  94470. };
  94471. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94472. for (var i = 0; i < 10; ++i) {
  94473. this.data[i] += data[i];
  94474. }
  94475. };
  94476. QuadraticMatrix.prototype.add = function (matrix) {
  94477. var m = new QuadraticMatrix();
  94478. for (var i = 0; i < 10; ++i) {
  94479. m.data[i] = this.data[i] + matrix.data[i];
  94480. }
  94481. return m;
  94482. };
  94483. QuadraticMatrix.FromData = function (a, b, c, d) {
  94484. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94485. };
  94486. //returning an array to avoid garbage collection
  94487. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94488. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94489. };
  94490. return QuadraticMatrix;
  94491. }());
  94492. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94493. var Reference = /** @class */ (function () {
  94494. function Reference(vertexId, triangleId) {
  94495. this.vertexId = vertexId;
  94496. this.triangleId = triangleId;
  94497. }
  94498. return Reference;
  94499. }());
  94500. BABYLON.Reference = Reference;
  94501. /**
  94502. * An implementation of the Quadratic Error simplification algorithm.
  94503. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94504. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94505. * @author RaananW
  94506. */
  94507. var QuadraticErrorSimplification = /** @class */ (function () {
  94508. function QuadraticErrorSimplification(_mesh) {
  94509. this._mesh = _mesh;
  94510. this.syncIterations = 5000;
  94511. this.aggressiveness = 7;
  94512. this.decimationIterations = 100;
  94513. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94514. }
  94515. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94516. var _this = this;
  94517. this.initDecimatedMesh();
  94518. //iterating through the submeshes array, one after the other.
  94519. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94520. _this.initWithMesh(loop.index, function () {
  94521. _this.runDecimation(settings, loop.index, function () {
  94522. loop.executeNext();
  94523. });
  94524. }, settings.optimizeMesh);
  94525. }, function () {
  94526. setTimeout(function () {
  94527. successCallback(_this._reconstructedMesh);
  94528. }, 0);
  94529. });
  94530. };
  94531. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94532. var _this = this;
  94533. var targetCount = ~~(this.triangles.length * settings.quality);
  94534. var deletedTriangles = 0;
  94535. var triangleCount = this.triangles.length;
  94536. var iterationFunction = function (iteration, callback) {
  94537. setTimeout(function () {
  94538. if (iteration % 5 === 0) {
  94539. _this.updateMesh(iteration === 0);
  94540. }
  94541. for (var i = 0; i < _this.triangles.length; ++i) {
  94542. _this.triangles[i].isDirty = false;
  94543. }
  94544. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94545. var trianglesIterator = function (i) {
  94546. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94547. var t = _this.triangles[tIdx];
  94548. if (!t)
  94549. return;
  94550. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94551. return;
  94552. }
  94553. for (var j = 0; j < 3; ++j) {
  94554. if (t.error[j] < threshold) {
  94555. var deleted0 = [];
  94556. var deleted1 = [];
  94557. var v0 = t.vertices[j];
  94558. var v1 = t.vertices[(j + 1) % 3];
  94559. if (v0.isBorder || v1.isBorder)
  94560. continue;
  94561. var p = BABYLON.Vector3.Zero();
  94562. var n = BABYLON.Vector3.Zero();
  94563. var uv = BABYLON.Vector2.Zero();
  94564. var color = new BABYLON.Color4(0, 0, 0, 1);
  94565. _this.calculateError(v0, v1, p, n, uv, color);
  94566. var delTr = new Array();
  94567. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94568. continue;
  94569. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94570. continue;
  94571. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94572. continue;
  94573. var uniqueArray = new Array();
  94574. delTr.forEach(function (deletedT) {
  94575. if (uniqueArray.indexOf(deletedT) === -1) {
  94576. deletedT.deletePending = true;
  94577. uniqueArray.push(deletedT);
  94578. }
  94579. });
  94580. if (uniqueArray.length % 2 !== 0) {
  94581. continue;
  94582. }
  94583. v0.q = v1.q.add(v0.q);
  94584. v0.updatePosition(p);
  94585. var tStart = _this.references.length;
  94586. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94587. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94588. var tCount = _this.references.length - tStart;
  94589. if (tCount <= v0.triangleCount) {
  94590. if (tCount) {
  94591. for (var c = 0; c < tCount; c++) {
  94592. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94593. }
  94594. }
  94595. }
  94596. else {
  94597. v0.triangleStart = tStart;
  94598. }
  94599. v0.triangleCount = tCount;
  94600. break;
  94601. }
  94602. }
  94603. };
  94604. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94605. }, 0);
  94606. };
  94607. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94608. if (triangleCount - deletedTriangles <= targetCount)
  94609. loop.breakLoop();
  94610. else {
  94611. iterationFunction(loop.index, function () {
  94612. loop.executeNext();
  94613. });
  94614. }
  94615. }, function () {
  94616. setTimeout(function () {
  94617. //reconstruct this part of the mesh
  94618. _this.reconstructMesh(submeshIndex);
  94619. successCallback();
  94620. }, 0);
  94621. });
  94622. };
  94623. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94624. var _this = this;
  94625. this.vertices = [];
  94626. this.triangles = [];
  94627. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94628. var indices = this._mesh.getIndices();
  94629. var submesh = this._mesh.subMeshes[submeshIndex];
  94630. var findInVertices = function (positionToSearch) {
  94631. if (optimizeMesh) {
  94632. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94633. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94634. return _this.vertices[ii];
  94635. }
  94636. }
  94637. }
  94638. return null;
  94639. };
  94640. var vertexReferences = [];
  94641. var vertexInit = function (i) {
  94642. if (!positionData) {
  94643. return;
  94644. }
  94645. var offset = i + submesh.verticesStart;
  94646. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94647. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94648. vertex.originalOffsets.push(offset);
  94649. if (vertex.id === _this.vertices.length) {
  94650. _this.vertices.push(vertex);
  94651. }
  94652. vertexReferences.push(vertex.id);
  94653. };
  94654. //var totalVertices = mesh.getTotalVertices();
  94655. var totalVertices = submesh.verticesCount;
  94656. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94657. var indicesInit = function (i) {
  94658. if (!indices) {
  94659. return;
  94660. }
  94661. var offset = (submesh.indexStart / 3) + i;
  94662. var pos = (offset * 3);
  94663. var i0 = indices[pos + 0];
  94664. var i1 = indices[pos + 1];
  94665. var i2 = indices[pos + 2];
  94666. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94667. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94668. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94669. var triangle = new DecimationTriangle([v0, v1, v2]);
  94670. triangle.originalOffset = pos;
  94671. _this.triangles.push(triangle);
  94672. };
  94673. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94674. _this.init(callback);
  94675. });
  94676. });
  94677. };
  94678. QuadraticErrorSimplification.prototype.init = function (callback) {
  94679. var _this = this;
  94680. var triangleInit1 = function (i) {
  94681. var t = _this.triangles[i];
  94682. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94683. for (var j = 0; j < 3; j++) {
  94684. 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))));
  94685. }
  94686. };
  94687. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94688. var triangleInit2 = function (i) {
  94689. var t = _this.triangles[i];
  94690. for (var j = 0; j < 3; ++j) {
  94691. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94692. }
  94693. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94694. };
  94695. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94696. callback();
  94697. });
  94698. });
  94699. };
  94700. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94701. var newTriangles = [];
  94702. var i;
  94703. for (i = 0; i < this.vertices.length; ++i) {
  94704. this.vertices[i].triangleCount = 0;
  94705. }
  94706. var t;
  94707. var j;
  94708. for (i = 0; i < this.triangles.length; ++i) {
  94709. if (!this.triangles[i].deleted) {
  94710. t = this.triangles[i];
  94711. for (j = 0; j < 3; ++j) {
  94712. t.vertices[j].triangleCount = 1;
  94713. }
  94714. newTriangles.push(t);
  94715. }
  94716. }
  94717. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94718. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94719. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94720. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94721. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94722. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94723. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94724. var vertexCount = 0;
  94725. for (i = 0; i < this.vertices.length; ++i) {
  94726. var vertex = this.vertices[i];
  94727. vertex.id = vertexCount;
  94728. if (vertex.triangleCount) {
  94729. vertex.originalOffsets.forEach(function (originalOffset) {
  94730. if (!normalData) {
  94731. return;
  94732. }
  94733. newPositionData.push(vertex.position.x);
  94734. newPositionData.push(vertex.position.y);
  94735. newPositionData.push(vertex.position.z);
  94736. newNormalData.push(normalData[originalOffset * 3]);
  94737. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94738. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94739. if (uvs && uvs.length) {
  94740. newUVsData.push(uvs[(originalOffset * 2)]);
  94741. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94742. }
  94743. else if (colorsData && colorsData.length) {
  94744. newColorsData.push(colorsData[(originalOffset * 4)]);
  94745. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94746. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94747. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94748. }
  94749. ++vertexCount;
  94750. });
  94751. }
  94752. }
  94753. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94754. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94755. var submeshesArray = this._reconstructedMesh.subMeshes;
  94756. this._reconstructedMesh.subMeshes = [];
  94757. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94758. var originalIndices = this._mesh.getIndices();
  94759. for (i = 0; i < newTriangles.length; ++i) {
  94760. t = newTriangles[i]; //now get the new referencing point for each vertex
  94761. [0, 1, 2].forEach(function (idx) {
  94762. var id = originalIndices[t.originalOffset + idx];
  94763. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94764. if (offset < 0)
  94765. offset = 0;
  94766. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94767. });
  94768. }
  94769. //overwriting the old vertex buffers and indices.
  94770. this._reconstructedMesh.setIndices(newIndicesArray);
  94771. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94772. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94773. if (newUVsData.length > 0)
  94774. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94775. if (newColorsData.length > 0)
  94776. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94777. //create submesh
  94778. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94779. if (submeshIndex > 0) {
  94780. this._reconstructedMesh.subMeshes = [];
  94781. submeshesArray.forEach(function (submesh) {
  94782. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94783. });
  94784. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94785. }
  94786. };
  94787. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94788. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94789. this._reconstructedMesh.material = this._mesh.material;
  94790. this._reconstructedMesh.parent = this._mesh.parent;
  94791. this._reconstructedMesh.isVisible = false;
  94792. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94793. };
  94794. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94795. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94796. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94797. if (t.deleted)
  94798. continue;
  94799. var s = this.references[vertex1.triangleStart + i].vertexId;
  94800. var v1 = t.vertices[(s + 1) % 3];
  94801. var v2 = t.vertices[(s + 2) % 3];
  94802. if ((v1 === vertex2 || v2 === vertex2)) {
  94803. deletedArray[i] = true;
  94804. delTr.push(t);
  94805. continue;
  94806. }
  94807. var d1 = v1.position.subtract(point);
  94808. d1 = d1.normalize();
  94809. var d2 = v2.position.subtract(point);
  94810. d2 = d2.normalize();
  94811. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94812. return true;
  94813. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94814. deletedArray[i] = false;
  94815. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94816. return true;
  94817. }
  94818. return false;
  94819. };
  94820. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94821. var newDeleted = deletedTriangles;
  94822. for (var i = 0; i < vertex.triangleCount; ++i) {
  94823. var ref = this.references[vertex.triangleStart + i];
  94824. var t = this.triangles[ref.triangleId];
  94825. if (t.deleted)
  94826. continue;
  94827. if (deletedArray[i] && t.deletePending) {
  94828. t.deleted = true;
  94829. newDeleted++;
  94830. continue;
  94831. }
  94832. t.vertices[ref.vertexId] = origVertex;
  94833. t.isDirty = true;
  94834. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94835. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94836. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94837. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94838. this.references.push(ref);
  94839. }
  94840. return newDeleted;
  94841. };
  94842. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94843. for (var i = 0; i < this.vertices.length; ++i) {
  94844. var vCount = [];
  94845. var vId = [];
  94846. var v = this.vertices[i];
  94847. var j;
  94848. for (j = 0; j < v.triangleCount; ++j) {
  94849. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94850. for (var ii = 0; ii < 3; ii++) {
  94851. var ofs = 0;
  94852. var vv = triangle.vertices[ii];
  94853. while (ofs < vCount.length) {
  94854. if (vId[ofs] === vv.id)
  94855. break;
  94856. ++ofs;
  94857. }
  94858. if (ofs === vCount.length) {
  94859. vCount.push(1);
  94860. vId.push(vv.id);
  94861. }
  94862. else {
  94863. vCount[ofs]++;
  94864. }
  94865. }
  94866. }
  94867. for (j = 0; j < vCount.length; ++j) {
  94868. if (vCount[j] === 1) {
  94869. this.vertices[vId[j]].isBorder = true;
  94870. }
  94871. else {
  94872. this.vertices[vId[j]].isBorder = false;
  94873. }
  94874. }
  94875. }
  94876. };
  94877. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94878. if (identifyBorders === void 0) { identifyBorders = false; }
  94879. var i;
  94880. if (!identifyBorders) {
  94881. var newTrianglesVector = [];
  94882. for (i = 0; i < this.triangles.length; ++i) {
  94883. if (!this.triangles[i].deleted) {
  94884. newTrianglesVector.push(this.triangles[i]);
  94885. }
  94886. }
  94887. this.triangles = newTrianglesVector;
  94888. }
  94889. for (i = 0; i < this.vertices.length; ++i) {
  94890. this.vertices[i].triangleCount = 0;
  94891. this.vertices[i].triangleStart = 0;
  94892. }
  94893. var t;
  94894. var j;
  94895. var v;
  94896. for (i = 0; i < this.triangles.length; ++i) {
  94897. t = this.triangles[i];
  94898. for (j = 0; j < 3; ++j) {
  94899. v = t.vertices[j];
  94900. v.triangleCount++;
  94901. }
  94902. }
  94903. var tStart = 0;
  94904. for (i = 0; i < this.vertices.length; ++i) {
  94905. this.vertices[i].triangleStart = tStart;
  94906. tStart += this.vertices[i].triangleCount;
  94907. this.vertices[i].triangleCount = 0;
  94908. }
  94909. var newReferences = new Array(this.triangles.length * 3);
  94910. for (i = 0; i < this.triangles.length; ++i) {
  94911. t = this.triangles[i];
  94912. for (j = 0; j < 3; ++j) {
  94913. v = t.vertices[j];
  94914. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94915. v.triangleCount++;
  94916. }
  94917. }
  94918. this.references = newReferences;
  94919. if (identifyBorders) {
  94920. this.identifyBorder();
  94921. }
  94922. };
  94923. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94924. var x = point.x;
  94925. var y = point.y;
  94926. var z = point.z;
  94927. 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
  94928. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94929. };
  94930. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94931. var q = vertex1.q.add(vertex2.q);
  94932. var border = vertex1.isBorder && vertex2.isBorder;
  94933. var error = 0;
  94934. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94935. if (qDet !== 0 && !border) {
  94936. if (!pointResult) {
  94937. pointResult = BABYLON.Vector3.Zero();
  94938. }
  94939. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94940. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94941. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94942. error = this.vertexError(q, pointResult);
  94943. }
  94944. else {
  94945. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94946. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94947. var error1 = this.vertexError(q, vertex1.position);
  94948. var error2 = this.vertexError(q, vertex2.position);
  94949. var error3 = this.vertexError(q, p3);
  94950. error = Math.min(error1, error2, error3);
  94951. if (error === error1) {
  94952. if (pointResult) {
  94953. pointResult.copyFrom(vertex1.position);
  94954. }
  94955. }
  94956. else if (error === error2) {
  94957. if (pointResult) {
  94958. pointResult.copyFrom(vertex2.position);
  94959. }
  94960. }
  94961. else {
  94962. if (pointResult) {
  94963. pointResult.copyFrom(p3);
  94964. }
  94965. }
  94966. }
  94967. return error;
  94968. };
  94969. return QuadraticErrorSimplification;
  94970. }());
  94971. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94972. })(BABYLON || (BABYLON = {}));
  94973. //# sourceMappingURL=babylon.meshSimplification.js.map
  94974. var BABYLON;
  94975. (function (BABYLON) {
  94976. var MeshLODLevel = /** @class */ (function () {
  94977. function MeshLODLevel(distance, mesh) {
  94978. this.distance = distance;
  94979. this.mesh = mesh;
  94980. }
  94981. return MeshLODLevel;
  94982. }());
  94983. BABYLON.MeshLODLevel = MeshLODLevel;
  94984. })(BABYLON || (BABYLON = {}));
  94985. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94986. var BABYLON;
  94987. (function (BABYLON) {
  94988. /**
  94989. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94990. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94991. */
  94992. var SceneOptimization = /** @class */ (function () {
  94993. /**
  94994. * Creates the SceneOptimization object
  94995. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94996. * @param desc defines the description associated with the optimization
  94997. */
  94998. function SceneOptimization(
  94999. /**
  95000. * Defines the priority of this optimization (0 by default which means first in the list)
  95001. */
  95002. priority) {
  95003. if (priority === void 0) { priority = 0; }
  95004. this.priority = priority;
  95005. }
  95006. /**
  95007. * Gets a string describing the action executed by the current optimization
  95008. * @returns description string
  95009. */
  95010. SceneOptimization.prototype.getDescription = function () {
  95011. return "";
  95012. };
  95013. /**
  95014. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95015. * @param scene defines the current scene where to apply this optimization
  95016. * @param optimizer defines the current optimizer
  95017. * @returns true if everything that can be done was applied
  95018. */
  95019. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95020. return true;
  95021. };
  95022. ;
  95023. return SceneOptimization;
  95024. }());
  95025. BABYLON.SceneOptimization = SceneOptimization;
  95026. /**
  95027. * Defines an optimization used to reduce the size of render target textures
  95028. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95029. */
  95030. var TextureOptimization = /** @class */ (function (_super) {
  95031. __extends(TextureOptimization, _super);
  95032. /**
  95033. * Creates the TextureOptimization object
  95034. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95035. * @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
  95036. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95037. */
  95038. function TextureOptimization(
  95039. /**
  95040. * Defines the priority of this optimization (0 by default which means first in the list)
  95041. */
  95042. priority,
  95043. /**
  95044. * 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
  95045. */
  95046. maximumSize,
  95047. /**
  95048. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95049. */
  95050. step) {
  95051. if (priority === void 0) { priority = 0; }
  95052. if (maximumSize === void 0) { maximumSize = 1024; }
  95053. if (step === void 0) { step = 0.5; }
  95054. var _this = _super.call(this, priority) || this;
  95055. _this.priority = priority;
  95056. _this.maximumSize = maximumSize;
  95057. _this.step = step;
  95058. return _this;
  95059. }
  95060. /**
  95061. * Gets a string describing the action executed by the current optimization
  95062. * @returns description string
  95063. */
  95064. TextureOptimization.prototype.getDescription = function () {
  95065. return "Reducing render target texture size to " + this.maximumSize;
  95066. };
  95067. /**
  95068. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95069. * @param scene defines the current scene where to apply this optimization
  95070. * @param optimizer defines the current optimizer
  95071. * @returns true if everything that can be done was applied
  95072. */
  95073. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95074. var allDone = true;
  95075. for (var index = 0; index < scene.textures.length; index++) {
  95076. var texture = scene.textures[index];
  95077. if (!texture.canRescale || texture.getContext) {
  95078. continue;
  95079. }
  95080. var currentSize = texture.getSize();
  95081. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95082. if (maxDimension > this.maximumSize) {
  95083. texture.scale(this.step);
  95084. allDone = false;
  95085. }
  95086. }
  95087. return allDone;
  95088. };
  95089. return TextureOptimization;
  95090. }(SceneOptimization));
  95091. BABYLON.TextureOptimization = TextureOptimization;
  95092. /**
  95093. * Defines an optimization used to increase or decrease the rendering resolution
  95094. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95095. */
  95096. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95097. __extends(HardwareScalingOptimization, _super);
  95098. /**
  95099. * Creates the HardwareScalingOptimization object
  95100. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95101. * @param maximumScale defines the maximum scale to use (2 by default)
  95102. * @param step defines the step to use between two passes (0.5 by default)
  95103. */
  95104. function HardwareScalingOptimization(
  95105. /**
  95106. * Defines the priority of this optimization (0 by default which means first in the list)
  95107. */
  95108. priority,
  95109. /**
  95110. * Defines the maximum scale to use (2 by default)
  95111. */
  95112. maximumScale,
  95113. /**
  95114. * Defines the step to use between two passes (0.5 by default)
  95115. */
  95116. step) {
  95117. if (priority === void 0) { priority = 0; }
  95118. if (maximumScale === void 0) { maximumScale = 2; }
  95119. if (step === void 0) { step = 0.25; }
  95120. var _this = _super.call(this, priority) || this;
  95121. _this.priority = priority;
  95122. _this.maximumScale = maximumScale;
  95123. _this.step = step;
  95124. _this._currentScale = -1;
  95125. _this._directionOffset = 1;
  95126. return _this;
  95127. }
  95128. /**
  95129. * Gets a string describing the action executed by the current optimization
  95130. * @return description string
  95131. */
  95132. HardwareScalingOptimization.prototype.getDescription = function () {
  95133. return "Setting hardware scaling level to " + this._currentScale;
  95134. };
  95135. /**
  95136. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95137. * @param scene defines the current scene where to apply this optimization
  95138. * @param optimizer defines the current optimizer
  95139. * @returns true if everything that can be done was applied
  95140. */
  95141. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95142. if (this._currentScale === -1) {
  95143. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95144. if (this._currentScale > this.maximumScale) {
  95145. this._directionOffset = -1;
  95146. }
  95147. }
  95148. this._currentScale += this._directionOffset * this.step;
  95149. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95150. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95151. };
  95152. ;
  95153. return HardwareScalingOptimization;
  95154. }(SceneOptimization));
  95155. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95156. /**
  95157. * Defines an optimization used to remove shadows
  95158. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95159. */
  95160. var ShadowsOptimization = /** @class */ (function (_super) {
  95161. __extends(ShadowsOptimization, _super);
  95162. function ShadowsOptimization() {
  95163. return _super !== null && _super.apply(this, arguments) || this;
  95164. }
  95165. /**
  95166. * Gets a string describing the action executed by the current optimization
  95167. * @return description string
  95168. */
  95169. ShadowsOptimization.prototype.getDescription = function () {
  95170. return "Turning shadows on/off";
  95171. };
  95172. /**
  95173. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95174. * @param scene defines the current scene where to apply this optimization
  95175. * @param optimizer defines the current optimizer
  95176. * @returns true if everything that can be done was applied
  95177. */
  95178. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  95179. scene.shadowsEnabled = optimizer.isInImprovementMode;
  95180. return true;
  95181. };
  95182. ;
  95183. return ShadowsOptimization;
  95184. }(SceneOptimization));
  95185. BABYLON.ShadowsOptimization = ShadowsOptimization;
  95186. /**
  95187. * Defines an optimization used to turn post-processes off
  95188. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95189. */
  95190. var PostProcessesOptimization = /** @class */ (function (_super) {
  95191. __extends(PostProcessesOptimization, _super);
  95192. function PostProcessesOptimization() {
  95193. return _super !== null && _super.apply(this, arguments) || this;
  95194. }
  95195. /**
  95196. * Gets a string describing the action executed by the current optimization
  95197. * @return description string
  95198. */
  95199. PostProcessesOptimization.prototype.getDescription = function () {
  95200. return "Turning post-processes on/off";
  95201. };
  95202. /**
  95203. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95204. * @param scene defines the current scene where to apply this optimization
  95205. * @param optimizer defines the current optimizer
  95206. * @returns true if everything that can be done was applied
  95207. */
  95208. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  95209. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  95210. return true;
  95211. };
  95212. ;
  95213. return PostProcessesOptimization;
  95214. }(SceneOptimization));
  95215. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  95216. /**
  95217. * Defines an optimization used to turn lens flares off
  95218. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95219. */
  95220. var LensFlaresOptimization = /** @class */ (function (_super) {
  95221. __extends(LensFlaresOptimization, _super);
  95222. function LensFlaresOptimization() {
  95223. return _super !== null && _super.apply(this, arguments) || this;
  95224. }
  95225. /**
  95226. * Gets a string describing the action executed by the current optimization
  95227. * @return description string
  95228. */
  95229. LensFlaresOptimization.prototype.getDescription = function () {
  95230. return "Turning lens flares on/off";
  95231. };
  95232. /**
  95233. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95234. * @param scene defines the current scene where to apply this optimization
  95235. * @param optimizer defines the current optimizer
  95236. * @returns true if everything that can be done was applied
  95237. */
  95238. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  95239. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  95240. return true;
  95241. };
  95242. ;
  95243. return LensFlaresOptimization;
  95244. }(SceneOptimization));
  95245. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95246. /**
  95247. * Defines an optimization based on user defined callback.
  95248. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95249. */
  95250. var CustomOptimization = /** @class */ (function (_super) {
  95251. __extends(CustomOptimization, _super);
  95252. function CustomOptimization() {
  95253. return _super !== null && _super.apply(this, arguments) || this;
  95254. }
  95255. /**
  95256. * Gets a string describing the action executed by the current optimization
  95257. * @returns description string
  95258. */
  95259. CustomOptimization.prototype.getDescription = function () {
  95260. if (this.onGetDescription) {
  95261. return this.onGetDescription();
  95262. }
  95263. return "Running user defined callback";
  95264. };
  95265. /**
  95266. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95267. * @param scene defines the current scene where to apply this optimization
  95268. * @param optimizer defines the current optimizer
  95269. * @returns true if everything that can be done was applied
  95270. */
  95271. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95272. if (this.onApply) {
  95273. return this.onApply(scene, optimizer);
  95274. }
  95275. return true;
  95276. };
  95277. ;
  95278. return CustomOptimization;
  95279. }(SceneOptimization));
  95280. BABYLON.CustomOptimization = CustomOptimization;
  95281. /**
  95282. * Defines an optimization used to turn particles off
  95283. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95284. */
  95285. var ParticlesOptimization = /** @class */ (function (_super) {
  95286. __extends(ParticlesOptimization, _super);
  95287. function ParticlesOptimization() {
  95288. return _super !== null && _super.apply(this, arguments) || this;
  95289. }
  95290. /**
  95291. * Gets a string describing the action executed by the current optimization
  95292. * @return description string
  95293. */
  95294. ParticlesOptimization.prototype.getDescription = function () {
  95295. return "Turning particles on/off";
  95296. };
  95297. /**
  95298. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95299. * @param scene defines the current scene where to apply this optimization
  95300. * @param optimizer defines the current optimizer
  95301. * @returns true if everything that can be done was applied
  95302. */
  95303. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95304. scene.particlesEnabled = optimizer.isInImprovementMode;
  95305. return true;
  95306. };
  95307. ;
  95308. return ParticlesOptimization;
  95309. }(SceneOptimization));
  95310. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95311. /**
  95312. * Defines an optimization used to turn render targets off
  95313. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95314. */
  95315. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95316. __extends(RenderTargetsOptimization, _super);
  95317. function RenderTargetsOptimization() {
  95318. return _super !== null && _super.apply(this, arguments) || this;
  95319. }
  95320. /**
  95321. * Gets a string describing the action executed by the current optimization
  95322. * @return description string
  95323. */
  95324. RenderTargetsOptimization.prototype.getDescription = function () {
  95325. return "Turning render targets off";
  95326. };
  95327. /**
  95328. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95329. * @param scene defines the current scene where to apply this optimization
  95330. * @param optimizer defines the current optimizer
  95331. * @returns true if everything that can be done was applied
  95332. */
  95333. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95334. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95335. return true;
  95336. };
  95337. ;
  95338. return RenderTargetsOptimization;
  95339. }(SceneOptimization));
  95340. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95341. /**
  95342. * Defines an optimization used to merge meshes with compatible materials
  95343. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95344. */
  95345. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95346. __extends(MergeMeshesOptimization, _super);
  95347. function MergeMeshesOptimization() {
  95348. var _this = _super !== null && _super.apply(this, arguments) || this;
  95349. _this._canBeMerged = function (abstractMesh) {
  95350. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95351. return false;
  95352. }
  95353. var mesh = abstractMesh;
  95354. if (!mesh.isVisible || !mesh.isEnabled()) {
  95355. return false;
  95356. }
  95357. if (mesh.instances.length > 0) {
  95358. return false;
  95359. }
  95360. if (mesh.skeleton || mesh.hasLODLevels) {
  95361. return false;
  95362. }
  95363. if (mesh.parent) {
  95364. return false;
  95365. }
  95366. return true;
  95367. };
  95368. return _this;
  95369. }
  95370. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95371. /**
  95372. * Gets or sets a boolean which defines if optimization octree has to be updated
  95373. */
  95374. get: function () {
  95375. return MergeMeshesOptimization._UpdateSelectionTree;
  95376. },
  95377. /**
  95378. * Gets or sets a boolean which defines if optimization octree has to be updated
  95379. */
  95380. set: function (value) {
  95381. MergeMeshesOptimization._UpdateSelectionTree = value;
  95382. },
  95383. enumerable: true,
  95384. configurable: true
  95385. });
  95386. /**
  95387. * Gets a string describing the action executed by the current optimization
  95388. * @return description string
  95389. */
  95390. MergeMeshesOptimization.prototype.getDescription = function () {
  95391. return "Merging similar meshes together";
  95392. };
  95393. /**
  95394. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95395. * @param scene defines the current scene where to apply this optimization
  95396. * @param optimizer defines the current optimizer
  95397. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95398. * @returns true if everything that can be done was applied
  95399. */
  95400. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95401. var globalPool = scene.meshes.slice(0);
  95402. var globalLength = globalPool.length;
  95403. for (var index = 0; index < globalLength; index++) {
  95404. var currentPool = new Array();
  95405. var current = globalPool[index];
  95406. // Checks
  95407. if (!this._canBeMerged(current)) {
  95408. continue;
  95409. }
  95410. currentPool.push(current);
  95411. // Find compatible meshes
  95412. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95413. var otherMesh = globalPool[subIndex];
  95414. if (!this._canBeMerged(otherMesh)) {
  95415. continue;
  95416. }
  95417. if (otherMesh.material !== current.material) {
  95418. continue;
  95419. }
  95420. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95421. continue;
  95422. }
  95423. currentPool.push(otherMesh);
  95424. globalLength--;
  95425. globalPool.splice(subIndex, 1);
  95426. subIndex--;
  95427. }
  95428. if (currentPool.length < 2) {
  95429. continue;
  95430. }
  95431. // Merge meshes
  95432. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95433. }
  95434. if (updateSelectionTree != undefined) {
  95435. if (updateSelectionTree) {
  95436. scene.createOrUpdateSelectionOctree();
  95437. }
  95438. }
  95439. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95440. scene.createOrUpdateSelectionOctree();
  95441. }
  95442. return true;
  95443. };
  95444. ;
  95445. MergeMeshesOptimization._UpdateSelectionTree = false;
  95446. return MergeMeshesOptimization;
  95447. }(SceneOptimization));
  95448. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95449. /**
  95450. * Defines a list of options used by SceneOptimizer
  95451. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95452. */
  95453. var SceneOptimizerOptions = /** @class */ (function () {
  95454. /**
  95455. * Creates a new list of options used by SceneOptimizer
  95456. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95457. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95458. */
  95459. function SceneOptimizerOptions(
  95460. /**
  95461. * Defines the target frame rate to reach (60 by default)
  95462. */
  95463. targetFrameRate,
  95464. /**
  95465. * Defines the interval between two checkes (2000ms by default)
  95466. */
  95467. trackerDuration) {
  95468. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95469. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95470. this.targetFrameRate = targetFrameRate;
  95471. this.trackerDuration = trackerDuration;
  95472. /**
  95473. * Gets the list of optimizations to apply
  95474. */
  95475. this.optimizations = new Array();
  95476. }
  95477. /**
  95478. * Add a new optimization
  95479. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95480. * @returns the current SceneOptimizerOptions
  95481. */
  95482. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95483. this.optimizations.push(optimization);
  95484. return this;
  95485. };
  95486. /**
  95487. * Add a new custom optimization
  95488. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95489. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95490. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95491. * @returns the current SceneOptimizerOptions
  95492. */
  95493. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95494. if (priority === void 0) { priority = 0; }
  95495. var optimization = new CustomOptimization(priority);
  95496. optimization.onApply = onApply;
  95497. optimization.onGetDescription = onGetDescription;
  95498. this.optimizations.push(optimization);
  95499. return this;
  95500. };
  95501. /**
  95502. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95503. * @param targetFrameRate defines the target frame rate (60 by default)
  95504. * @returns a SceneOptimizerOptions object
  95505. */
  95506. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95507. var result = new SceneOptimizerOptions(targetFrameRate);
  95508. var priority = 0;
  95509. result.addOptimization(new MergeMeshesOptimization(priority));
  95510. result.addOptimization(new ShadowsOptimization(priority));
  95511. result.addOptimization(new LensFlaresOptimization(priority));
  95512. // Next priority
  95513. priority++;
  95514. result.addOptimization(new PostProcessesOptimization(priority));
  95515. result.addOptimization(new ParticlesOptimization(priority));
  95516. // Next priority
  95517. priority++;
  95518. result.addOptimization(new TextureOptimization(priority, 1024));
  95519. return result;
  95520. };
  95521. /**
  95522. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95523. * @param targetFrameRate defines the target frame rate (60 by default)
  95524. * @returns a SceneOptimizerOptions object
  95525. */
  95526. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95527. var result = new SceneOptimizerOptions(targetFrameRate);
  95528. var priority = 0;
  95529. result.addOptimization(new MergeMeshesOptimization(priority));
  95530. result.addOptimization(new ShadowsOptimization(priority));
  95531. result.addOptimization(new LensFlaresOptimization(priority));
  95532. // Next priority
  95533. priority++;
  95534. result.addOptimization(new PostProcessesOptimization(priority));
  95535. result.addOptimization(new ParticlesOptimization(priority));
  95536. // Next priority
  95537. priority++;
  95538. result.addOptimization(new TextureOptimization(priority, 512));
  95539. // Next priority
  95540. priority++;
  95541. result.addOptimization(new RenderTargetsOptimization(priority));
  95542. // Next priority
  95543. priority++;
  95544. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95545. return result;
  95546. };
  95547. /**
  95548. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95549. * @param targetFrameRate defines the target frame rate (60 by default)
  95550. * @returns a SceneOptimizerOptions object
  95551. */
  95552. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95553. var result = new SceneOptimizerOptions(targetFrameRate);
  95554. var priority = 0;
  95555. result.addOptimization(new MergeMeshesOptimization(priority));
  95556. result.addOptimization(new ShadowsOptimization(priority));
  95557. result.addOptimization(new LensFlaresOptimization(priority));
  95558. // Next priority
  95559. priority++;
  95560. result.addOptimization(new PostProcessesOptimization(priority));
  95561. result.addOptimization(new ParticlesOptimization(priority));
  95562. // Next priority
  95563. priority++;
  95564. result.addOptimization(new TextureOptimization(priority, 256));
  95565. // Next priority
  95566. priority++;
  95567. result.addOptimization(new RenderTargetsOptimization(priority));
  95568. // Next priority
  95569. priority++;
  95570. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95571. return result;
  95572. };
  95573. return SceneOptimizerOptions;
  95574. }());
  95575. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95576. /**
  95577. * Class used to run optimizations in order to reach a target frame rate
  95578. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95579. */
  95580. var SceneOptimizer = /** @class */ (function () {
  95581. /**
  95582. * Creates a new SceneOptimizer
  95583. * @param scene defines the scene to work on
  95584. * @param options defines the options to use with the SceneOptimizer
  95585. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95586. * @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)
  95587. */
  95588. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95589. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95590. if (improvementMode === void 0) { improvementMode = false; }
  95591. var _this = this;
  95592. this._isRunning = false;
  95593. this._currentPriorityLevel = 0;
  95594. this._targetFrameRate = 60;
  95595. this._trackerDuration = 2000;
  95596. this._currentFrameRate = 0;
  95597. this._improvementMode = false;
  95598. /**
  95599. * Defines an observable called when the optimizer reaches the target frame rate
  95600. */
  95601. this.onSuccessObservable = new BABYLON.Observable();
  95602. /**
  95603. * Defines an observable called when the optimizer enables an optimization
  95604. */
  95605. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95606. /**
  95607. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95608. */
  95609. this.onFailureObservable = new BABYLON.Observable();
  95610. if (!options) {
  95611. this._options = new SceneOptimizerOptions();
  95612. }
  95613. else {
  95614. this._options = options;
  95615. }
  95616. if (this._options.targetFrameRate) {
  95617. this._targetFrameRate = this._options.targetFrameRate;
  95618. }
  95619. if (this._options.trackerDuration) {
  95620. this._trackerDuration = this._options.trackerDuration;
  95621. }
  95622. if (autoGeneratePriorities) {
  95623. var priority = 0;
  95624. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95625. var optim = _a[_i];
  95626. optim.priority = priority++;
  95627. }
  95628. }
  95629. this._improvementMode = improvementMode;
  95630. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95631. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95632. _this._sceneDisposeObserver = null;
  95633. _this.dispose();
  95634. });
  95635. }
  95636. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95637. /**
  95638. * Gets a boolean indicating if the optimizer is in improvement mode
  95639. */
  95640. get: function () {
  95641. return this._improvementMode;
  95642. },
  95643. enumerable: true,
  95644. configurable: true
  95645. });
  95646. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95647. /**
  95648. * Gets the current priority level (0 at start)
  95649. */
  95650. get: function () {
  95651. return this._currentPriorityLevel;
  95652. },
  95653. enumerable: true,
  95654. configurable: true
  95655. });
  95656. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95657. /**
  95658. * Gets the current frame rate checked by the SceneOptimizer
  95659. */
  95660. get: function () {
  95661. return this._currentFrameRate;
  95662. },
  95663. enumerable: true,
  95664. configurable: true
  95665. });
  95666. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95667. /**
  95668. * Gets or sets the current target frame rate (60 by default)
  95669. */
  95670. get: function () {
  95671. return this._targetFrameRate;
  95672. },
  95673. /**
  95674. * Gets or sets the current target frame rate (60 by default)
  95675. */
  95676. set: function (value) {
  95677. this._targetFrameRate = value;
  95678. },
  95679. enumerable: true,
  95680. configurable: true
  95681. });
  95682. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95683. /**
  95684. * Gets or sets the current interval between two checks (every 2000ms by default)
  95685. */
  95686. get: function () {
  95687. return this._trackerDuration;
  95688. },
  95689. /**
  95690. * Gets or sets the current interval between two checks (every 2000ms by default)
  95691. */
  95692. set: function (value) {
  95693. this._trackerDuration = value;
  95694. },
  95695. enumerable: true,
  95696. configurable: true
  95697. });
  95698. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95699. /**
  95700. * Gets the list of active optimizations
  95701. */
  95702. get: function () {
  95703. return this._options.optimizations;
  95704. },
  95705. enumerable: true,
  95706. configurable: true
  95707. });
  95708. /**
  95709. * Stops the current optimizer
  95710. */
  95711. SceneOptimizer.prototype.stop = function () {
  95712. this._isRunning = false;
  95713. };
  95714. /**
  95715. * Reset the optimizer to initial step (current priority level = 0)
  95716. */
  95717. SceneOptimizer.prototype.reset = function () {
  95718. this._currentPriorityLevel = 0;
  95719. };
  95720. /**
  95721. * Start the optimizer. By default it will try to reach a specific framerate
  95722. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95723. */
  95724. SceneOptimizer.prototype.start = function () {
  95725. var _this = this;
  95726. if (this._isRunning) {
  95727. return;
  95728. }
  95729. this._isRunning = true;
  95730. // Let's wait for the scene to be ready before running our check
  95731. this._scene.executeWhenReady(function () {
  95732. setTimeout(function () {
  95733. _this._checkCurrentState();
  95734. }, _this._trackerDuration);
  95735. });
  95736. };
  95737. SceneOptimizer.prototype._checkCurrentState = function () {
  95738. var _this = this;
  95739. if (!this._isRunning) {
  95740. return;
  95741. }
  95742. var scene = this._scene;
  95743. var options = this._options;
  95744. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95745. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95746. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95747. this._isRunning = false;
  95748. this.onSuccessObservable.notifyObservers(this);
  95749. return;
  95750. }
  95751. // Apply current level of optimizations
  95752. var allDone = true;
  95753. var noOptimizationApplied = true;
  95754. for (var index = 0; index < options.optimizations.length; index++) {
  95755. var optimization = options.optimizations[index];
  95756. if (optimization.priority === this._currentPriorityLevel) {
  95757. noOptimizationApplied = false;
  95758. allDone = allDone && optimization.apply(scene, this);
  95759. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95760. }
  95761. }
  95762. // If no optimization was applied, this is a failure :(
  95763. if (noOptimizationApplied) {
  95764. this._isRunning = false;
  95765. this.onFailureObservable.notifyObservers(this);
  95766. return;
  95767. }
  95768. // If all optimizations were done, move to next level
  95769. if (allDone) {
  95770. this._currentPriorityLevel++;
  95771. }
  95772. // Let's the system running for a specific amount of time before checking FPS
  95773. scene.executeWhenReady(function () {
  95774. setTimeout(function () {
  95775. _this._checkCurrentState();
  95776. }, _this._trackerDuration);
  95777. });
  95778. };
  95779. /**
  95780. * Release all resources
  95781. */
  95782. SceneOptimizer.prototype.dispose = function () {
  95783. this.stop();
  95784. this.onSuccessObservable.clear();
  95785. this.onFailureObservable.clear();
  95786. this.onNewOptimizationAppliedObservable.clear();
  95787. if (this._sceneDisposeObserver) {
  95788. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95789. }
  95790. };
  95791. /**
  95792. * Helper function to create a SceneOptimizer with one single line of code
  95793. * @param scene defines the scene to work on
  95794. * @param options defines the options to use with the SceneOptimizer
  95795. * @param onSuccess defines a callback to call on success
  95796. * @param onFailure defines a callback to call on failure
  95797. * @returns the new SceneOptimizer object
  95798. */
  95799. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95800. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95801. if (onSuccess) {
  95802. optimizer.onSuccessObservable.add(function () {
  95803. onSuccess();
  95804. });
  95805. }
  95806. if (onFailure) {
  95807. optimizer.onFailureObservable.add(function () {
  95808. onFailure();
  95809. });
  95810. }
  95811. optimizer.start();
  95812. return optimizer;
  95813. };
  95814. return SceneOptimizer;
  95815. }());
  95816. BABYLON.SceneOptimizer = SceneOptimizer;
  95817. })(BABYLON || (BABYLON = {}));
  95818. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95819. var BABYLON;
  95820. (function (BABYLON) {
  95821. var OutlineRenderer = /** @class */ (function () {
  95822. function OutlineRenderer(scene) {
  95823. this.zOffset = 1;
  95824. this._scene = scene;
  95825. }
  95826. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95827. var _this = this;
  95828. if (useOverlay === void 0) { useOverlay = false; }
  95829. var scene = this._scene;
  95830. var engine = this._scene.getEngine();
  95831. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95832. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95833. return;
  95834. }
  95835. var mesh = subMesh.getRenderingMesh();
  95836. var material = subMesh.getMaterial();
  95837. if (!material || !scene.activeCamera) {
  95838. return;
  95839. }
  95840. engine.enableEffect(this._effect);
  95841. // Logarithmic depth
  95842. if (material.useLogarithmicDepth) {
  95843. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95844. }
  95845. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95846. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95847. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95848. // Bones
  95849. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95850. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95851. }
  95852. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95853. // Alpha test
  95854. if (material && material.needAlphaTesting()) {
  95855. var alphaTexture = material.getAlphaTestTexture();
  95856. if (alphaTexture) {
  95857. this._effect.setTexture("diffuseSampler", alphaTexture);
  95858. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95859. }
  95860. }
  95861. engine.setZOffset(-this.zOffset);
  95862. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95863. engine.setZOffset(0);
  95864. };
  95865. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95866. var defines = [];
  95867. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95868. var mesh = subMesh.getMesh();
  95869. var material = subMesh.getMaterial();
  95870. if (material) {
  95871. // Alpha test
  95872. if (material.needAlphaTesting()) {
  95873. defines.push("#define ALPHATEST");
  95874. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95875. attribs.push(BABYLON.VertexBuffer.UVKind);
  95876. defines.push("#define UV1");
  95877. }
  95878. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95879. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95880. defines.push("#define UV2");
  95881. }
  95882. }
  95883. //Logarithmic depth
  95884. if (material.useLogarithmicDepth) {
  95885. defines.push("#define LOGARITHMICDEPTH");
  95886. }
  95887. }
  95888. // Bones
  95889. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95890. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95891. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95892. if (mesh.numBoneInfluencers > 4) {
  95893. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95894. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95895. }
  95896. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95897. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95898. }
  95899. else {
  95900. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95901. }
  95902. // Instances
  95903. if (useInstances) {
  95904. defines.push("#define INSTANCES");
  95905. attribs.push("world0");
  95906. attribs.push("world1");
  95907. attribs.push("world2");
  95908. attribs.push("world3");
  95909. }
  95910. // Get correct effect
  95911. var join = defines.join("\n");
  95912. if (this._cachedDefines !== join) {
  95913. this._cachedDefines = join;
  95914. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95915. }
  95916. return this._effect.isReady();
  95917. };
  95918. return OutlineRenderer;
  95919. }());
  95920. BABYLON.OutlineRenderer = OutlineRenderer;
  95921. })(BABYLON || (BABYLON = {}));
  95922. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95923. var BABYLON;
  95924. (function (BABYLON) {
  95925. var FaceAdjacencies = /** @class */ (function () {
  95926. function FaceAdjacencies() {
  95927. this.edges = new Array();
  95928. this.edgesConnectedCount = 0;
  95929. }
  95930. return FaceAdjacencies;
  95931. }());
  95932. var EdgesRenderer = /** @class */ (function () {
  95933. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95934. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95935. if (epsilon === void 0) { epsilon = 0.95; }
  95936. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95937. this.edgesWidthScalerForOrthographic = 1000.0;
  95938. this.edgesWidthScalerForPerspective = 50.0;
  95939. this._linesPositions = new Array();
  95940. this._linesNormals = new Array();
  95941. this._linesIndices = new Array();
  95942. this._buffers = {};
  95943. this._checkVerticesInsteadOfIndices = false;
  95944. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95945. this.isEnabled = true;
  95946. this._source = source;
  95947. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95948. this._epsilon = epsilon;
  95949. this._prepareRessources();
  95950. this._generateEdgesLines();
  95951. }
  95952. EdgesRenderer.prototype._prepareRessources = function () {
  95953. if (this._lineShader) {
  95954. return;
  95955. }
  95956. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95957. attributes: ["position", "normal"],
  95958. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95959. });
  95960. this._lineShader.disableDepthWrite = true;
  95961. this._lineShader.backFaceCulling = false;
  95962. };
  95963. EdgesRenderer.prototype._rebuild = function () {
  95964. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95965. if (buffer) {
  95966. buffer._rebuild();
  95967. }
  95968. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95969. if (buffer) {
  95970. buffer._rebuild();
  95971. }
  95972. var scene = this._source.getScene();
  95973. var engine = scene.getEngine();
  95974. this._ib = engine.createIndexBuffer(this._linesIndices);
  95975. };
  95976. EdgesRenderer.prototype.dispose = function () {
  95977. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95978. if (buffer) {
  95979. buffer.dispose();
  95980. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95981. }
  95982. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95983. if (buffer) {
  95984. buffer.dispose();
  95985. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95986. }
  95987. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95988. this._lineShader.dispose();
  95989. };
  95990. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95991. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95992. return 0;
  95993. }
  95994. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95995. return 1;
  95996. }
  95997. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95998. return 2;
  95999. }
  96000. return -1;
  96001. };
  96002. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96003. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96004. return 0;
  96005. }
  96006. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96007. return 1;
  96008. }
  96009. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96010. return 2;
  96011. }
  96012. return -1;
  96013. };
  96014. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96015. var needToCreateLine;
  96016. if (edge === undefined) {
  96017. needToCreateLine = true;
  96018. }
  96019. else {
  96020. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96021. needToCreateLine = dotProduct < this._epsilon;
  96022. }
  96023. if (needToCreateLine) {
  96024. var offset = this._linesPositions.length / 3;
  96025. var normal = p0.subtract(p1);
  96026. normal.normalize();
  96027. // Positions
  96028. this._linesPositions.push(p0.x);
  96029. this._linesPositions.push(p0.y);
  96030. this._linesPositions.push(p0.z);
  96031. this._linesPositions.push(p0.x);
  96032. this._linesPositions.push(p0.y);
  96033. this._linesPositions.push(p0.z);
  96034. this._linesPositions.push(p1.x);
  96035. this._linesPositions.push(p1.y);
  96036. this._linesPositions.push(p1.z);
  96037. this._linesPositions.push(p1.x);
  96038. this._linesPositions.push(p1.y);
  96039. this._linesPositions.push(p1.z);
  96040. // Normals
  96041. this._linesNormals.push(p1.x);
  96042. this._linesNormals.push(p1.y);
  96043. this._linesNormals.push(p1.z);
  96044. this._linesNormals.push(-1);
  96045. this._linesNormals.push(p1.x);
  96046. this._linesNormals.push(p1.y);
  96047. this._linesNormals.push(p1.z);
  96048. this._linesNormals.push(1);
  96049. this._linesNormals.push(p0.x);
  96050. this._linesNormals.push(p0.y);
  96051. this._linesNormals.push(p0.z);
  96052. this._linesNormals.push(-1);
  96053. this._linesNormals.push(p0.x);
  96054. this._linesNormals.push(p0.y);
  96055. this._linesNormals.push(p0.z);
  96056. this._linesNormals.push(1);
  96057. // Indices
  96058. this._linesIndices.push(offset);
  96059. this._linesIndices.push(offset + 1);
  96060. this._linesIndices.push(offset + 2);
  96061. this._linesIndices.push(offset);
  96062. this._linesIndices.push(offset + 2);
  96063. this._linesIndices.push(offset + 3);
  96064. }
  96065. };
  96066. EdgesRenderer.prototype._generateEdgesLines = function () {
  96067. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96068. var indices = this._source.getIndices();
  96069. if (!indices || !positions) {
  96070. return;
  96071. }
  96072. // First let's find adjacencies
  96073. var adjacencies = new Array();
  96074. var faceNormals = new Array();
  96075. var index;
  96076. var faceAdjacencies;
  96077. // Prepare faces
  96078. for (index = 0; index < indices.length; index += 3) {
  96079. faceAdjacencies = new FaceAdjacencies();
  96080. var p0Index = indices[index];
  96081. var p1Index = indices[index + 1];
  96082. var p2Index = indices[index + 2];
  96083. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96084. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96085. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96086. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96087. faceNormal.normalize();
  96088. faceNormals.push(faceNormal);
  96089. adjacencies.push(faceAdjacencies);
  96090. }
  96091. // Scan
  96092. for (index = 0; index < adjacencies.length; index++) {
  96093. faceAdjacencies = adjacencies[index];
  96094. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96095. var otherFaceAdjacencies = adjacencies[otherIndex];
  96096. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96097. break;
  96098. }
  96099. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96100. continue;
  96101. }
  96102. var otherP0 = indices[otherIndex * 3];
  96103. var otherP1 = indices[otherIndex * 3 + 1];
  96104. var otherP2 = indices[otherIndex * 3 + 2];
  96105. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96106. var otherEdgeIndex = 0;
  96107. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96108. continue;
  96109. }
  96110. switch (edgeIndex) {
  96111. case 0:
  96112. if (this._checkVerticesInsteadOfIndices) {
  96113. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96114. }
  96115. else {
  96116. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96117. }
  96118. break;
  96119. case 1:
  96120. if (this._checkVerticesInsteadOfIndices) {
  96121. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96122. }
  96123. else {
  96124. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96125. }
  96126. break;
  96127. case 2:
  96128. if (this._checkVerticesInsteadOfIndices) {
  96129. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96130. }
  96131. else {
  96132. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96133. }
  96134. break;
  96135. }
  96136. if (otherEdgeIndex === -1) {
  96137. continue;
  96138. }
  96139. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96140. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96141. faceAdjacencies.edgesConnectedCount++;
  96142. otherFaceAdjacencies.edgesConnectedCount++;
  96143. if (faceAdjacencies.edgesConnectedCount === 3) {
  96144. break;
  96145. }
  96146. }
  96147. }
  96148. }
  96149. // Create lines
  96150. for (index = 0; index < adjacencies.length; index++) {
  96151. // 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
  96152. var current = adjacencies[index];
  96153. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96154. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96155. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96156. }
  96157. // Merge into a single mesh
  96158. var engine = this._source.getScene().getEngine();
  96159. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96160. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96161. this._ib = engine.createIndexBuffer(this._linesIndices);
  96162. this._indicesCount = this._linesIndices.length;
  96163. };
  96164. EdgesRenderer.prototype.render = function () {
  96165. var scene = this._source.getScene();
  96166. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96167. return;
  96168. }
  96169. var engine = scene.getEngine();
  96170. this._lineShader._preBind();
  96171. // VBOs
  96172. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96173. scene.resetCachedMaterial();
  96174. this._lineShader.setColor4("color", this._source.edgesColor);
  96175. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96176. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  96177. }
  96178. else {
  96179. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  96180. }
  96181. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  96182. this._lineShader.bind(this._source.getWorldMatrix());
  96183. // Draw order
  96184. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  96185. this._lineShader.unbind();
  96186. engine.setDepthWrite(true);
  96187. };
  96188. return EdgesRenderer;
  96189. }());
  96190. BABYLON.EdgesRenderer = EdgesRenderer;
  96191. })(BABYLON || (BABYLON = {}));
  96192. //# sourceMappingURL=babylon.edgesRenderer.js.map
  96193. var BABYLON;
  96194. (function (BABYLON) {
  96195. // Adds the parser to the scene parsers.
  96196. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  96197. if (parsedData.effectLayers) {
  96198. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  96199. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  96200. container.effectLayers.push(effectLayer);
  96201. }
  96202. }
  96203. });
  96204. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  96205. var index = this.effectLayers.indexOf(toRemove);
  96206. if (index !== -1) {
  96207. this.effectLayers.splice(index, 1);
  96208. }
  96209. return index;
  96210. };
  96211. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  96212. this.effectLayers.push(newEffectLayer);
  96213. };
  96214. /**
  96215. * Defines the layer scene component responsible to manage any effect layers
  96216. * in a given scene.
  96217. */
  96218. var EffectLayerSceneComponent = /** @class */ (function () {
  96219. /**
  96220. * Creates a new instance of the component for the given scene
  96221. * @param scene Defines the scene to register the component in
  96222. */
  96223. function EffectLayerSceneComponent(scene) {
  96224. /**
  96225. * The component name helpfull to identify the component in the list of scene components.
  96226. */
  96227. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  96228. this._renderEffects = false;
  96229. this._needStencil = false;
  96230. this._previousStencilState = false;
  96231. this.scene = scene;
  96232. this._engine = scene.getEngine();
  96233. scene.effectLayers = new Array();
  96234. }
  96235. /**
  96236. * Registers the component in a given scene
  96237. */
  96238. EffectLayerSceneComponent.prototype.register = function () {
  96239. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  96240. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  96241. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  96242. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  96243. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  96244. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  96245. };
  96246. /**
  96247. * Rebuilds the elements related to this component in case of
  96248. * context lost for instance.
  96249. */
  96250. EffectLayerSceneComponent.prototype.rebuild = function () {
  96251. var layers = this.scene.effectLayers;
  96252. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  96253. var effectLayer = layers_1[_i];
  96254. effectLayer._rebuild();
  96255. }
  96256. };
  96257. /**
  96258. * Serializes the component data to the specified json object
  96259. * @param serializationObject The object to serialize to
  96260. */
  96261. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96262. // Effect layers
  96263. serializationObject.effectLayers = [];
  96264. var layers = this.scene.effectLayers;
  96265. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  96266. var effectLayer = layers_2[_i];
  96267. if (effectLayer.serialize) {
  96268. serializationObject.effectLayers.push(effectLayer.serialize());
  96269. }
  96270. }
  96271. };
  96272. /**
  96273. * Adds all the element from the container to the scene
  96274. * @param container the container holding the elements
  96275. */
  96276. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96277. var _this = this;
  96278. if (!container.effectLayers) {
  96279. return;
  96280. }
  96281. container.effectLayers.forEach(function (o) {
  96282. _this.scene.addEffectLayer(o);
  96283. });
  96284. };
  96285. /**
  96286. * Removes all the elements in the container from the scene
  96287. * @param container contains the elements to remove
  96288. */
  96289. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96290. var _this = this;
  96291. if (!container.effectLayers) {
  96292. return;
  96293. }
  96294. container.effectLayers.forEach(function (o) {
  96295. _this.scene.removeEffectLayer(o);
  96296. });
  96297. };
  96298. /**
  96299. * Disposes the component and the associated ressources.
  96300. */
  96301. EffectLayerSceneComponent.prototype.dispose = function () {
  96302. var layers = this.scene.effectLayers;
  96303. while (layers.length) {
  96304. layers[0].dispose();
  96305. }
  96306. };
  96307. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96308. var layers = this.scene.effectLayers;
  96309. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  96310. var layer = layers_3[_i];
  96311. if (!layer.hasMesh(mesh)) {
  96312. continue;
  96313. }
  96314. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  96315. var subMesh = _b[_a];
  96316. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96317. return false;
  96318. }
  96319. }
  96320. }
  96321. return true;
  96322. };
  96323. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96324. this._renderEffects = false;
  96325. this._needStencil = false;
  96326. var layers = this.scene.effectLayers;
  96327. if (layers && layers.length > 0) {
  96328. this._previousStencilState = this._engine.getStencilBuffer();
  96329. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  96330. var effectLayer = layers_4[_i];
  96331. if (effectLayer.shouldRender() &&
  96332. (!effectLayer.camera ||
  96333. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96334. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96335. this._renderEffects = true;
  96336. this._needStencil = this._needStencil || effectLayer.needStencil();
  96337. var renderTarget = effectLayer._mainTexture;
  96338. if (renderTarget._shouldRender()) {
  96339. this.scene.incrementRenderId();
  96340. renderTarget.render(false, false);
  96341. }
  96342. }
  96343. }
  96344. this.scene.incrementRenderId();
  96345. }
  96346. };
  96347. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96348. // Activate effect Layer stencil
  96349. if (this._needStencil) {
  96350. this._engine.setStencilBuffer(true);
  96351. }
  96352. };
  96353. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96354. // Restore effect Layer stencil
  96355. if (this._needStencil) {
  96356. this._engine.setStencilBuffer(this._previousStencilState);
  96357. }
  96358. };
  96359. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  96360. if (this._renderEffects) {
  96361. this._engine.setDepthBuffer(false);
  96362. var layers = this.scene.effectLayers;
  96363. for (var i = 0; i < layers.length; i++) {
  96364. var effectLayer = layers[i];
  96365. if (effectLayer.renderingGroupId === renderingGroupId) {
  96366. if (effectLayer.shouldRender()) {
  96367. effectLayer.render();
  96368. }
  96369. }
  96370. }
  96371. this._engine.setDepthBuffer(true);
  96372. }
  96373. };
  96374. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  96375. if (this._renderEffects) {
  96376. this._draw(-1);
  96377. }
  96378. };
  96379. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  96380. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  96381. this._draw(index);
  96382. }
  96383. };
  96384. return EffectLayerSceneComponent;
  96385. }());
  96386. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96387. })(BABYLON || (BABYLON = {}));
  96388. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96389. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96390. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96391. s = arguments[i];
  96392. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96393. t[p] = s[p];
  96394. }
  96395. return t;
  96396. };
  96397. var BABYLON;
  96398. (function (BABYLON) {
  96399. /**
  96400. * The effect layer Helps adding post process effect blended with the main pass.
  96401. *
  96402. * This can be for instance use to generate glow or higlight effects on the scene.
  96403. *
  96404. * The effect layer class can not be used directly and is intented to inherited from to be
  96405. * customized per effects.
  96406. */
  96407. var EffectLayer = /** @class */ (function () {
  96408. /**
  96409. * Instantiates a new effect Layer and references it in the scene.
  96410. * @param name The name of the layer
  96411. * @param scene The scene to use the layer in
  96412. */
  96413. function EffectLayer(
  96414. /** The Friendly of the effect in the scene */
  96415. name, scene) {
  96416. this._vertexBuffers = {};
  96417. this._maxSize = 0;
  96418. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96419. this._shouldRender = true;
  96420. this._postProcesses = [];
  96421. this._textures = [];
  96422. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96423. /**
  96424. * The clear color of the texture used to generate the glow map.
  96425. */
  96426. this.neutralColor = new BABYLON.Color4();
  96427. /**
  96428. * Specifies wether the highlight layer is enabled or not.
  96429. */
  96430. this.isEnabled = true;
  96431. /**
  96432. * An event triggered when the effect layer has been disposed.
  96433. */
  96434. this.onDisposeObservable = new BABYLON.Observable();
  96435. /**
  96436. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96437. */
  96438. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96439. /**
  96440. * An event triggered when the generated texture is being merged in the scene.
  96441. */
  96442. this.onBeforeComposeObservable = new BABYLON.Observable();
  96443. /**
  96444. * An event triggered when the generated texture has been merged in the scene.
  96445. */
  96446. this.onAfterComposeObservable = new BABYLON.Observable();
  96447. /**
  96448. * An event triggered when the efffect layer changes its size.
  96449. */
  96450. this.onSizeChangedObservable = new BABYLON.Observable();
  96451. this.name = name;
  96452. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96453. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96454. if (!component) {
  96455. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96456. this._scene._addComponent(component);
  96457. }
  96458. this._engine = this._scene.getEngine();
  96459. this._maxSize = this._engine.getCaps().maxTextureSize;
  96460. this._scene.effectLayers.push(this);
  96461. // Generate Buffers
  96462. this._generateIndexBuffer();
  96463. this._genrateVertexBuffer();
  96464. }
  96465. Object.defineProperty(EffectLayer.prototype, "camera", {
  96466. /**
  96467. * Gets the camera attached to the layer.
  96468. */
  96469. get: function () {
  96470. return this._effectLayerOptions.camera;
  96471. },
  96472. enumerable: true,
  96473. configurable: true
  96474. });
  96475. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  96476. /**
  96477. * Gets the rendering group id the layer should render in.
  96478. */
  96479. get: function () {
  96480. return this._effectLayerOptions.renderingGroupId;
  96481. },
  96482. enumerable: true,
  96483. configurable: true
  96484. });
  96485. /**
  96486. * Initializes the effect layer with the required options.
  96487. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96488. */
  96489. EffectLayer.prototype._init = function (options) {
  96490. // Adapt options
  96491. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96492. this._setMainTextureSize();
  96493. this._createMainTexture();
  96494. this._createTextureAndPostProcesses();
  96495. this._mergeEffect = this._createMergeEffect();
  96496. };
  96497. /**
  96498. * Generates the index buffer of the full screen quad blending to the main canvas.
  96499. */
  96500. EffectLayer.prototype._generateIndexBuffer = function () {
  96501. // Indices
  96502. var indices = [];
  96503. indices.push(0);
  96504. indices.push(1);
  96505. indices.push(2);
  96506. indices.push(0);
  96507. indices.push(2);
  96508. indices.push(3);
  96509. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96510. };
  96511. /**
  96512. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96513. */
  96514. EffectLayer.prototype._genrateVertexBuffer = function () {
  96515. // VBO
  96516. var vertices = [];
  96517. vertices.push(1, 1);
  96518. vertices.push(-1, 1);
  96519. vertices.push(-1, -1);
  96520. vertices.push(1, -1);
  96521. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96522. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96523. };
  96524. /**
  96525. * Sets the main texture desired size which is the closest power of two
  96526. * of the engine canvas size.
  96527. */
  96528. EffectLayer.prototype._setMainTextureSize = function () {
  96529. if (this._effectLayerOptions.mainTextureFixedSize) {
  96530. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96531. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96532. }
  96533. else {
  96534. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96535. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96536. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96537. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96538. }
  96539. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96540. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96541. };
  96542. /**
  96543. * Creates the main texture for the effect layer.
  96544. */
  96545. EffectLayer.prototype._createMainTexture = function () {
  96546. var _this = this;
  96547. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96548. width: this._mainTextureDesiredSize.width,
  96549. height: this._mainTextureDesiredSize.height
  96550. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96551. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96552. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96553. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96554. this._mainTexture.anisotropicFilteringLevel = 1;
  96555. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96556. this._mainTexture.renderParticles = false;
  96557. this._mainTexture.renderList = null;
  96558. this._mainTexture.ignoreCameraViewport = true;
  96559. // Custom render function
  96560. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96561. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96562. var index;
  96563. var engine = _this._scene.getEngine();
  96564. if (depthOnlySubMeshes.length) {
  96565. engine.setColorWrite(false);
  96566. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96567. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96568. }
  96569. engine.setColorWrite(true);
  96570. }
  96571. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96572. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96573. }
  96574. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96575. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96576. }
  96577. for (index = 0; index < transparentSubMeshes.length; index++) {
  96578. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96579. }
  96580. };
  96581. this._mainTexture.onClearObservable.add(function (engine) {
  96582. engine.clear(_this.neutralColor, true, true, true);
  96583. });
  96584. };
  96585. /**
  96586. * Checks for the readiness of the element composing the layer.
  96587. * @param subMesh the mesh to check for
  96588. * @param useInstances specify wether or not to use instances to render the mesh
  96589. * @param emissiveTexture the associated emissive texture used to generate the glow
  96590. * @return true if ready otherwise, false
  96591. */
  96592. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96593. var material = subMesh.getMaterial();
  96594. if (!material) {
  96595. return false;
  96596. }
  96597. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96598. return false;
  96599. }
  96600. var defines = [];
  96601. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96602. var mesh = subMesh.getMesh();
  96603. var uv1 = false;
  96604. var uv2 = false;
  96605. // Alpha test
  96606. if (material && material.needAlphaTesting()) {
  96607. var alphaTexture = material.getAlphaTestTexture();
  96608. if (alphaTexture) {
  96609. defines.push("#define ALPHATEST");
  96610. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96611. alphaTexture.coordinatesIndex === 1) {
  96612. defines.push("#define DIFFUSEUV2");
  96613. uv2 = true;
  96614. }
  96615. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96616. defines.push("#define DIFFUSEUV1");
  96617. uv1 = true;
  96618. }
  96619. }
  96620. }
  96621. // Emissive
  96622. if (emissiveTexture) {
  96623. defines.push("#define EMISSIVE");
  96624. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96625. emissiveTexture.coordinatesIndex === 1) {
  96626. defines.push("#define EMISSIVEUV2");
  96627. uv2 = true;
  96628. }
  96629. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96630. defines.push("#define EMISSIVEUV1");
  96631. uv1 = true;
  96632. }
  96633. }
  96634. if (uv1) {
  96635. attribs.push(BABYLON.VertexBuffer.UVKind);
  96636. defines.push("#define UV1");
  96637. }
  96638. if (uv2) {
  96639. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96640. defines.push("#define UV2");
  96641. }
  96642. // Bones
  96643. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96646. if (mesh.numBoneInfluencers > 4) {
  96647. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96648. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96649. }
  96650. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96651. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96652. }
  96653. else {
  96654. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96655. }
  96656. // Morph targets
  96657. var manager = mesh.morphTargetManager;
  96658. var morphInfluencers = 0;
  96659. if (manager) {
  96660. if (manager.numInfluencers > 0) {
  96661. defines.push("#define MORPHTARGETS");
  96662. morphInfluencers = manager.numInfluencers;
  96663. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96664. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96665. }
  96666. }
  96667. // Instances
  96668. if (useInstances) {
  96669. defines.push("#define INSTANCES");
  96670. attribs.push("world0");
  96671. attribs.push("world1");
  96672. attribs.push("world2");
  96673. attribs.push("world3");
  96674. }
  96675. // Get correct effect
  96676. var join = defines.join("\n");
  96677. if (this._cachedDefines !== join) {
  96678. this._cachedDefines = join;
  96679. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96680. }
  96681. return this._effectLayerMapGenerationEffect.isReady();
  96682. };
  96683. /**
  96684. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96685. */
  96686. EffectLayer.prototype.render = function () {
  96687. var currentEffect = this._mergeEffect;
  96688. // Check
  96689. if (!currentEffect.isReady())
  96690. return;
  96691. for (var i = 0; i < this._postProcesses.length; i++) {
  96692. if (!this._postProcesses[i].isReady()) {
  96693. return;
  96694. }
  96695. }
  96696. var engine = this._scene.getEngine();
  96697. this.onBeforeComposeObservable.notifyObservers(this);
  96698. // Render
  96699. engine.enableEffect(currentEffect);
  96700. engine.setState(false);
  96701. // VBOs
  96702. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96703. // Cache
  96704. var previousAlphaMode = engine.getAlphaMode();
  96705. // Go Blend.
  96706. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96707. // Blends the map on the main canvas.
  96708. this._internalRender(currentEffect);
  96709. // Restore Alpha
  96710. engine.setAlphaMode(previousAlphaMode);
  96711. this.onAfterComposeObservable.notifyObservers(this);
  96712. // Handle size changes.
  96713. var size = this._mainTexture.getSize();
  96714. this._setMainTextureSize();
  96715. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96716. // Recreate RTT and post processes on size change.
  96717. this.onSizeChangedObservable.notifyObservers(this);
  96718. this._disposeTextureAndPostProcesses();
  96719. this._createMainTexture();
  96720. this._createTextureAndPostProcesses();
  96721. }
  96722. };
  96723. /**
  96724. * Determine if a given mesh will be used in the current effect.
  96725. * @param mesh mesh to test
  96726. * @returns true if the mesh will be used
  96727. */
  96728. EffectLayer.prototype.hasMesh = function (mesh) {
  96729. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  96730. return true;
  96731. }
  96732. return false;
  96733. };
  96734. /**
  96735. * Returns true if the layer contains information to display, otherwise false.
  96736. * @returns true if the glow layer should be rendered
  96737. */
  96738. EffectLayer.prototype.shouldRender = function () {
  96739. return this.isEnabled && this._shouldRender;
  96740. };
  96741. /**
  96742. * Returns true if the mesh should render, otherwise false.
  96743. * @param mesh The mesh to render
  96744. * @returns true if it should render otherwise false
  96745. */
  96746. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96747. return true;
  96748. };
  96749. /**
  96750. * Returns true if the mesh should render, otherwise false.
  96751. * @param mesh The mesh to render
  96752. * @returns true if it should render otherwise false
  96753. */
  96754. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96755. return true;
  96756. };
  96757. /**
  96758. * Renders the submesh passed in parameter to the generation map.
  96759. */
  96760. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96761. var _this = this;
  96762. if (!this.shouldRender()) {
  96763. return;
  96764. }
  96765. var material = subMesh.getMaterial();
  96766. var mesh = subMesh.getRenderingMesh();
  96767. var scene = this._scene;
  96768. var engine = scene.getEngine();
  96769. if (!material) {
  96770. return;
  96771. }
  96772. // Do not block in blend mode.
  96773. if (material.needAlphaBlendingForMesh(mesh)) {
  96774. return;
  96775. }
  96776. // Culling
  96777. engine.setState(material.backFaceCulling);
  96778. // Managing instances
  96779. var batch = mesh._getInstancesRenderList(subMesh._id);
  96780. if (batch.mustReturn) {
  96781. return;
  96782. }
  96783. // Early Exit per mesh
  96784. if (!this._shouldRenderMesh(mesh)) {
  96785. return;
  96786. }
  96787. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96788. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96789. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96790. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96791. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96792. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96793. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96794. // Alpha test
  96795. if (material && material.needAlphaTesting()) {
  96796. var alphaTexture = material.getAlphaTestTexture();
  96797. if (alphaTexture) {
  96798. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96799. var textureMatrix = alphaTexture.getTextureMatrix();
  96800. if (textureMatrix) {
  96801. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96802. }
  96803. }
  96804. }
  96805. // Glow emissive only
  96806. if (this._emissiveTextureAndColor.texture) {
  96807. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96808. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96809. }
  96810. // Bones
  96811. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96812. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96813. }
  96814. // Morph targets
  96815. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96816. // Draw
  96817. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96818. }
  96819. else {
  96820. // Need to reset refresh rate of the main map
  96821. this._mainTexture.resetRefreshCounter();
  96822. }
  96823. };
  96824. /**
  96825. * Rebuild the required buffers.
  96826. * @hidden Internal use only.
  96827. */
  96828. EffectLayer.prototype._rebuild = function () {
  96829. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96830. if (vb) {
  96831. vb._rebuild();
  96832. }
  96833. this._generateIndexBuffer();
  96834. };
  96835. /**
  96836. * Dispose only the render target textures and post process.
  96837. */
  96838. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96839. this._mainTexture.dispose();
  96840. for (var i = 0; i < this._postProcesses.length; i++) {
  96841. if (this._postProcesses[i]) {
  96842. this._postProcesses[i].dispose();
  96843. }
  96844. }
  96845. this._postProcesses = [];
  96846. for (var i = 0; i < this._textures.length; i++) {
  96847. if (this._textures[i]) {
  96848. this._textures[i].dispose();
  96849. }
  96850. }
  96851. this._textures = [];
  96852. };
  96853. /**
  96854. * Dispose the highlight layer and free resources.
  96855. */
  96856. EffectLayer.prototype.dispose = function () {
  96857. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96858. if (vertexBuffer) {
  96859. vertexBuffer.dispose();
  96860. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96861. }
  96862. if (this._indexBuffer) {
  96863. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96864. this._indexBuffer = null;
  96865. }
  96866. // Clean textures and post processes
  96867. this._disposeTextureAndPostProcesses();
  96868. // Remove from scene
  96869. var index = this._scene.effectLayers.indexOf(this, 0);
  96870. if (index > -1) {
  96871. this._scene.effectLayers.splice(index, 1);
  96872. }
  96873. // Callback
  96874. this.onDisposeObservable.notifyObservers(this);
  96875. this.onDisposeObservable.clear();
  96876. this.onBeforeRenderMainTextureObservable.clear();
  96877. this.onBeforeComposeObservable.clear();
  96878. this.onAfterComposeObservable.clear();
  96879. this.onSizeChangedObservable.clear();
  96880. };
  96881. /**
  96882. * Gets the class name of the effect layer
  96883. * @returns the string with the class name of the effect layer
  96884. */
  96885. EffectLayer.prototype.getClassName = function () {
  96886. return "EffectLayer";
  96887. };
  96888. /**
  96889. * Creates an effect layer from parsed effect layer data
  96890. * @param parsedEffectLayer defines effect layer data
  96891. * @param scene defines the current scene
  96892. * @param rootUrl defines the root URL containing the effect layer information
  96893. * @returns a parsed effect Layer
  96894. */
  96895. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96896. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96897. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96898. };
  96899. __decorate([
  96900. BABYLON.serialize()
  96901. ], EffectLayer.prototype, "name", void 0);
  96902. __decorate([
  96903. BABYLON.serializeAsColor4()
  96904. ], EffectLayer.prototype, "neutralColor", void 0);
  96905. __decorate([
  96906. BABYLON.serialize()
  96907. ], EffectLayer.prototype, "isEnabled", void 0);
  96908. __decorate([
  96909. BABYLON.serializeAsCameraReference()
  96910. ], EffectLayer.prototype, "camera", null);
  96911. __decorate([
  96912. BABYLON.serialize()
  96913. ], EffectLayer.prototype, "renderingGroupId", null);
  96914. return EffectLayer;
  96915. }());
  96916. BABYLON.EffectLayer = EffectLayer;
  96917. })(BABYLON || (BABYLON = {}));
  96918. //# sourceMappingURL=babylon.effectLayer.js.map
  96919. var BABYLON;
  96920. (function (BABYLON) {
  96921. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  96922. for (var index = 0; index < this.effectLayers.length; index++) {
  96923. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  96924. return this.effectLayers[index];
  96925. }
  96926. }
  96927. return null;
  96928. };
  96929. /**
  96930. * Special Glow Blur post process only blurring the alpha channel
  96931. * It enforces keeping the most luminous color in the color channel.
  96932. */
  96933. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96934. __extends(GlowBlurPostProcess, _super);
  96935. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96936. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96937. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96938. _this.direction = direction;
  96939. _this.kernel = kernel;
  96940. _this.onApplyObservable.add(function (effect) {
  96941. effect.setFloat2("screenSize", _this.width, _this.height);
  96942. effect.setVector2("direction", _this.direction);
  96943. effect.setFloat("blurWidth", _this.kernel);
  96944. });
  96945. return _this;
  96946. }
  96947. return GlowBlurPostProcess;
  96948. }(BABYLON.PostProcess));
  96949. /**
  96950. * The highlight layer Helps adding a glow effect around a mesh.
  96951. *
  96952. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96953. * glowy meshes to your scene.
  96954. *
  96955. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96956. */
  96957. var HighlightLayer = /** @class */ (function (_super) {
  96958. __extends(HighlightLayer, _super);
  96959. /**
  96960. * Instantiates a new highlight Layer and references it to the scene..
  96961. * @param name The name of the layer
  96962. * @param scene The scene to use the layer in
  96963. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  96964. */
  96965. function HighlightLayer(name, scene, options) {
  96966. var _this = _super.call(this, name, scene) || this;
  96967. _this.name = name;
  96968. /**
  96969. * Specifies whether or not the inner glow is ACTIVE in the layer.
  96970. */
  96971. _this.innerGlow = true;
  96972. /**
  96973. * Specifies whether or not the outer glow is ACTIVE in the layer.
  96974. */
  96975. _this.outerGlow = true;
  96976. /**
  96977. * An event triggered when the highlight layer is being blurred.
  96978. */
  96979. _this.onBeforeBlurObservable = new BABYLON.Observable();
  96980. /**
  96981. * An event triggered when the highlight layer has been blurred.
  96982. */
  96983. _this.onAfterBlurObservable = new BABYLON.Observable();
  96984. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  96985. _this._meshes = {};
  96986. _this._excludedMeshes = {};
  96987. _this.neutralColor = HighlightLayer.NeutralColor;
  96988. // Warn on stencil
  96989. if (!_this._engine.isStencilEnable) {
  96990. 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 }");
  96991. }
  96992. // Adapt options
  96993. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96994. // Initialize the layer
  96995. _this._init({
  96996. alphaBlendingMode: _this._options.alphaBlendingMode,
  96997. camera: _this._options.camera,
  96998. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96999. mainTextureRatio: _this._options.mainTextureRatio,
  97000. renderingGroupId: _this._options.renderingGroupId
  97001. });
  97002. // Do not render as long as no meshes have been added
  97003. _this._shouldRender = false;
  97004. return _this;
  97005. }
  97006. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97007. /**
  97008. * Gets the horizontal size of the blur.
  97009. */
  97010. get: function () {
  97011. return this._horizontalBlurPostprocess.kernel;
  97012. },
  97013. /**
  97014. * Specifies the horizontal size of the blur.
  97015. */
  97016. set: function (value) {
  97017. this._horizontalBlurPostprocess.kernel = value;
  97018. },
  97019. enumerable: true,
  97020. configurable: true
  97021. });
  97022. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97023. /**
  97024. * Gets the vertical size of the blur.
  97025. */
  97026. get: function () {
  97027. return this._verticalBlurPostprocess.kernel;
  97028. },
  97029. /**
  97030. * Specifies the vertical size of the blur.
  97031. */
  97032. set: function (value) {
  97033. this._verticalBlurPostprocess.kernel = value;
  97034. },
  97035. enumerable: true,
  97036. configurable: true
  97037. });
  97038. /**
  97039. * Get the effect name of the layer.
  97040. * @return The effect name
  97041. */
  97042. HighlightLayer.prototype.getEffectName = function () {
  97043. return HighlightLayer.EffectName;
  97044. };
  97045. /**
  97046. * Create the merge effect. This is the shader use to blit the information back
  97047. * to the main canvas at the end of the scene rendering.
  97048. */
  97049. HighlightLayer.prototype._createMergeEffect = function () {
  97050. // Effect
  97051. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97052. };
  97053. /**
  97054. * Creates the render target textures and post processes used in the highlight layer.
  97055. */
  97056. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97057. var _this = this;
  97058. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97059. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97060. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97061. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97062. var textureType = 0;
  97063. if (this._engine.getCaps().textureHalfFloatRender) {
  97064. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97065. }
  97066. else {
  97067. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97068. }
  97069. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97070. width: blurTextureWidth,
  97071. height: blurTextureHeight
  97072. }, this._scene, false, true, textureType);
  97073. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97074. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97075. this._blurTexture.anisotropicFilteringLevel = 16;
  97076. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97077. this._blurTexture.renderParticles = false;
  97078. this._blurTexture.ignoreCameraViewport = true;
  97079. this._textures = [this._blurTexture];
  97080. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97081. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97082. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97083. effect.setTexture("textureSampler", _this._mainTexture);
  97084. });
  97085. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97086. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97087. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97088. });
  97089. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97090. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97091. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97092. });
  97093. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97094. }
  97095. else {
  97096. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97097. width: blurTextureWidth,
  97098. height: blurTextureHeight
  97099. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97100. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97101. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97102. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97103. effect.setTexture("textureSampler", _this._mainTexture);
  97104. });
  97105. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97106. width: blurTextureWidth,
  97107. height: blurTextureHeight
  97108. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97109. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97110. }
  97111. this._mainTexture.onAfterUnbindObservable.add(function () {
  97112. _this.onBeforeBlurObservable.notifyObservers(_this);
  97113. var internalTexture = _this._blurTexture.getInternalTexture();
  97114. if (internalTexture) {
  97115. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97116. }
  97117. _this.onAfterBlurObservable.notifyObservers(_this);
  97118. });
  97119. // Prevent autoClear.
  97120. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97121. };
  97122. /**
  97123. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97124. */
  97125. HighlightLayer.prototype.needStencil = function () {
  97126. return true;
  97127. };
  97128. /**
  97129. * Checks for the readiness of the element composing the layer.
  97130. * @param subMesh the mesh to check for
  97131. * @param useInstances specify wether or not to use instances to render the mesh
  97132. * @param emissiveTexture the associated emissive texture used to generate the glow
  97133. * @return true if ready otherwise, false
  97134. */
  97135. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97136. var material = subMesh.getMaterial();
  97137. var mesh = subMesh.getRenderingMesh();
  97138. if (!material || !mesh || !this._meshes) {
  97139. return false;
  97140. }
  97141. var emissiveTexture = null;
  97142. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97143. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97144. emissiveTexture = material.emissiveTexture;
  97145. }
  97146. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97147. };
  97148. /**
  97149. * Implementation specific of rendering the generating effect on the main canvas.
  97150. * @param effect The effect used to render through
  97151. */
  97152. HighlightLayer.prototype._internalRender = function (effect) {
  97153. // Texture
  97154. effect.setTexture("textureSampler", this._blurTexture);
  97155. // Cache
  97156. var engine = this._engine;
  97157. var previousStencilBuffer = engine.getStencilBuffer();
  97158. var previousStencilFunction = engine.getStencilFunction();
  97159. var previousStencilMask = engine.getStencilMask();
  97160. var previousStencilOperationPass = engine.getStencilOperationPass();
  97161. var previousStencilOperationFail = engine.getStencilOperationFail();
  97162. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97163. var previousStencilReference = engine.getStencilFunctionReference();
  97164. // Stencil operations
  97165. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97166. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97167. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97168. // Draw order
  97169. engine.setStencilMask(0x00);
  97170. engine.setStencilBuffer(true);
  97171. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97172. // 2 passes inner outer
  97173. if (this.outerGlow) {
  97174. effect.setFloat("offset", 0);
  97175. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97176. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97177. }
  97178. if (this.innerGlow) {
  97179. effect.setFloat("offset", 1);
  97180. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  97181. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97182. }
  97183. // Restore Cache
  97184. engine.setStencilFunction(previousStencilFunction);
  97185. engine.setStencilMask(previousStencilMask);
  97186. engine.setStencilBuffer(previousStencilBuffer);
  97187. engine.setStencilOperationPass(previousStencilOperationPass);
  97188. engine.setStencilOperationFail(previousStencilOperationFail);
  97189. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  97190. engine.setStencilFunctionReference(previousStencilReference);
  97191. };
  97192. /**
  97193. * Returns true if the layer contains information to display, otherwise false.
  97194. */
  97195. HighlightLayer.prototype.shouldRender = function () {
  97196. if (_super.prototype.shouldRender.call(this)) {
  97197. return this._meshes ? true : false;
  97198. }
  97199. return false;
  97200. };
  97201. /**
  97202. * Returns true if the mesh should render, otherwise false.
  97203. * @param mesh The mesh to render
  97204. * @returns true if it should render otherwise false
  97205. */
  97206. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  97207. // Excluded Mesh
  97208. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  97209. return false;
  97210. }
  97211. ;
  97212. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97213. return false;
  97214. }
  97215. return true;
  97216. };
  97217. /**
  97218. * Sets the required values for both the emissive texture and and the main color.
  97219. */
  97220. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97221. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97222. if (highlightLayerMesh) {
  97223. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  97224. }
  97225. else {
  97226. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97227. }
  97228. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97229. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97230. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  97231. }
  97232. else {
  97233. this._emissiveTextureAndColor.texture = null;
  97234. }
  97235. };
  97236. /**
  97237. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  97238. * @param mesh The mesh to exclude from the highlight layer
  97239. */
  97240. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  97241. if (!this._excludedMeshes) {
  97242. return;
  97243. }
  97244. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97245. if (!meshExcluded) {
  97246. this._excludedMeshes[mesh.uniqueId] = {
  97247. mesh: mesh,
  97248. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  97249. mesh.getEngine().setStencilBuffer(false);
  97250. }),
  97251. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  97252. mesh.getEngine().setStencilBuffer(true);
  97253. }),
  97254. };
  97255. }
  97256. };
  97257. /**
  97258. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  97259. * @param mesh The mesh to highlight
  97260. */
  97261. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  97262. if (!this._excludedMeshes) {
  97263. return;
  97264. }
  97265. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97266. if (meshExcluded) {
  97267. if (meshExcluded.beforeRender) {
  97268. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  97269. }
  97270. if (meshExcluded.afterRender) {
  97271. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  97272. }
  97273. }
  97274. this._excludedMeshes[mesh.uniqueId] = null;
  97275. };
  97276. /**
  97277. * Determine if a given mesh will be highlighted by the current HighlightLayer
  97278. * @param mesh mesh to test
  97279. * @returns true if the mesh will be highlighted by the current HighlightLayer
  97280. */
  97281. HighlightLayer.prototype.hasMesh = function (mesh) {
  97282. if (!this._meshes) {
  97283. return false;
  97284. }
  97285. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97286. return false;
  97287. }
  97288. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97289. };
  97290. /**
  97291. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97292. * @param mesh The mesh to highlight
  97293. * @param color The color of the highlight
  97294. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97295. */
  97296. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97297. var _this = this;
  97298. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97299. if (!this._meshes) {
  97300. return;
  97301. }
  97302. var meshHighlight = this._meshes[mesh.uniqueId];
  97303. if (meshHighlight) {
  97304. meshHighlight.color = color;
  97305. }
  97306. else {
  97307. this._meshes[mesh.uniqueId] = {
  97308. mesh: mesh,
  97309. color: color,
  97310. // Lambda required for capture due to Observable this context
  97311. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97312. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97313. _this._defaultStencilReference(mesh);
  97314. }
  97315. else {
  97316. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97317. }
  97318. }),
  97319. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97320. glowEmissiveOnly: glowEmissiveOnly
  97321. };
  97322. mesh.onDisposeObservable.add(function () {
  97323. _this._disposeMesh(mesh);
  97324. });
  97325. }
  97326. this._shouldRender = true;
  97327. };
  97328. /**
  97329. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97330. * @param mesh The mesh to highlight
  97331. */
  97332. HighlightLayer.prototype.removeMesh = function (mesh) {
  97333. if (!this._meshes) {
  97334. return;
  97335. }
  97336. var meshHighlight = this._meshes[mesh.uniqueId];
  97337. if (meshHighlight) {
  97338. if (meshHighlight.observerHighlight) {
  97339. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97340. }
  97341. if (meshHighlight.observerDefault) {
  97342. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97343. }
  97344. delete this._meshes[mesh.uniqueId];
  97345. }
  97346. this._shouldRender = false;
  97347. for (var meshHighlightToCheck in this._meshes) {
  97348. if (this._meshes[meshHighlightToCheck]) {
  97349. this._shouldRender = true;
  97350. break;
  97351. }
  97352. }
  97353. };
  97354. /**
  97355. * Force the stencil to the normal expected value for none glowing parts
  97356. */
  97357. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97358. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97359. };
  97360. /**
  97361. * Free any resources and references associated to a mesh.
  97362. * Internal use
  97363. * @param mesh The mesh to free.
  97364. */
  97365. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97366. this.removeMesh(mesh);
  97367. this.removeExcludedMesh(mesh);
  97368. };
  97369. /**
  97370. * Dispose the highlight layer and free resources.
  97371. */
  97372. HighlightLayer.prototype.dispose = function () {
  97373. if (this._meshes) {
  97374. // Clean mesh references
  97375. for (var id in this._meshes) {
  97376. var meshHighlight = this._meshes[id];
  97377. if (meshHighlight && meshHighlight.mesh) {
  97378. if (meshHighlight.observerHighlight) {
  97379. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97380. }
  97381. if (meshHighlight.observerDefault) {
  97382. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97383. }
  97384. }
  97385. }
  97386. this._meshes = null;
  97387. }
  97388. if (this._excludedMeshes) {
  97389. for (var id in this._excludedMeshes) {
  97390. var meshHighlight = this._excludedMeshes[id];
  97391. if (meshHighlight) {
  97392. if (meshHighlight.beforeRender) {
  97393. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97394. }
  97395. if (meshHighlight.afterRender) {
  97396. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97397. }
  97398. }
  97399. }
  97400. this._excludedMeshes = null;
  97401. }
  97402. _super.prototype.dispose.call(this);
  97403. };
  97404. /**
  97405. * Gets the class name of the effect layer
  97406. * @returns the string with the class name of the effect layer
  97407. */
  97408. HighlightLayer.prototype.getClassName = function () {
  97409. return "HighlightLayer";
  97410. };
  97411. /**
  97412. * Serializes this Highlight layer
  97413. * @returns a serialized Highlight layer object
  97414. */
  97415. HighlightLayer.prototype.serialize = function () {
  97416. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97417. serializationObject.customType = "BABYLON.HighlightLayer";
  97418. // Highlighted meshes
  97419. serializationObject.meshes = [];
  97420. if (this._meshes) {
  97421. for (var m in this._meshes) {
  97422. var mesh = this._meshes[m];
  97423. if (mesh) {
  97424. serializationObject.meshes.push({
  97425. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97426. color: mesh.color.asArray(),
  97427. meshId: mesh.mesh.id
  97428. });
  97429. }
  97430. }
  97431. }
  97432. // Excluded meshes
  97433. serializationObject.excludedMeshes = [];
  97434. if (this._excludedMeshes) {
  97435. for (var e in this._excludedMeshes) {
  97436. var excludedMesh = this._excludedMeshes[e];
  97437. if (excludedMesh) {
  97438. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97439. }
  97440. }
  97441. }
  97442. return serializationObject;
  97443. };
  97444. /**
  97445. * Creates a Highlight layer from parsed Highlight layer data
  97446. * @param parsedHightlightLayer defines the Highlight layer data
  97447. * @param scene defines the current scene
  97448. * @param rootUrl defines the root URL containing the Highlight layer information
  97449. * @returns a parsed Highlight layer
  97450. */
  97451. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97452. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97453. var index;
  97454. // Excluded meshes
  97455. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97456. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97457. if (mesh) {
  97458. hl.addExcludedMesh(mesh);
  97459. }
  97460. }
  97461. // Included meshes
  97462. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97463. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97464. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97465. if (mesh) {
  97466. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97467. }
  97468. }
  97469. return hl;
  97470. };
  97471. /**
  97472. * Effect Name of the highlight layer.
  97473. */
  97474. HighlightLayer.EffectName = "HighlightLayer";
  97475. /**
  97476. * The neutral color used during the preparation of the glow effect.
  97477. * This is black by default as the blend operation is a blend operation.
  97478. */
  97479. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97480. /**
  97481. * Stencil value used for glowing meshes.
  97482. */
  97483. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97484. /**
  97485. * Stencil value used for the other meshes in the scene.
  97486. */
  97487. HighlightLayer.NormalMeshStencilReference = 0x01;
  97488. __decorate([
  97489. BABYLON.serialize()
  97490. ], HighlightLayer.prototype, "innerGlow", void 0);
  97491. __decorate([
  97492. BABYLON.serialize()
  97493. ], HighlightLayer.prototype, "outerGlow", void 0);
  97494. __decorate([
  97495. BABYLON.serialize()
  97496. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97497. __decorate([
  97498. BABYLON.serialize()
  97499. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97500. __decorate([
  97501. BABYLON.serialize("options")
  97502. ], HighlightLayer.prototype, "_options", void 0);
  97503. return HighlightLayer;
  97504. }(BABYLON.EffectLayer));
  97505. BABYLON.HighlightLayer = HighlightLayer;
  97506. })(BABYLON || (BABYLON = {}));
  97507. //# sourceMappingURL=babylon.highlightLayer.js.map
  97508. var BABYLON;
  97509. (function (BABYLON) {
  97510. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97511. for (var index = 0; index < this.effectLayers.length; index++) {
  97512. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97513. return this.effectLayers[index];
  97514. }
  97515. }
  97516. return null;
  97517. };
  97518. /**
  97519. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97520. *
  97521. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97522. * glowy meshes to your scene.
  97523. *
  97524. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97525. */
  97526. var GlowLayer = /** @class */ (function (_super) {
  97527. __extends(GlowLayer, _super);
  97528. /**
  97529. * Instantiates a new glow Layer and references it to the scene.
  97530. * @param name The name of the layer
  97531. * @param scene The scene to use the layer in
  97532. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97533. */
  97534. function GlowLayer(name, scene, options) {
  97535. var _this = _super.call(this, name, scene) || this;
  97536. _this._intensity = 1.0;
  97537. _this._includedOnlyMeshes = [];
  97538. _this._excludedMeshes = [];
  97539. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97540. // Adapt options
  97541. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  97542. // Initialize the layer
  97543. _this._init({
  97544. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97545. camera: _this._options.camera,
  97546. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97547. mainTextureRatio: _this._options.mainTextureRatio,
  97548. renderingGroupId: _this._options.renderingGroupId
  97549. });
  97550. return _this;
  97551. }
  97552. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97553. /**
  97554. * Gets the kernel size of the blur.
  97555. */
  97556. get: function () {
  97557. return this._horizontalBlurPostprocess1.kernel;
  97558. },
  97559. /**
  97560. * Sets the kernel size of the blur.
  97561. */
  97562. set: function (value) {
  97563. this._horizontalBlurPostprocess1.kernel = value;
  97564. this._verticalBlurPostprocess1.kernel = value;
  97565. this._horizontalBlurPostprocess2.kernel = value;
  97566. this._verticalBlurPostprocess2.kernel = value;
  97567. },
  97568. enumerable: true,
  97569. configurable: true
  97570. });
  97571. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97572. /**
  97573. * Gets the glow intensity.
  97574. */
  97575. get: function () {
  97576. return this._intensity;
  97577. },
  97578. /**
  97579. * Sets the glow intensity.
  97580. */
  97581. set: function (value) {
  97582. this._intensity = value;
  97583. },
  97584. enumerable: true,
  97585. configurable: true
  97586. });
  97587. /**
  97588. * Get the effect name of the layer.
  97589. * @return The effect name
  97590. */
  97591. GlowLayer.prototype.getEffectName = function () {
  97592. return GlowLayer.EffectName;
  97593. };
  97594. /**
  97595. * Create the merge effect. This is the shader use to blit the information back
  97596. * to the main canvas at the end of the scene rendering.
  97597. */
  97598. GlowLayer.prototype._createMergeEffect = function () {
  97599. // Effect
  97600. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97601. };
  97602. /**
  97603. * Creates the render target textures and post processes used in the glow layer.
  97604. */
  97605. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97606. var _this = this;
  97607. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97608. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97609. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97610. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97611. var textureType = 0;
  97612. if (this._engine.getCaps().textureHalfFloatRender) {
  97613. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97614. }
  97615. else {
  97616. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97617. }
  97618. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97619. width: blurTextureWidth,
  97620. height: blurTextureHeight
  97621. }, this._scene, false, true, textureType);
  97622. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97623. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97624. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97625. this._blurTexture1.renderParticles = false;
  97626. this._blurTexture1.ignoreCameraViewport = true;
  97627. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97628. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97629. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97630. width: blurTextureWidth2,
  97631. height: blurTextureHeight2
  97632. }, this._scene, false, true, textureType);
  97633. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97634. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97635. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97636. this._blurTexture2.renderParticles = false;
  97637. this._blurTexture2.ignoreCameraViewport = true;
  97638. this._textures = [this._blurTexture1, this._blurTexture2];
  97639. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97640. width: blurTextureWidth,
  97641. height: blurTextureHeight
  97642. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97643. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97644. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97645. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97646. effect.setTexture("textureSampler", _this._mainTexture);
  97647. });
  97648. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97649. width: blurTextureWidth,
  97650. height: blurTextureHeight
  97651. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97652. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97653. width: blurTextureWidth2,
  97654. height: blurTextureHeight2
  97655. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97656. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97657. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97658. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97659. effect.setTexture("textureSampler", _this._blurTexture1);
  97660. });
  97661. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97662. width: blurTextureWidth2,
  97663. height: blurTextureHeight2
  97664. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97665. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97666. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97667. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97668. this._mainTexture.samples = this._options.mainTextureSamples;
  97669. this._mainTexture.onAfterUnbindObservable.add(function () {
  97670. var internalTexture = _this._blurTexture1.getInternalTexture();
  97671. if (internalTexture) {
  97672. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97673. internalTexture = _this._blurTexture2.getInternalTexture();
  97674. if (internalTexture) {
  97675. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97676. }
  97677. }
  97678. });
  97679. // Prevent autoClear.
  97680. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97681. };
  97682. /**
  97683. * Checks for the readiness of the element composing the layer.
  97684. * @param subMesh the mesh to check for
  97685. * @param useInstances specify wether or not to use instances to render the mesh
  97686. * @param emissiveTexture the associated emissive texture used to generate the glow
  97687. * @return true if ready otherwise, false
  97688. */
  97689. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97690. var material = subMesh.getMaterial();
  97691. var mesh = subMesh.getRenderingMesh();
  97692. if (!material || !mesh) {
  97693. return false;
  97694. }
  97695. var emissiveTexture = material.emissiveTexture;
  97696. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97697. };
  97698. /**
  97699. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97700. */
  97701. GlowLayer.prototype.needStencil = function () {
  97702. return false;
  97703. };
  97704. /**
  97705. * Implementation specific of rendering the generating effect on the main canvas.
  97706. * @param effect The effect used to render through
  97707. */
  97708. GlowLayer.prototype._internalRender = function (effect) {
  97709. // Texture
  97710. effect.setTexture("textureSampler", this._blurTexture1);
  97711. effect.setTexture("textureSampler2", this._blurTexture2);
  97712. effect.setFloat("offset", this._intensity);
  97713. // Cache
  97714. var engine = this._engine;
  97715. var previousStencilBuffer = engine.getStencilBuffer();
  97716. // Draw order
  97717. engine.setStencilBuffer(false);
  97718. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97719. // Draw order
  97720. engine.setStencilBuffer(previousStencilBuffer);
  97721. };
  97722. /**
  97723. * Sets the required values for both the emissive texture and and the main color.
  97724. */
  97725. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97726. var textureLevel = 1.0;
  97727. if (this.customEmissiveTextureSelector) {
  97728. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97729. }
  97730. else {
  97731. if (material) {
  97732. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97733. if (this._emissiveTextureAndColor.texture) {
  97734. textureLevel = this._emissiveTextureAndColor.texture.level;
  97735. }
  97736. }
  97737. else {
  97738. this._emissiveTextureAndColor.texture = null;
  97739. }
  97740. }
  97741. if (this.customEmissiveColorSelector) {
  97742. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97743. }
  97744. else {
  97745. if (material.emissiveColor) {
  97746. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97747. }
  97748. else {
  97749. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97750. }
  97751. }
  97752. };
  97753. /**
  97754. * Returns true if the mesh should render, otherwise false.
  97755. * @param mesh The mesh to render
  97756. * @returns true if it should render otherwise false
  97757. */
  97758. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97759. return this.hasMesh(mesh);
  97760. };
  97761. /**
  97762. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97763. * @param mesh The mesh to exclude from the glow layer
  97764. */
  97765. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97766. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97767. this._excludedMeshes.push(mesh.uniqueId);
  97768. }
  97769. };
  97770. /**
  97771. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97772. * @param mesh The mesh to remove
  97773. */
  97774. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97775. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97776. if (index !== -1) {
  97777. this._excludedMeshes.splice(index, 1);
  97778. }
  97779. };
  97780. /**
  97781. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97782. * @param mesh The mesh to include in the glow layer
  97783. */
  97784. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97785. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97786. this._includedOnlyMeshes.push(mesh.uniqueId);
  97787. }
  97788. };
  97789. /**
  97790. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97791. * @param mesh The mesh to remove
  97792. */
  97793. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97794. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97795. if (index !== -1) {
  97796. this._includedOnlyMeshes.splice(index, 1);
  97797. }
  97798. };
  97799. /**
  97800. * Determine if a given mesh will be used in the glow layer
  97801. * @param mesh The mesh to test
  97802. * @returns true if the mesh will be highlighted by the current glow layer
  97803. */
  97804. GlowLayer.prototype.hasMesh = function (mesh) {
  97805. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97806. return false;
  97807. }
  97808. // Included Mesh
  97809. if (this._includedOnlyMeshes.length) {
  97810. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97811. }
  97812. ;
  97813. // Excluded Mesh
  97814. if (this._excludedMeshes.length) {
  97815. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97816. }
  97817. ;
  97818. return true;
  97819. };
  97820. /**
  97821. * Free any resources and references associated to a mesh.
  97822. * Internal use
  97823. * @param mesh The mesh to free.
  97824. */
  97825. GlowLayer.prototype._disposeMesh = function (mesh) {
  97826. this.removeIncludedOnlyMesh(mesh);
  97827. this.removeExcludedMesh(mesh);
  97828. };
  97829. /**
  97830. * Gets the class name of the effect layer
  97831. * @returns the string with the class name of the effect layer
  97832. */
  97833. GlowLayer.prototype.getClassName = function () {
  97834. return "GlowLayer";
  97835. };
  97836. /**
  97837. * Serializes this glow layer
  97838. * @returns a serialized glow layer object
  97839. */
  97840. GlowLayer.prototype.serialize = function () {
  97841. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97842. serializationObject.customType = "BABYLON.GlowLayer";
  97843. var index;
  97844. // Included meshes
  97845. serializationObject.includedMeshes = [];
  97846. if (this._includedOnlyMeshes.length) {
  97847. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97848. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97849. if (mesh) {
  97850. serializationObject.includedMeshes.push(mesh.id);
  97851. }
  97852. }
  97853. }
  97854. // Excluded meshes
  97855. serializationObject.excludedMeshes = [];
  97856. if (this._excludedMeshes.length) {
  97857. for (index = 0; index < this._excludedMeshes.length; index++) {
  97858. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97859. if (mesh) {
  97860. serializationObject.excludedMeshes.push(mesh.id);
  97861. }
  97862. }
  97863. }
  97864. return serializationObject;
  97865. };
  97866. /**
  97867. * Creates a Glow Layer from parsed glow layer data
  97868. * @param parsedGlowLayer defines glow layer data
  97869. * @param scene defines the current scene
  97870. * @param rootUrl defines the root URL containing the glow layer information
  97871. * @returns a parsed Glow Layer
  97872. */
  97873. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97874. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97875. var index;
  97876. // Excluded meshes
  97877. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97878. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97879. if (mesh) {
  97880. gl.addExcludedMesh(mesh);
  97881. }
  97882. }
  97883. // Included meshes
  97884. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  97885. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  97886. if (mesh) {
  97887. gl.addIncludedOnlyMesh(mesh);
  97888. }
  97889. }
  97890. return gl;
  97891. };
  97892. /**
  97893. * Effect Name of the layer.
  97894. */
  97895. GlowLayer.EffectName = "GlowLayer";
  97896. /**
  97897. * The default blur kernel size used for the glow.
  97898. */
  97899. GlowLayer.DefaultBlurKernelSize = 32;
  97900. /**
  97901. * The default texture size ratio used for the glow.
  97902. */
  97903. GlowLayer.DefaultTextureRatio = 0.5;
  97904. __decorate([
  97905. BABYLON.serialize()
  97906. ], GlowLayer.prototype, "blurKernelSize", null);
  97907. __decorate([
  97908. BABYLON.serialize()
  97909. ], GlowLayer.prototype, "intensity", null);
  97910. __decorate([
  97911. BABYLON.serialize("options")
  97912. ], GlowLayer.prototype, "_options", void 0);
  97913. return GlowLayer;
  97914. }(BABYLON.EffectLayer));
  97915. BABYLON.GlowLayer = GlowLayer;
  97916. })(BABYLON || (BABYLON = {}));
  97917. //# sourceMappingURL=babylon.glowLayer.js.map
  97918. var BABYLON;
  97919. (function (BABYLON) {
  97920. /**
  97921. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97922. */
  97923. var AssetTaskState;
  97924. (function (AssetTaskState) {
  97925. /**
  97926. * Initialization
  97927. */
  97928. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97929. /**
  97930. * Running
  97931. */
  97932. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97933. /**
  97934. * Done
  97935. */
  97936. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97937. /**
  97938. * Error
  97939. */
  97940. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97941. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97942. /**
  97943. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97944. */
  97945. var AbstractAssetTask = /** @class */ (function () {
  97946. /**
  97947. * Creates a new {BABYLON.AssetsManager}
  97948. * @param name defines the name of the task
  97949. */
  97950. function AbstractAssetTask(
  97951. /**
  97952. * Task name
  97953. */ name) {
  97954. this.name = name;
  97955. this._isCompleted = false;
  97956. this._taskState = AssetTaskState.INIT;
  97957. }
  97958. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  97959. /**
  97960. * Get if the task is completed
  97961. */
  97962. get: function () {
  97963. return this._isCompleted;
  97964. },
  97965. enumerable: true,
  97966. configurable: true
  97967. });
  97968. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  97969. /**
  97970. * Gets the current state of the task
  97971. */
  97972. get: function () {
  97973. return this._taskState;
  97974. },
  97975. enumerable: true,
  97976. configurable: true
  97977. });
  97978. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  97979. /**
  97980. * Gets the current error object (if task is in error)
  97981. */
  97982. get: function () {
  97983. return this._errorObject;
  97984. },
  97985. enumerable: true,
  97986. configurable: true
  97987. });
  97988. /**
  97989. * Internal only
  97990. * @hidden
  97991. */
  97992. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  97993. if (this._errorObject) {
  97994. return;
  97995. }
  97996. this._errorObject = {
  97997. message: message,
  97998. exception: exception
  97999. };
  98000. };
  98001. /**
  98002. * Execute the current task
  98003. * @param scene defines the scene where you want your assets to be loaded
  98004. * @param onSuccess is a callback called when the task is successfully executed
  98005. * @param onError is a callback called if an error occurs
  98006. */
  98007. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98008. var _this = this;
  98009. this._taskState = AssetTaskState.RUNNING;
  98010. this.runTask(scene, function () {
  98011. _this.onDoneCallback(onSuccess, onError);
  98012. }, function (msg, exception) {
  98013. _this.onErrorCallback(onError, msg, exception);
  98014. });
  98015. };
  98016. /**
  98017. * Execute the current task
  98018. * @param scene defines the scene where you want your assets to be loaded
  98019. * @param onSuccess is a callback called when the task is successfully executed
  98020. * @param onError is a callback called if an error occurs
  98021. */
  98022. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98023. throw new Error("runTask is not implemented");
  98024. };
  98025. /**
  98026. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98027. * This can be used with failed tasks that have the reason for failure fixed.
  98028. */
  98029. AbstractAssetTask.prototype.reset = function () {
  98030. this._taskState = AssetTaskState.INIT;
  98031. };
  98032. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98033. this._taskState = AssetTaskState.ERROR;
  98034. this._errorObject = {
  98035. message: message,
  98036. exception: exception
  98037. };
  98038. if (this.onError) {
  98039. this.onError(this, message, exception);
  98040. }
  98041. onError();
  98042. };
  98043. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98044. try {
  98045. this._taskState = AssetTaskState.DONE;
  98046. this._isCompleted = true;
  98047. if (this.onSuccess) {
  98048. this.onSuccess(this);
  98049. }
  98050. onSuccess();
  98051. }
  98052. catch (e) {
  98053. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98054. }
  98055. };
  98056. return AbstractAssetTask;
  98057. }());
  98058. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98059. /**
  98060. * Class used to share progress information about assets loading
  98061. */
  98062. var AssetsProgressEvent = /** @class */ (function () {
  98063. /**
  98064. * Creates a {BABYLON.AssetsProgressEvent}
  98065. * @param remainingCount defines the number of remaining tasks to process
  98066. * @param totalCount defines the total number of tasks
  98067. * @param task defines the task that was just processed
  98068. */
  98069. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98070. this.remainingCount = remainingCount;
  98071. this.totalCount = totalCount;
  98072. this.task = task;
  98073. }
  98074. return AssetsProgressEvent;
  98075. }());
  98076. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98077. /**
  98078. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98079. */
  98080. var MeshAssetTask = /** @class */ (function (_super) {
  98081. __extends(MeshAssetTask, _super);
  98082. /**
  98083. * Creates a new {BABYLON.MeshAssetTask}
  98084. * @param name defines the name of the task
  98085. * @param meshesNames defines the list of mesh's names you want to load
  98086. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98087. * @param sceneFilename defines the filename of the scene to load from
  98088. */
  98089. function MeshAssetTask(
  98090. /**
  98091. * Defines the name of the task
  98092. */
  98093. name,
  98094. /**
  98095. * Defines the list of mesh's names you want to load
  98096. */
  98097. meshesNames,
  98098. /**
  98099. * Defines the root url to use as a base to load your meshes and associated resources
  98100. */
  98101. rootUrl,
  98102. /**
  98103. * Defines the filename of the scene to load from
  98104. */
  98105. sceneFilename) {
  98106. var _this = _super.call(this, name) || this;
  98107. _this.name = name;
  98108. _this.meshesNames = meshesNames;
  98109. _this.rootUrl = rootUrl;
  98110. _this.sceneFilename = sceneFilename;
  98111. return _this;
  98112. }
  98113. /**
  98114. * Execute the current task
  98115. * @param scene defines the scene where you want your assets to be loaded
  98116. * @param onSuccess is a callback called when the task is successfully executed
  98117. * @param onError is a callback called if an error occurs
  98118. */
  98119. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98120. var _this = this;
  98121. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98122. _this.loadedMeshes = meshes;
  98123. _this.loadedParticleSystems = particleSystems;
  98124. _this.loadedSkeletons = skeletons;
  98125. onSuccess();
  98126. }, null, function (scene, message, exception) {
  98127. onError(message, exception);
  98128. });
  98129. };
  98130. return MeshAssetTask;
  98131. }(AbstractAssetTask));
  98132. BABYLON.MeshAssetTask = MeshAssetTask;
  98133. /**
  98134. * Define a task used by {BABYLON.AssetsManager} to load text content
  98135. */
  98136. var TextFileAssetTask = /** @class */ (function (_super) {
  98137. __extends(TextFileAssetTask, _super);
  98138. /**
  98139. * Creates a new TextFileAssetTask object
  98140. * @param name defines the name of the task
  98141. * @param url defines the location of the file to load
  98142. */
  98143. function TextFileAssetTask(
  98144. /**
  98145. * Defines the name of the task
  98146. */
  98147. name,
  98148. /**
  98149. * Defines the location of the file to load
  98150. */
  98151. url) {
  98152. var _this = _super.call(this, name) || this;
  98153. _this.name = name;
  98154. _this.url = url;
  98155. return _this;
  98156. }
  98157. /**
  98158. * Execute the current task
  98159. * @param scene defines the scene where you want your assets to be loaded
  98160. * @param onSuccess is a callback called when the task is successfully executed
  98161. * @param onError is a callback called if an error occurs
  98162. */
  98163. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98164. var _this = this;
  98165. scene._loadFile(this.url, function (data) {
  98166. _this.text = data;
  98167. onSuccess();
  98168. }, undefined, false, false, function (request, exception) {
  98169. if (request) {
  98170. onError(request.status + " " + request.statusText, exception);
  98171. }
  98172. });
  98173. };
  98174. return TextFileAssetTask;
  98175. }(AbstractAssetTask));
  98176. BABYLON.TextFileAssetTask = TextFileAssetTask;
  98177. /**
  98178. * Define a task used by {BABYLON.AssetsManager} to load binary data
  98179. */
  98180. var BinaryFileAssetTask = /** @class */ (function (_super) {
  98181. __extends(BinaryFileAssetTask, _super);
  98182. /**
  98183. * Creates a new BinaryFileAssetTask object
  98184. * @param name defines the name of the new task
  98185. * @param url defines the location of the file to load
  98186. */
  98187. function BinaryFileAssetTask(
  98188. /**
  98189. * Defines the name of the task
  98190. */
  98191. name,
  98192. /**
  98193. * Defines the location of the file to load
  98194. */
  98195. url) {
  98196. var _this = _super.call(this, name) || this;
  98197. _this.name = name;
  98198. _this.url = url;
  98199. return _this;
  98200. }
  98201. /**
  98202. * Execute the current task
  98203. * @param scene defines the scene where you want your assets to be loaded
  98204. * @param onSuccess is a callback called when the task is successfully executed
  98205. * @param onError is a callback called if an error occurs
  98206. */
  98207. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98208. var _this = this;
  98209. scene._loadFile(this.url, function (data) {
  98210. _this.data = data;
  98211. onSuccess();
  98212. }, undefined, true, true, function (request, exception) {
  98213. if (request) {
  98214. onError(request.status + " " + request.statusText, exception);
  98215. }
  98216. });
  98217. };
  98218. return BinaryFileAssetTask;
  98219. }(AbstractAssetTask));
  98220. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  98221. /**
  98222. * Define a task used by {BABYLON.AssetsManager} to load images
  98223. */
  98224. var ImageAssetTask = /** @class */ (function (_super) {
  98225. __extends(ImageAssetTask, _super);
  98226. /**
  98227. * Creates a new ImageAssetTask
  98228. * @param name defines the name of the task
  98229. * @param url defines the location of the image to load
  98230. */
  98231. function ImageAssetTask(
  98232. /**
  98233. * Defines the name of the task
  98234. */
  98235. name,
  98236. /**
  98237. * Defines the location of the image to load
  98238. */
  98239. url) {
  98240. var _this = _super.call(this, name) || this;
  98241. _this.name = name;
  98242. _this.url = url;
  98243. return _this;
  98244. }
  98245. /**
  98246. * Execute the current task
  98247. * @param scene defines the scene where you want your assets to be loaded
  98248. * @param onSuccess is a callback called when the task is successfully executed
  98249. * @param onError is a callback called if an error occurs
  98250. */
  98251. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98252. var _this = this;
  98253. var img = new Image();
  98254. BABYLON.Tools.SetCorsBehavior(this.url, img);
  98255. img.onload = function () {
  98256. _this.image = img;
  98257. onSuccess();
  98258. };
  98259. img.onerror = function (err) {
  98260. onError("Error loading image", err);
  98261. };
  98262. img.src = this.url;
  98263. };
  98264. return ImageAssetTask;
  98265. }(AbstractAssetTask));
  98266. BABYLON.ImageAssetTask = ImageAssetTask;
  98267. /**
  98268. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  98269. */
  98270. var TextureAssetTask = /** @class */ (function (_super) {
  98271. __extends(TextureAssetTask, _super);
  98272. /**
  98273. * Creates a new TextureAssetTask object
  98274. * @param name defines the name of the task
  98275. * @param url defines the location of the file to load
  98276. * @param noMipmap defines if mipmap should not be generated (default is false)
  98277. * @param invertY defines if texture must be inverted on Y axis (default is false)
  98278. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98279. */
  98280. function TextureAssetTask(
  98281. /**
  98282. * Defines the name of the task
  98283. */
  98284. name,
  98285. /**
  98286. * Defines the location of the file to load
  98287. */
  98288. url,
  98289. /**
  98290. * Defines if mipmap should not be generated (default is false)
  98291. */
  98292. noMipmap,
  98293. /**
  98294. * Defines if texture must be inverted on Y axis (default is false)
  98295. */
  98296. invertY,
  98297. /**
  98298. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98299. */
  98300. samplingMode) {
  98301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98302. var _this = _super.call(this, name) || this;
  98303. _this.name = name;
  98304. _this.url = url;
  98305. _this.noMipmap = noMipmap;
  98306. _this.invertY = invertY;
  98307. _this.samplingMode = samplingMode;
  98308. return _this;
  98309. }
  98310. /**
  98311. * Execute the current task
  98312. * @param scene defines the scene where you want your assets to be loaded
  98313. * @param onSuccess is a callback called when the task is successfully executed
  98314. * @param onError is a callback called if an error occurs
  98315. */
  98316. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98317. var onload = function () {
  98318. onSuccess();
  98319. };
  98320. var onerror = function (message, exception) {
  98321. onError(message, exception);
  98322. };
  98323. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98324. };
  98325. return TextureAssetTask;
  98326. }(AbstractAssetTask));
  98327. BABYLON.TextureAssetTask = TextureAssetTask;
  98328. /**
  98329. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98330. */
  98331. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98332. __extends(CubeTextureAssetTask, _super);
  98333. /**
  98334. * Creates a new CubeTextureAssetTask
  98335. * @param name defines the name of the task
  98336. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98337. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98338. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98339. * @param files defines the explicit list of files (undefined by default)
  98340. */
  98341. function CubeTextureAssetTask(
  98342. /**
  98343. * Defines the name of the task
  98344. */
  98345. name,
  98346. /**
  98347. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98348. */
  98349. url,
  98350. /**
  98351. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98352. */
  98353. extensions,
  98354. /**
  98355. * Defines if mipmaps should not be generated (default is false)
  98356. */
  98357. noMipmap,
  98358. /**
  98359. * Defines the explicit list of files (undefined by default)
  98360. */
  98361. files) {
  98362. var _this = _super.call(this, name) || this;
  98363. _this.name = name;
  98364. _this.url = url;
  98365. _this.extensions = extensions;
  98366. _this.noMipmap = noMipmap;
  98367. _this.files = files;
  98368. return _this;
  98369. }
  98370. /**
  98371. * Execute the current task
  98372. * @param scene defines the scene where you want your assets to be loaded
  98373. * @param onSuccess is a callback called when the task is successfully executed
  98374. * @param onError is a callback called if an error occurs
  98375. */
  98376. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98377. var onload = function () {
  98378. onSuccess();
  98379. };
  98380. var onerror = function (message, exception) {
  98381. onError(message, exception);
  98382. };
  98383. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98384. };
  98385. return CubeTextureAssetTask;
  98386. }(AbstractAssetTask));
  98387. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98388. /**
  98389. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98390. */
  98391. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98392. __extends(HDRCubeTextureAssetTask, _super);
  98393. /**
  98394. * Creates a new HDRCubeTextureAssetTask object
  98395. * @param name defines the name of the task
  98396. * @param url defines the location of the file to load
  98397. * @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.
  98398. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98399. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98400. * @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)
  98401. * @param reserved Internal use only
  98402. */
  98403. function HDRCubeTextureAssetTask(
  98404. /**
  98405. * Defines the name of the task
  98406. */
  98407. name,
  98408. /**
  98409. * Defines the location of the file to load
  98410. */
  98411. url,
  98412. /**
  98413. * Defines the desired size (the more it increases the longer the generation will be)
  98414. */
  98415. size,
  98416. /**
  98417. * Defines if mipmaps should not be generated (default is false)
  98418. */
  98419. noMipmap,
  98420. /**
  98421. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98422. */
  98423. generateHarmonics,
  98424. /**
  98425. * 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)
  98426. */
  98427. gammaSpace,
  98428. /**
  98429. * Internal Use Only
  98430. */
  98431. reserved) {
  98432. if (noMipmap === void 0) { noMipmap = false; }
  98433. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98434. if (gammaSpace === void 0) { gammaSpace = false; }
  98435. if (reserved === void 0) { reserved = false; }
  98436. var _this = _super.call(this, name) || this;
  98437. _this.name = name;
  98438. _this.url = url;
  98439. _this.size = size;
  98440. _this.noMipmap = noMipmap;
  98441. _this.generateHarmonics = generateHarmonics;
  98442. _this.gammaSpace = gammaSpace;
  98443. _this.reserved = reserved;
  98444. return _this;
  98445. }
  98446. /**
  98447. * Execute the current task
  98448. * @param scene defines the scene where you want your assets to be loaded
  98449. * @param onSuccess is a callback called when the task is successfully executed
  98450. * @param onError is a callback called if an error occurs
  98451. */
  98452. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98453. var onload = function () {
  98454. onSuccess();
  98455. };
  98456. var onerror = function (message, exception) {
  98457. onError(message, exception);
  98458. };
  98459. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98460. };
  98461. return HDRCubeTextureAssetTask;
  98462. }(AbstractAssetTask));
  98463. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98464. /**
  98465. * This class can be used to easily import assets into a scene
  98466. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98467. */
  98468. var AssetsManager = /** @class */ (function () {
  98469. /**
  98470. * Creates a new AssetsManager
  98471. * @param scene defines the scene to work on
  98472. */
  98473. function AssetsManager(scene) {
  98474. this._isLoading = false;
  98475. this._tasks = new Array();
  98476. this._waitingTasksCount = 0;
  98477. this._totalTasksCount = 0;
  98478. /**
  98479. * Observable called when all tasks are processed
  98480. */
  98481. this.onTaskSuccessObservable = new BABYLON.Observable();
  98482. /**
  98483. * Observable called when a task had an error
  98484. */
  98485. this.onTaskErrorObservable = new BABYLON.Observable();
  98486. /**
  98487. * Observable called when a task is successful
  98488. */
  98489. this.onTasksDoneObservable = new BABYLON.Observable();
  98490. /**
  98491. * Observable called when a task is done (whatever the result is)
  98492. */
  98493. this.onProgressObservable = new BABYLON.Observable();
  98494. /**
  98495. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98496. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98497. */
  98498. this.useDefaultLoadingScreen = true;
  98499. this._scene = scene;
  98500. }
  98501. /**
  98502. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98503. * @param taskName defines the name of the new task
  98504. * @param meshesNames defines the name of meshes to load
  98505. * @param rootUrl defines the root url to use to locate files
  98506. * @param sceneFilename defines the filename of the scene file
  98507. * @returns a new {BABYLON.MeshAssetTask} object
  98508. */
  98509. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98510. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98511. this._tasks.push(task);
  98512. return task;
  98513. };
  98514. /**
  98515. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98516. * @param taskName defines the name of the new task
  98517. * @param url defines the url of the file to load
  98518. * @returns a new {BABYLON.TextFileAssetTask} object
  98519. */
  98520. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98521. var task = new TextFileAssetTask(taskName, url);
  98522. this._tasks.push(task);
  98523. return task;
  98524. };
  98525. /**
  98526. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98527. * @param taskName defines the name of the new task
  98528. * @param url defines the url of the file to load
  98529. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98530. */
  98531. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98532. var task = new BinaryFileAssetTask(taskName, url);
  98533. this._tasks.push(task);
  98534. return task;
  98535. };
  98536. /**
  98537. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98538. * @param taskName defines the name of the new task
  98539. * @param url defines the url of the file to load
  98540. * @returns a new {BABYLON.ImageAssetTask} object
  98541. */
  98542. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98543. var task = new ImageAssetTask(taskName, url);
  98544. this._tasks.push(task);
  98545. return task;
  98546. };
  98547. /**
  98548. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98549. * @param taskName defines the name of the new task
  98550. * @param url defines the url of the file to load
  98551. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98552. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98553. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98554. * @returns a new {BABYLON.TextureAssetTask} object
  98555. */
  98556. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98558. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98559. this._tasks.push(task);
  98560. return task;
  98561. };
  98562. /**
  98563. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98564. * @param taskName defines the name of the new task
  98565. * @param url defines the url of the file to load
  98566. * @param extensions defines the extension to use to load the cube map (can be null)
  98567. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98568. * @param files defines the list of files to load (can be null)
  98569. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98570. */
  98571. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98572. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98573. this._tasks.push(task);
  98574. return task;
  98575. };
  98576. /**
  98577. *
  98578. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98579. * @param taskName defines the name of the new task
  98580. * @param url defines the url of the file to load
  98581. * @param size defines the size you want for the cubemap (can be null)
  98582. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98583. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98584. * @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)
  98585. * @param reserved Internal use only
  98586. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98587. */
  98588. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98589. if (noMipmap === void 0) { noMipmap = false; }
  98590. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98591. if (gammaSpace === void 0) { gammaSpace = false; }
  98592. if (reserved === void 0) { reserved = false; }
  98593. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98594. this._tasks.push(task);
  98595. return task;
  98596. };
  98597. /**
  98598. * Remove a task from the assets manager.
  98599. * @param task the task to remove
  98600. */
  98601. AssetsManager.prototype.removeTask = function (task) {
  98602. var index = this._tasks.indexOf(task);
  98603. if (index > -1) {
  98604. this._tasks.splice(index, 1);
  98605. }
  98606. };
  98607. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98608. this._waitingTasksCount--;
  98609. try {
  98610. if (this.onProgress) {
  98611. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98612. }
  98613. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98614. }
  98615. catch (e) {
  98616. BABYLON.Tools.Error("Error running progress callbacks.");
  98617. console.log(e);
  98618. }
  98619. if (this._waitingTasksCount === 0) {
  98620. try {
  98621. if (this.onFinish) {
  98622. this.onFinish(this._tasks);
  98623. }
  98624. // Let's remove successfull tasks
  98625. var currentTasks = this._tasks.slice();
  98626. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98627. var task = currentTasks_1[_i];
  98628. if (task.taskState === AssetTaskState.DONE) {
  98629. var index = this._tasks.indexOf(task);
  98630. if (index > -1) {
  98631. this._tasks.splice(index, 1);
  98632. }
  98633. }
  98634. }
  98635. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98636. }
  98637. catch (e) {
  98638. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98639. console.log(e);
  98640. }
  98641. this._isLoading = false;
  98642. this._scene.getEngine().hideLoadingUI();
  98643. }
  98644. };
  98645. AssetsManager.prototype._runTask = function (task) {
  98646. var _this = this;
  98647. var done = function () {
  98648. try {
  98649. if (_this.onTaskSuccess) {
  98650. _this.onTaskSuccess(task);
  98651. }
  98652. _this.onTaskSuccessObservable.notifyObservers(task);
  98653. _this._decreaseWaitingTasksCount(task);
  98654. }
  98655. catch (e) {
  98656. error("Error executing task success callbacks", e);
  98657. }
  98658. };
  98659. var error = function (message, exception) {
  98660. task._setErrorObject(message, exception);
  98661. if (_this.onTaskError) {
  98662. _this.onTaskError(task);
  98663. }
  98664. _this.onTaskErrorObservable.notifyObservers(task);
  98665. _this._decreaseWaitingTasksCount(task);
  98666. };
  98667. task.run(this._scene, done, error);
  98668. };
  98669. /**
  98670. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98671. * @return the current instance of the {BABYLON.AssetsManager}
  98672. */
  98673. AssetsManager.prototype.reset = function () {
  98674. this._isLoading = false;
  98675. this._tasks = new Array();
  98676. return this;
  98677. };
  98678. /**
  98679. * Start the loading process
  98680. * @return the current instance of the {BABYLON.AssetsManager}
  98681. */
  98682. AssetsManager.prototype.load = function () {
  98683. if (this._isLoading) {
  98684. return this;
  98685. }
  98686. this._isLoading = true;
  98687. this._waitingTasksCount = this._tasks.length;
  98688. this._totalTasksCount = this._tasks.length;
  98689. if (this._waitingTasksCount === 0) {
  98690. this._isLoading = false;
  98691. if (this.onFinish) {
  98692. this.onFinish(this._tasks);
  98693. }
  98694. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98695. return this;
  98696. }
  98697. if (this.useDefaultLoadingScreen) {
  98698. this._scene.getEngine().displayLoadingUI();
  98699. }
  98700. for (var index = 0; index < this._tasks.length; index++) {
  98701. var task = this._tasks[index];
  98702. if (task.taskState === AssetTaskState.INIT) {
  98703. this._runTask(task);
  98704. }
  98705. }
  98706. return this;
  98707. };
  98708. return AssetsManager;
  98709. }());
  98710. BABYLON.AssetsManager = AssetsManager;
  98711. })(BABYLON || (BABYLON = {}));
  98712. //# sourceMappingURL=babylon.assetsManager.js.map
  98713. var BABYLON;
  98714. (function (BABYLON) {
  98715. var serializedGeometries = [];
  98716. var serializeGeometry = function (geometry, serializationGeometries) {
  98717. if (serializedGeometries[geometry.id]) {
  98718. return;
  98719. }
  98720. if (geometry.doNotSerialize) {
  98721. return;
  98722. }
  98723. if (geometry instanceof BABYLON.BoxGeometry) {
  98724. serializationGeometries.boxes.push(geometry.serialize());
  98725. }
  98726. else if (geometry instanceof BABYLON.SphereGeometry) {
  98727. serializationGeometries.spheres.push(geometry.serialize());
  98728. }
  98729. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98730. serializationGeometries.cylinders.push(geometry.serialize());
  98731. }
  98732. else if (geometry instanceof BABYLON.TorusGeometry) {
  98733. serializationGeometries.toruses.push(geometry.serialize());
  98734. }
  98735. else if (geometry instanceof BABYLON.GroundGeometry) {
  98736. serializationGeometries.grounds.push(geometry.serialize());
  98737. }
  98738. else if (geometry instanceof BABYLON.Plane) {
  98739. serializationGeometries.planes.push(geometry.serialize());
  98740. }
  98741. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98742. serializationGeometries.torusKnots.push(geometry.serialize());
  98743. }
  98744. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98745. throw new Error("Unknown primitive type");
  98746. }
  98747. else {
  98748. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98749. }
  98750. serializedGeometries[geometry.id] = true;
  98751. };
  98752. var serializeMesh = function (mesh, serializationScene) {
  98753. var serializationObject = {};
  98754. // Geometry
  98755. var geometry = mesh._geometry;
  98756. if (geometry) {
  98757. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98758. // 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
  98759. serializeGeometry(geometry, serializationScene.geometries);
  98760. }
  98761. }
  98762. // Custom
  98763. if (mesh.serialize) {
  98764. mesh.serialize(serializationObject);
  98765. }
  98766. return serializationObject;
  98767. };
  98768. var finalizeSingleMesh = function (mesh, serializationObject) {
  98769. //only works if the mesh is already loaded
  98770. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98771. //serialize material
  98772. if (mesh.material) {
  98773. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98774. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98775. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98776. serializationObject.multiMaterials.push(mesh.material.serialize());
  98777. }
  98778. }
  98779. else {
  98780. serializationObject.materials = serializationObject.materials || [];
  98781. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98782. serializationObject.materials.push(mesh.material.serialize());
  98783. }
  98784. }
  98785. }
  98786. //serialize geometry
  98787. var geometry = mesh._geometry;
  98788. if (geometry) {
  98789. if (!serializationObject.geometries) {
  98790. serializationObject.geometries = {};
  98791. serializationObject.geometries.boxes = [];
  98792. serializationObject.geometries.spheres = [];
  98793. serializationObject.geometries.cylinders = [];
  98794. serializationObject.geometries.toruses = [];
  98795. serializationObject.geometries.grounds = [];
  98796. serializationObject.geometries.planes = [];
  98797. serializationObject.geometries.torusKnots = [];
  98798. serializationObject.geometries.vertexData = [];
  98799. }
  98800. serializeGeometry(geometry, serializationObject.geometries);
  98801. }
  98802. // Skeletons
  98803. if (mesh.skeleton) {
  98804. serializationObject.skeletons = serializationObject.skeletons || [];
  98805. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98806. }
  98807. //serialize the actual mesh
  98808. serializationObject.meshes = serializationObject.meshes || [];
  98809. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98810. }
  98811. };
  98812. var SceneSerializer = /** @class */ (function () {
  98813. function SceneSerializer() {
  98814. }
  98815. SceneSerializer.ClearCache = function () {
  98816. serializedGeometries = [];
  98817. };
  98818. SceneSerializer.Serialize = function (scene) {
  98819. var serializationObject = {};
  98820. SceneSerializer.ClearCache();
  98821. // Scene
  98822. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98823. serializationObject.autoClear = scene.autoClear;
  98824. serializationObject.clearColor = scene.clearColor.asArray();
  98825. serializationObject.ambientColor = scene.ambientColor.asArray();
  98826. serializationObject.gravity = scene.gravity.asArray();
  98827. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98828. serializationObject.workerCollisions = scene.workerCollisions;
  98829. // Fog
  98830. if (scene.fogMode && scene.fogMode !== 0) {
  98831. serializationObject.fogMode = scene.fogMode;
  98832. serializationObject.fogColor = scene.fogColor.asArray();
  98833. serializationObject.fogStart = scene.fogStart;
  98834. serializationObject.fogEnd = scene.fogEnd;
  98835. serializationObject.fogDensity = scene.fogDensity;
  98836. }
  98837. //Physics
  98838. if (scene.isPhysicsEnabled()) {
  98839. var physicEngine = scene.getPhysicsEngine();
  98840. if (physicEngine) {
  98841. serializationObject.physicsEnabled = true;
  98842. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98843. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98844. }
  98845. }
  98846. // Metadata
  98847. if (scene.metadata) {
  98848. serializationObject.metadata = scene.metadata;
  98849. }
  98850. // Morph targets
  98851. serializationObject.morphTargetManagers = [];
  98852. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98853. var abstractMesh = _a[_i];
  98854. var manager = abstractMesh.morphTargetManager;
  98855. if (manager) {
  98856. serializationObject.morphTargetManagers.push(manager.serialize());
  98857. }
  98858. }
  98859. // Lights
  98860. serializationObject.lights = [];
  98861. var index;
  98862. var light;
  98863. for (index = 0; index < scene.lights.length; index++) {
  98864. light = scene.lights[index];
  98865. if (!light.doNotSerialize) {
  98866. serializationObject.lights.push(light.serialize());
  98867. }
  98868. }
  98869. // Cameras
  98870. serializationObject.cameras = [];
  98871. for (index = 0; index < scene.cameras.length; index++) {
  98872. var camera = scene.cameras[index];
  98873. if (!camera.doNotSerialize) {
  98874. serializationObject.cameras.push(camera.serialize());
  98875. }
  98876. }
  98877. if (scene.activeCamera) {
  98878. serializationObject.activeCameraID = scene.activeCamera.id;
  98879. }
  98880. // Animations
  98881. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  98882. // Materials
  98883. serializationObject.materials = [];
  98884. serializationObject.multiMaterials = [];
  98885. var material;
  98886. for (index = 0; index < scene.materials.length; index++) {
  98887. material = scene.materials[index];
  98888. if (!material.doNotSerialize) {
  98889. serializationObject.materials.push(material.serialize());
  98890. }
  98891. }
  98892. // MultiMaterials
  98893. serializationObject.multiMaterials = [];
  98894. for (index = 0; index < scene.multiMaterials.length; index++) {
  98895. var multiMaterial = scene.multiMaterials[index];
  98896. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98897. }
  98898. // Environment texture
  98899. if (scene.environmentTexture) {
  98900. serializationObject.environmentTexture = scene.environmentTexture.name;
  98901. }
  98902. // Skeletons
  98903. serializationObject.skeletons = [];
  98904. for (index = 0; index < scene.skeletons.length; index++) {
  98905. var skeleton = scene.skeletons[index];
  98906. if (!skeleton.doNotSerialize) {
  98907. serializationObject.skeletons.push(skeleton.serialize());
  98908. }
  98909. }
  98910. // Transform nodes
  98911. serializationObject.transformNodes = [];
  98912. for (index = 0; index < scene.transformNodes.length; index++) {
  98913. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98914. }
  98915. // Geometries
  98916. serializationObject.geometries = {};
  98917. serializationObject.geometries.boxes = [];
  98918. serializationObject.geometries.spheres = [];
  98919. serializationObject.geometries.cylinders = [];
  98920. serializationObject.geometries.toruses = [];
  98921. serializationObject.geometries.grounds = [];
  98922. serializationObject.geometries.planes = [];
  98923. serializationObject.geometries.torusKnots = [];
  98924. serializationObject.geometries.vertexData = [];
  98925. serializedGeometries = [];
  98926. var geometries = scene.getGeometries();
  98927. for (index = 0; index < geometries.length; index++) {
  98928. var geometry = geometries[index];
  98929. if (geometry.isReady()) {
  98930. serializeGeometry(geometry, serializationObject.geometries);
  98931. }
  98932. }
  98933. // Meshes
  98934. serializationObject.meshes = [];
  98935. for (index = 0; index < scene.meshes.length; index++) {
  98936. var abstractMesh = scene.meshes[index];
  98937. if (abstractMesh instanceof BABYLON.Mesh) {
  98938. var mesh = abstractMesh;
  98939. if (!mesh.doNotSerialize) {
  98940. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98941. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98942. }
  98943. }
  98944. }
  98945. }
  98946. // Particles Systems
  98947. serializationObject.particleSystems = [];
  98948. for (index = 0; index < scene.particleSystems.length; index++) {
  98949. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98950. }
  98951. // Shadows
  98952. serializationObject.shadowGenerators = [];
  98953. for (index = 0; index < scene.lights.length; index++) {
  98954. light = scene.lights[index];
  98955. var shadowGenerator = light.getShadowGenerator();
  98956. if (shadowGenerator) {
  98957. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98958. }
  98959. }
  98960. // Action Manager
  98961. if (scene.actionManager) {
  98962. serializationObject.actions = scene.actionManager.serialize("scene");
  98963. }
  98964. // Audio
  98965. serializationObject.sounds = [];
  98966. for (index = 0; index < scene.soundTracks.length; index++) {
  98967. var soundtrack = scene.soundTracks[index];
  98968. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  98969. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  98970. }
  98971. }
  98972. // Components
  98973. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  98974. var component = _c[_b];
  98975. component.serialize(serializationObject);
  98976. }
  98977. return serializationObject;
  98978. };
  98979. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  98980. if (withParents === void 0) { withParents = false; }
  98981. if (withChildren === void 0) { withChildren = false; }
  98982. var serializationObject = {};
  98983. SceneSerializer.ClearCache();
  98984. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  98985. if (withParents || withChildren) {
  98986. //deliberate for loop! not for each, appended should be processed as well.
  98987. for (var i = 0; i < toSerialize.length; ++i) {
  98988. if (withChildren) {
  98989. toSerialize[i].getDescendants().forEach(function (node) {
  98990. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  98991. toSerialize.push(node);
  98992. }
  98993. });
  98994. }
  98995. //make sure the array doesn't contain the object already
  98996. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  98997. toSerialize.push(toSerialize[i].parent);
  98998. }
  98999. }
  99000. }
  99001. toSerialize.forEach(function (mesh) {
  99002. finalizeSingleMesh(mesh, serializationObject);
  99003. });
  99004. return serializationObject;
  99005. };
  99006. return SceneSerializer;
  99007. }());
  99008. BABYLON.SceneSerializer = SceneSerializer;
  99009. })(BABYLON || (BABYLON = {}));
  99010. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99011. var BABYLON;
  99012. (function (BABYLON) {
  99013. var ReflectionProbe = /** @class */ (function () {
  99014. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99015. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99016. var _this = this;
  99017. this.name = name;
  99018. this._viewMatrix = BABYLON.Matrix.Identity();
  99019. this._target = BABYLON.Vector3.Zero();
  99020. this._add = BABYLON.Vector3.Zero();
  99021. this._invertYAxis = false;
  99022. this.position = BABYLON.Vector3.Zero();
  99023. this._scene = scene;
  99024. this._scene.reflectionProbes.push(this);
  99025. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99026. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99027. switch (faceIndex) {
  99028. case 0:
  99029. _this._add.copyFromFloats(1, 0, 0);
  99030. break;
  99031. case 1:
  99032. _this._add.copyFromFloats(-1, 0, 0);
  99033. break;
  99034. case 2:
  99035. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99036. break;
  99037. case 3:
  99038. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99039. break;
  99040. case 4:
  99041. _this._add.copyFromFloats(0, 0, 1);
  99042. break;
  99043. case 5:
  99044. _this._add.copyFromFloats(0, 0, -1);
  99045. break;
  99046. }
  99047. if (_this._attachedMesh) {
  99048. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99049. }
  99050. _this.position.addToRef(_this._add, _this._target);
  99051. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99052. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99053. scene._forcedViewPosition = _this.position;
  99054. });
  99055. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99056. scene._forcedViewPosition = null;
  99057. scene.updateTransformMatrix(true);
  99058. });
  99059. if (scene.activeCamera) {
  99060. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99061. }
  99062. }
  99063. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99064. get: function () {
  99065. return this._renderTargetTexture.samples;
  99066. },
  99067. set: function (value) {
  99068. this._renderTargetTexture.samples = value;
  99069. },
  99070. enumerable: true,
  99071. configurable: true
  99072. });
  99073. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99074. get: function () {
  99075. return this._renderTargetTexture.refreshRate;
  99076. },
  99077. set: function (value) {
  99078. this._renderTargetTexture.refreshRate = value;
  99079. },
  99080. enumerable: true,
  99081. configurable: true
  99082. });
  99083. ReflectionProbe.prototype.getScene = function () {
  99084. return this._scene;
  99085. };
  99086. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99087. get: function () {
  99088. return this._renderTargetTexture;
  99089. },
  99090. enumerable: true,
  99091. configurable: true
  99092. });
  99093. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99094. get: function () {
  99095. return this._renderTargetTexture.renderList;
  99096. },
  99097. enumerable: true,
  99098. configurable: true
  99099. });
  99100. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99101. this._attachedMesh = mesh;
  99102. };
  99103. /**
  99104. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99105. *
  99106. * @param renderingGroupId The rendering group id corresponding to its index
  99107. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99108. */
  99109. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99110. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99111. };
  99112. ReflectionProbe.prototype.dispose = function () {
  99113. var index = this._scene.reflectionProbes.indexOf(this);
  99114. if (index !== -1) {
  99115. // Remove from the scene if found
  99116. this._scene.reflectionProbes.splice(index, 1);
  99117. }
  99118. if (this._renderTargetTexture) {
  99119. this._renderTargetTexture.dispose();
  99120. this._renderTargetTexture = null;
  99121. }
  99122. };
  99123. return ReflectionProbe;
  99124. }());
  99125. BABYLON.ReflectionProbe = ReflectionProbe;
  99126. })(BABYLON || (BABYLON = {}));
  99127. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99128. var BABYLON;
  99129. (function (BABYLON) {
  99130. /**
  99131. * Defines the layer scene component responsible to manage any layers
  99132. * in a given scene.
  99133. */
  99134. var LayerSceneComponent = /** @class */ (function () {
  99135. /**
  99136. * Creates a new instance of the component for the given scene
  99137. * @param scene Defines the scene to register the component in
  99138. */
  99139. function LayerSceneComponent(scene) {
  99140. /**
  99141. * The component name helpfull to identify the component in the list of scene components.
  99142. */
  99143. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99144. this.scene = scene;
  99145. this._engine = scene.getEngine();
  99146. scene.layers = new Array();
  99147. }
  99148. /**
  99149. * Registers the component in a given scene
  99150. */
  99151. LayerSceneComponent.prototype.register = function () {
  99152. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99153. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99154. };
  99155. /**
  99156. * Rebuilds the elements related to this component in case of
  99157. * context lost for instance.
  99158. */
  99159. LayerSceneComponent.prototype.rebuild = function () {
  99160. var layers = this.scene.layers;
  99161. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99162. var layer = layers_1[_i];
  99163. layer._rebuild();
  99164. }
  99165. };
  99166. /**
  99167. * Disposes the component and the associated ressources.
  99168. */
  99169. LayerSceneComponent.prototype.dispose = function () {
  99170. var layers = this.scene.layers;
  99171. while (layers.length) {
  99172. layers[0].dispose();
  99173. }
  99174. };
  99175. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  99176. var layers = this.scene.layers;
  99177. if (layers.length) {
  99178. this._engine.setDepthBuffer(false);
  99179. var cameraLayerMask = camera.layerMask;
  99180. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99181. var layer = layers_2[_i];
  99182. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  99183. layer.render();
  99184. }
  99185. }
  99186. this._engine.setDepthBuffer(true);
  99187. }
  99188. };
  99189. LayerSceneComponent.prototype._drawBackground = function (camera) {
  99190. this._draw(camera, true);
  99191. };
  99192. LayerSceneComponent.prototype._drawForeground = function (camera) {
  99193. this._draw(camera, false);
  99194. };
  99195. return LayerSceneComponent;
  99196. }());
  99197. BABYLON.LayerSceneComponent = LayerSceneComponent;
  99198. })(BABYLON || (BABYLON = {}));
  99199. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  99200. var BABYLON;
  99201. (function (BABYLON) {
  99202. var Layer = /** @class */ (function () {
  99203. function Layer(name, imgUrl, scene, isBackground, color) {
  99204. this.name = name;
  99205. this.scale = new BABYLON.Vector2(1, 1);
  99206. this.offset = new BABYLON.Vector2(0, 0);
  99207. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  99208. this.layerMask = 0x0FFFFFFF;
  99209. this._vertexBuffers = {};
  99210. // Events
  99211. /**
  99212. * An event triggered when the layer is disposed.
  99213. */
  99214. this.onDisposeObservable = new BABYLON.Observable();
  99215. /**
  99216. * An event triggered before rendering the scene
  99217. */
  99218. this.onBeforeRenderObservable = new BABYLON.Observable();
  99219. /**
  99220. * An event triggered after rendering the scene
  99221. */
  99222. this.onAfterRenderObservable = new BABYLON.Observable();
  99223. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  99224. this.isBackground = isBackground === undefined ? true : isBackground;
  99225. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  99226. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  99227. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  99228. if (!layerComponent) {
  99229. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  99230. this._scene._addComponent(layerComponent);
  99231. }
  99232. this._scene.layers.push(this);
  99233. var engine = this._scene.getEngine();
  99234. // VBO
  99235. var vertices = [];
  99236. vertices.push(1, 1);
  99237. vertices.push(-1, 1);
  99238. vertices.push(-1, -1);
  99239. vertices.push(1, -1);
  99240. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99241. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99242. this._createIndexBuffer();
  99243. // Effects
  99244. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  99245. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  99246. }
  99247. Object.defineProperty(Layer.prototype, "onDispose", {
  99248. set: function (callback) {
  99249. if (this._onDisposeObserver) {
  99250. this.onDisposeObservable.remove(this._onDisposeObserver);
  99251. }
  99252. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  99253. },
  99254. enumerable: true,
  99255. configurable: true
  99256. });
  99257. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99258. set: function (callback) {
  99259. if (this._onBeforeRenderObserver) {
  99260. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99261. }
  99262. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99263. },
  99264. enumerable: true,
  99265. configurable: true
  99266. });
  99267. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99268. set: function (callback) {
  99269. if (this._onAfterRenderObserver) {
  99270. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99271. }
  99272. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99273. },
  99274. enumerable: true,
  99275. configurable: true
  99276. });
  99277. Layer.prototype._createIndexBuffer = function () {
  99278. var engine = this._scene.getEngine();
  99279. // Indices
  99280. var indices = [];
  99281. indices.push(0);
  99282. indices.push(1);
  99283. indices.push(2);
  99284. indices.push(0);
  99285. indices.push(2);
  99286. indices.push(3);
  99287. this._indexBuffer = engine.createIndexBuffer(indices);
  99288. };
  99289. Layer.prototype._rebuild = function () {
  99290. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99291. if (vb) {
  99292. vb._rebuild();
  99293. }
  99294. this._createIndexBuffer();
  99295. };
  99296. Layer.prototype.render = function () {
  99297. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99298. // Check
  99299. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99300. return;
  99301. var engine = this._scene.getEngine();
  99302. this.onBeforeRenderObservable.notifyObservers(this);
  99303. // Render
  99304. engine.enableEffect(currentEffect);
  99305. engine.setState(false);
  99306. // Texture
  99307. currentEffect.setTexture("textureSampler", this.texture);
  99308. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99309. // Color
  99310. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99311. // Scale / offset
  99312. currentEffect.setVector2("offset", this.offset);
  99313. currentEffect.setVector2("scale", this.scale);
  99314. // VBOs
  99315. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99316. // Draw order
  99317. if (!this.alphaTest) {
  99318. engine.setAlphaMode(this.alphaBlendingMode);
  99319. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99320. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99321. }
  99322. else {
  99323. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99324. }
  99325. this.onAfterRenderObservable.notifyObservers(this);
  99326. };
  99327. Layer.prototype.dispose = function () {
  99328. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99329. if (vertexBuffer) {
  99330. vertexBuffer.dispose();
  99331. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99332. }
  99333. if (this._indexBuffer) {
  99334. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99335. this._indexBuffer = null;
  99336. }
  99337. if (this.texture) {
  99338. this.texture.dispose();
  99339. this.texture = null;
  99340. }
  99341. // Remove from scene
  99342. var index = this._scene.layers.indexOf(this);
  99343. this._scene.layers.splice(index, 1);
  99344. // Callback
  99345. this.onDisposeObservable.notifyObservers(this);
  99346. this.onDisposeObservable.clear();
  99347. this.onAfterRenderObservable.clear();
  99348. this.onBeforeRenderObservable.clear();
  99349. };
  99350. return Layer;
  99351. }());
  99352. BABYLON.Layer = Layer;
  99353. })(BABYLON || (BABYLON = {}));
  99354. //# sourceMappingURL=babylon.layer.js.map
  99355. var BABYLON;
  99356. (function (BABYLON) {
  99357. var TextureTools = /** @class */ (function () {
  99358. function TextureTools() {
  99359. }
  99360. /**
  99361. * Uses the GPU to create a copy texture rescaled at a given size
  99362. * @param texture Texture to copy from
  99363. * @param width Desired width
  99364. * @param height Desired height
  99365. * @return Generated texture
  99366. */
  99367. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99368. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99369. var scene = texture.getScene();
  99370. var engine = scene.getEngine();
  99371. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99372. rtt.wrapU = texture.wrapU;
  99373. rtt.wrapV = texture.wrapV;
  99374. rtt.uOffset = texture.uOffset;
  99375. rtt.vOffset = texture.vOffset;
  99376. rtt.uScale = texture.uScale;
  99377. rtt.vScale = texture.vScale;
  99378. rtt.uAng = texture.uAng;
  99379. rtt.vAng = texture.vAng;
  99380. rtt.wAng = texture.wAng;
  99381. rtt.coordinatesIndex = texture.coordinatesIndex;
  99382. rtt.level = texture.level;
  99383. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99384. rtt._texture.isReady = false;
  99385. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99386. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99387. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99388. passPostProcess.getEffect().executeWhenCompiled(function () {
  99389. passPostProcess.onApply = function (effect) {
  99390. effect.setTexture("textureSampler", texture);
  99391. };
  99392. var internalTexture = rtt.getInternalTexture();
  99393. if (internalTexture) {
  99394. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99395. engine.unBindFramebuffer(internalTexture);
  99396. rtt.disposeFramebufferObjects();
  99397. passPostProcess.dispose();
  99398. internalTexture.isReady = true;
  99399. }
  99400. });
  99401. return rtt;
  99402. };
  99403. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99404. if (!scene._environmentBRDFTexture) {
  99405. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99406. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99407. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99408. scene._environmentBRDFTexture = texture;
  99409. }
  99410. return scene._environmentBRDFTexture;
  99411. };
  99412. TextureTools._environmentBR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AM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  99413. return TextureTools;
  99414. }());
  99415. BABYLON.TextureTools = TextureTools;
  99416. })(BABYLON || (BABYLON = {}));
  99417. //# sourceMappingURL=babylon.textureTools.js.map
  99418. var BABYLON;
  99419. (function (BABYLON) {
  99420. var FramingBehavior = /** @class */ (function () {
  99421. function FramingBehavior() {
  99422. this._mode = FramingBehavior.FitFrustumSidesMode;
  99423. this._radiusScale = 1.0;
  99424. this._positionScale = 0.5;
  99425. this._defaultElevation = 0.3;
  99426. this._elevationReturnTime = 1500;
  99427. this._elevationReturnWaitTime = 1000;
  99428. this._zoomStopsAnimation = false;
  99429. this._framingTime = 1500;
  99430. this._isPointerDown = false;
  99431. this._lastInteractionTime = -Infinity;
  99432. // Framing control
  99433. this._animatables = new Array();
  99434. this._betaIsAnimating = false;
  99435. }
  99436. Object.defineProperty(FramingBehavior.prototype, "name", {
  99437. get: function () {
  99438. return "Framing";
  99439. },
  99440. enumerable: true,
  99441. configurable: true
  99442. });
  99443. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99444. /**
  99445. * Gets current mode used by the behavior.
  99446. */
  99447. get: function () {
  99448. return this._mode;
  99449. },
  99450. /**
  99451. * Sets the current mode used by the behavior
  99452. */
  99453. set: function (mode) {
  99454. this._mode = mode;
  99455. },
  99456. enumerable: true,
  99457. configurable: true
  99458. });
  99459. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99460. /**
  99461. * Gets the scale applied to the radius
  99462. */
  99463. get: function () {
  99464. return this._radiusScale;
  99465. },
  99466. /**
  99467. * Sets the scale applied to the radius (1 by default)
  99468. */
  99469. set: function (radius) {
  99470. this._radiusScale = radius;
  99471. },
  99472. enumerable: true,
  99473. configurable: true
  99474. });
  99475. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99476. /**
  99477. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99478. */
  99479. get: function () {
  99480. return this._positionScale;
  99481. },
  99482. /**
  99483. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99484. */
  99485. set: function (scale) {
  99486. this._positionScale = scale;
  99487. },
  99488. enumerable: true,
  99489. configurable: true
  99490. });
  99491. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99492. /**
  99493. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99494. * behaviour is triggered, in radians.
  99495. */
  99496. get: function () {
  99497. return this._defaultElevation;
  99498. },
  99499. /**
  99500. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99501. * behaviour is triggered, in radians.
  99502. */
  99503. set: function (elevation) {
  99504. this._defaultElevation = elevation;
  99505. },
  99506. enumerable: true,
  99507. configurable: true
  99508. });
  99509. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99510. /**
  99511. * Gets the time (in milliseconds) taken to return to the default beta position.
  99512. * Negative value indicates camera should not return to default.
  99513. */
  99514. get: function () {
  99515. return this._elevationReturnTime;
  99516. },
  99517. /**
  99518. * Sets the time (in milliseconds) taken to return to the default beta position.
  99519. * Negative value indicates camera should not return to default.
  99520. */
  99521. set: function (speed) {
  99522. this._elevationReturnTime = speed;
  99523. },
  99524. enumerable: true,
  99525. configurable: true
  99526. });
  99527. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99528. /**
  99529. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99530. */
  99531. get: function () {
  99532. return this._elevationReturnWaitTime;
  99533. },
  99534. /**
  99535. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99536. */
  99537. set: function (time) {
  99538. this._elevationReturnWaitTime = time;
  99539. },
  99540. enumerable: true,
  99541. configurable: true
  99542. });
  99543. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99544. /**
  99545. * Gets the flag that indicates if user zooming should stop animation.
  99546. */
  99547. get: function () {
  99548. return this._zoomStopsAnimation;
  99549. },
  99550. /**
  99551. * Sets the flag that indicates if user zooming should stop animation.
  99552. */
  99553. set: function (flag) {
  99554. this._zoomStopsAnimation = flag;
  99555. },
  99556. enumerable: true,
  99557. configurable: true
  99558. });
  99559. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99560. /**
  99561. * Gets the transition time when framing the mesh, in milliseconds
  99562. */
  99563. get: function () {
  99564. return this._framingTime;
  99565. },
  99566. /**
  99567. * Sets the transition time when framing the mesh, in milliseconds
  99568. */
  99569. set: function (time) {
  99570. this._framingTime = time;
  99571. },
  99572. enumerable: true,
  99573. configurable: true
  99574. });
  99575. FramingBehavior.prototype.init = function () {
  99576. // Do notihng
  99577. };
  99578. FramingBehavior.prototype.attach = function (camera) {
  99579. var _this = this;
  99580. this._attachedCamera = camera;
  99581. var scene = this._attachedCamera.getScene();
  99582. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99583. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99584. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99585. _this._isPointerDown = true;
  99586. return;
  99587. }
  99588. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99589. _this._isPointerDown = false;
  99590. }
  99591. });
  99592. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99593. if (mesh) {
  99594. _this.zoomOnMesh(mesh);
  99595. }
  99596. });
  99597. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99598. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99599. _this._applyUserInteraction();
  99600. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99601. // back to the default position after a given timeout
  99602. _this._maintainCameraAboveGround();
  99603. });
  99604. };
  99605. FramingBehavior.prototype.detach = function () {
  99606. if (!this._attachedCamera) {
  99607. return;
  99608. }
  99609. var scene = this._attachedCamera.getScene();
  99610. if (this._onPrePointerObservableObserver) {
  99611. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99612. }
  99613. if (this._onAfterCheckInputsObserver) {
  99614. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99615. }
  99616. if (this._onMeshTargetChangedObserver) {
  99617. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99618. }
  99619. this._attachedCamera = null;
  99620. };
  99621. /**
  99622. * Targets the given mesh and updates zoom level accordingly.
  99623. * @param mesh The mesh to target.
  99624. * @param radius Optional. If a cached radius position already exists, overrides default.
  99625. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99626. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99627. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99628. */
  99629. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99630. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99631. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99632. mesh.computeWorldMatrix(true);
  99633. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99634. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99635. };
  99636. /**
  99637. * Targets the given mesh with its children and updates zoom level accordingly.
  99638. * @param mesh The mesh to target.
  99639. * @param radius Optional. If a cached radius position already exists, overrides default.
  99640. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99641. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99642. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99643. */
  99644. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99645. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99646. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99647. mesh.computeWorldMatrix(true);
  99648. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99649. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99650. };
  99651. /**
  99652. * Targets the given meshes with their children and updates zoom level accordingly.
  99653. * @param meshes The mesh to target.
  99654. * @param radius Optional. If a cached radius position already exists, overrides default.
  99655. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99656. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99657. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99658. */
  99659. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99660. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99661. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99662. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99663. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99664. for (var i = 0; i < meshes.length; i++) {
  99665. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99666. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99667. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99668. }
  99669. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99670. };
  99671. /**
  99672. * Targets the given mesh and updates zoom level accordingly.
  99673. * @param mesh The mesh to target.
  99674. * @param radius Optional. If a cached radius position already exists, overrides default.
  99675. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99676. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99677. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99678. */
  99679. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99680. var _this = this;
  99681. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99682. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99683. var zoomTarget;
  99684. if (!this._attachedCamera) {
  99685. return;
  99686. }
  99687. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99688. var bottom = minimumWorld.y;
  99689. var top = maximumWorld.y;
  99690. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99691. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99692. if (focusOnOriginXZ) {
  99693. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99694. }
  99695. else {
  99696. var centerWorld = minimumWorld.add(radiusWorld);
  99697. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99698. }
  99699. if (!this._vectorTransition) {
  99700. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99701. }
  99702. this._betaIsAnimating = true;
  99703. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99704. if (animatable) {
  99705. this._animatables.push(animatable);
  99706. }
  99707. // sets the radius and lower radius bounds
  99708. // Small delta ensures camera is not always at lower zoom limit.
  99709. var radius = 0;
  99710. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99711. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99712. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99713. radius = position;
  99714. }
  99715. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99716. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99717. if (this._attachedCamera.lowerRadiusLimit === null) {
  99718. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99719. }
  99720. }
  99721. // Set sensibilities
  99722. var extend = maximumWorld.subtract(minimumWorld).length();
  99723. this._attachedCamera.panningSensibility = 5000 / extend;
  99724. this._attachedCamera.wheelPrecision = 100 / radius;
  99725. // transition to new radius
  99726. if (!this._radiusTransition) {
  99727. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99728. }
  99729. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99730. _this.stopAllAnimations();
  99731. if (onAnimationEnd) {
  99732. onAnimationEnd();
  99733. }
  99734. if (_this._attachedCamera) {
  99735. _this._attachedCamera.storeState();
  99736. }
  99737. });
  99738. if (animatable) {
  99739. this._animatables.push(animatable);
  99740. }
  99741. };
  99742. /**
  99743. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99744. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99745. * frustum width.
  99746. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99747. * to fully enclose the mesh in the viewing frustum.
  99748. */
  99749. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99750. var size = maximumWorld.subtract(minimumWorld);
  99751. var boxVectorGlobalDiagonal = size.length();
  99752. var frustumSlope = this._getFrustumSlope();
  99753. // Formula for setting distance
  99754. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99755. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99756. // Horizon distance
  99757. var radius = radiusWithoutFraming * this._radiusScale;
  99758. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99759. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99760. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99761. var camera = this._attachedCamera;
  99762. if (!camera) {
  99763. return 0;
  99764. }
  99765. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99766. // Don't exceed the requested limit
  99767. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99768. }
  99769. // Don't exceed the upper radius limit
  99770. if (camera.upperRadiusLimit) {
  99771. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99772. }
  99773. return distance;
  99774. };
  99775. /**
  99776. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99777. * is automatically returned to its default position (expected to be above ground plane).
  99778. */
  99779. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99780. var _this = this;
  99781. if (this._elevationReturnTime < 0) {
  99782. return;
  99783. }
  99784. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99785. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99786. var limitBeta = Math.PI * 0.5;
  99787. // Bring the camera back up if below the ground plane
  99788. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99789. this._betaIsAnimating = true;
  99790. //Transition to new position
  99791. this.stopAllAnimations();
  99792. if (!this._betaTransition) {
  99793. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99794. }
  99795. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99796. _this._clearAnimationLocks();
  99797. _this.stopAllAnimations();
  99798. });
  99799. if (animatabe) {
  99800. this._animatables.push(animatabe);
  99801. }
  99802. }
  99803. };
  99804. /**
  99805. * Returns the frustum slope based on the canvas ratio and camera FOV
  99806. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99807. */
  99808. FramingBehavior.prototype._getFrustumSlope = function () {
  99809. // Calculate the viewport ratio
  99810. // Aspect Ratio is Height/Width.
  99811. var camera = this._attachedCamera;
  99812. if (!camera) {
  99813. return BABYLON.Vector2.Zero();
  99814. }
  99815. var engine = camera.getScene().getEngine();
  99816. var aspectRatio = engine.getAspectRatio(camera);
  99817. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99818. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99819. var frustumSlopeY = Math.tan(camera.fov / 2);
  99820. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99821. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99822. // along the forward vector.
  99823. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99824. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99825. };
  99826. /**
  99827. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99828. */
  99829. FramingBehavior.prototype._clearAnimationLocks = function () {
  99830. this._betaIsAnimating = false;
  99831. };
  99832. /**
  99833. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99834. */
  99835. FramingBehavior.prototype._applyUserInteraction = function () {
  99836. if (this.isUserIsMoving) {
  99837. this._lastInteractionTime = BABYLON.Tools.Now;
  99838. this.stopAllAnimations();
  99839. this._clearAnimationLocks();
  99840. }
  99841. };
  99842. /**
  99843. * Stops and removes all animations that have been applied to the camera
  99844. */
  99845. FramingBehavior.prototype.stopAllAnimations = function () {
  99846. if (this._attachedCamera) {
  99847. this._attachedCamera.animations = [];
  99848. }
  99849. while (this._animatables.length) {
  99850. if (this._animatables[0]) {
  99851. this._animatables[0].onAnimationEnd = null;
  99852. this._animatables[0].stop();
  99853. }
  99854. this._animatables.shift();
  99855. }
  99856. };
  99857. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99858. /**
  99859. * Gets a value indicating if the user is moving the camera
  99860. */
  99861. get: function () {
  99862. if (!this._attachedCamera) {
  99863. return false;
  99864. }
  99865. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99866. this._attachedCamera.inertialBetaOffset !== 0 ||
  99867. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99868. this._attachedCamera.inertialPanningX !== 0 ||
  99869. this._attachedCamera.inertialPanningY !== 0 ||
  99870. this._isPointerDown;
  99871. },
  99872. enumerable: true,
  99873. configurable: true
  99874. });
  99875. /**
  99876. * The easing function used by animations
  99877. */
  99878. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99879. /**
  99880. * The easing mode used by animations
  99881. */
  99882. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  99883. // Statics
  99884. /**
  99885. * The camera can move all the way towards the mesh.
  99886. */
  99887. FramingBehavior.IgnoreBoundsSizeMode = 0;
  99888. /**
  99889. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  99890. */
  99891. FramingBehavior.FitFrustumSidesMode = 1;
  99892. return FramingBehavior;
  99893. }());
  99894. BABYLON.FramingBehavior = FramingBehavior;
  99895. })(BABYLON || (BABYLON = {}));
  99896. //# sourceMappingURL=babylon.framingBehavior.js.map
  99897. var BABYLON;
  99898. (function (BABYLON) {
  99899. /**
  99900. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  99901. */
  99902. var BouncingBehavior = /** @class */ (function () {
  99903. function BouncingBehavior() {
  99904. /**
  99905. * The duration of the animation, in milliseconds
  99906. */
  99907. this.transitionDuration = 450;
  99908. /**
  99909. * Length of the distance animated by the transition when lower radius is reached
  99910. */
  99911. this.lowerRadiusTransitionRange = 2;
  99912. /**
  99913. * Length of the distance animated by the transition when upper radius is reached
  99914. */
  99915. this.upperRadiusTransitionRange = -2;
  99916. this._autoTransitionRange = false;
  99917. // Animations
  99918. this._radiusIsAnimating = false;
  99919. this._radiusBounceTransition = null;
  99920. this._animatables = new Array();
  99921. }
  99922. Object.defineProperty(BouncingBehavior.prototype, "name", {
  99923. get: function () {
  99924. return "Bouncing";
  99925. },
  99926. enumerable: true,
  99927. configurable: true
  99928. });
  99929. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  99930. /**
  99931. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99932. */
  99933. get: function () {
  99934. return this._autoTransitionRange;
  99935. },
  99936. /**
  99937. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99938. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  99939. */
  99940. set: function (value) {
  99941. var _this = this;
  99942. if (this._autoTransitionRange === value) {
  99943. return;
  99944. }
  99945. this._autoTransitionRange = value;
  99946. var camera = this._attachedCamera;
  99947. if (!camera) {
  99948. return;
  99949. }
  99950. if (value) {
  99951. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99952. if (!mesh) {
  99953. return;
  99954. }
  99955. mesh.computeWorldMatrix(true);
  99956. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99957. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99958. _this.upperRadiusTransitionRange = diagonal * 0.05;
  99959. });
  99960. }
  99961. else if (this._onMeshTargetChangedObserver) {
  99962. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99963. }
  99964. },
  99965. enumerable: true,
  99966. configurable: true
  99967. });
  99968. BouncingBehavior.prototype.init = function () {
  99969. // Do notihng
  99970. };
  99971. BouncingBehavior.prototype.attach = function (camera) {
  99972. var _this = this;
  99973. this._attachedCamera = camera;
  99974. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99975. if (!_this._attachedCamera) {
  99976. return;
  99977. }
  99978. // Add the bounce animation to the lower radius limit
  99979. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  99980. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  99981. }
  99982. // Add the bounce animation to the upper radius limit
  99983. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  99984. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  99985. }
  99986. });
  99987. };
  99988. BouncingBehavior.prototype.detach = function () {
  99989. if (!this._attachedCamera) {
  99990. return;
  99991. }
  99992. if (this._onAfterCheckInputsObserver) {
  99993. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99994. }
  99995. if (this._onMeshTargetChangedObserver) {
  99996. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99997. }
  99998. this._attachedCamera = null;
  99999. };
  100000. /**
  100001. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100002. * @param radiusLimit The limit to check against.
  100003. * @return Bool to indicate if at limit.
  100004. */
  100005. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100006. if (!this._attachedCamera) {
  100007. return false;
  100008. }
  100009. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100010. return true;
  100011. }
  100012. return false;
  100013. };
  100014. /**
  100015. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100016. * @param radiusDelta The delta by which to animate to. Can be negative.
  100017. */
  100018. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100019. var _this = this;
  100020. if (!this._attachedCamera) {
  100021. return;
  100022. }
  100023. if (!this._radiusBounceTransition) {
  100024. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100025. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100026. }
  100027. // Prevent zoom until bounce has completed
  100028. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100029. this._attachedCamera.wheelPrecision = Infinity;
  100030. this._attachedCamera.inertialRadiusOffset = 0;
  100031. // Animate to the radius limit
  100032. this.stopAllAnimations();
  100033. this._radiusIsAnimating = true;
  100034. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100035. if (animatable) {
  100036. this._animatables.push(animatable);
  100037. }
  100038. };
  100039. /**
  100040. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100041. */
  100042. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100043. this._radiusIsAnimating = false;
  100044. if (this._attachedCamera) {
  100045. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100046. }
  100047. };
  100048. /**
  100049. * Stops and removes all animations that have been applied to the camera
  100050. */
  100051. BouncingBehavior.prototype.stopAllAnimations = function () {
  100052. if (this._attachedCamera) {
  100053. this._attachedCamera.animations = [];
  100054. }
  100055. while (this._animatables.length) {
  100056. this._animatables[0].onAnimationEnd = null;
  100057. this._animatables[0].stop();
  100058. this._animatables.shift();
  100059. }
  100060. };
  100061. /**
  100062. * The easing function used by animations
  100063. */
  100064. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100065. /**
  100066. * The easing mode used by animations
  100067. */
  100068. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100069. return BouncingBehavior;
  100070. }());
  100071. BABYLON.BouncingBehavior = BouncingBehavior;
  100072. })(BABYLON || (BABYLON = {}));
  100073. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100074. var BABYLON;
  100075. (function (BABYLON) {
  100076. var AutoRotationBehavior = /** @class */ (function () {
  100077. function AutoRotationBehavior() {
  100078. this._zoomStopsAnimation = false;
  100079. this._idleRotationSpeed = 0.05;
  100080. this._idleRotationWaitTime = 2000;
  100081. this._idleRotationSpinupTime = 2000;
  100082. this._isPointerDown = false;
  100083. this._lastFrameTime = null;
  100084. this._lastInteractionTime = -Infinity;
  100085. this._cameraRotationSpeed = 0;
  100086. this._lastFrameRadius = 0;
  100087. }
  100088. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100089. get: function () {
  100090. return "AutoRotation";
  100091. },
  100092. enumerable: true,
  100093. configurable: true
  100094. });
  100095. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100096. /**
  100097. * Gets the flag that indicates if user zooming should stop animation.
  100098. */
  100099. get: function () {
  100100. return this._zoomStopsAnimation;
  100101. },
  100102. /**
  100103. * Sets the flag that indicates if user zooming should stop animation.
  100104. */
  100105. set: function (flag) {
  100106. this._zoomStopsAnimation = flag;
  100107. },
  100108. enumerable: true,
  100109. configurable: true
  100110. });
  100111. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100112. /**
  100113. * Gets the default speed at which the camera rotates around the model.
  100114. */
  100115. get: function () {
  100116. return this._idleRotationSpeed;
  100117. },
  100118. /**
  100119. * Sets the default speed at which the camera rotates around the model.
  100120. */
  100121. set: function (speed) {
  100122. this._idleRotationSpeed = speed;
  100123. },
  100124. enumerable: true,
  100125. configurable: true
  100126. });
  100127. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100128. /**
  100129. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100130. */
  100131. get: function () {
  100132. return this._idleRotationWaitTime;
  100133. },
  100134. /**
  100135. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100136. */
  100137. set: function (time) {
  100138. this._idleRotationWaitTime = time;
  100139. },
  100140. enumerable: true,
  100141. configurable: true
  100142. });
  100143. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100144. /**
  100145. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100146. */
  100147. get: function () {
  100148. return this._idleRotationSpinupTime;
  100149. },
  100150. /**
  100151. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100152. */
  100153. set: function (time) {
  100154. this._idleRotationSpinupTime = time;
  100155. },
  100156. enumerable: true,
  100157. configurable: true
  100158. });
  100159. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100160. /**
  100161. * Gets a value indicating if the camera is currently rotating because of this behavior
  100162. */
  100163. get: function () {
  100164. return Math.abs(this._cameraRotationSpeed) > 0;
  100165. },
  100166. enumerable: true,
  100167. configurable: true
  100168. });
  100169. AutoRotationBehavior.prototype.init = function () {
  100170. // Do notihng
  100171. };
  100172. AutoRotationBehavior.prototype.attach = function (camera) {
  100173. var _this = this;
  100174. this._attachedCamera = camera;
  100175. var scene = this._attachedCamera.getScene();
  100176. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100177. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100178. _this._isPointerDown = true;
  100179. return;
  100180. }
  100181. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100182. _this._isPointerDown = false;
  100183. }
  100184. });
  100185. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100186. var now = BABYLON.Tools.Now;
  100187. var dt = 0;
  100188. if (_this._lastFrameTime != null) {
  100189. dt = now - _this._lastFrameTime;
  100190. }
  100191. _this._lastFrameTime = now;
  100192. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100193. _this._applyUserInteraction();
  100194. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  100195. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  100196. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  100197. // Step camera rotation by rotation speed
  100198. if (_this._attachedCamera) {
  100199. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  100200. }
  100201. });
  100202. };
  100203. AutoRotationBehavior.prototype.detach = function () {
  100204. if (!this._attachedCamera) {
  100205. return;
  100206. }
  100207. var scene = this._attachedCamera.getScene();
  100208. if (this._onPrePointerObservableObserver) {
  100209. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100210. }
  100211. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100212. this._attachedCamera = null;
  100213. };
  100214. /**
  100215. * Returns true if user is scrolling.
  100216. * @return true if user is scrolling.
  100217. */
  100218. AutoRotationBehavior.prototype._userIsZooming = function () {
  100219. if (!this._attachedCamera) {
  100220. return false;
  100221. }
  100222. return this._attachedCamera.inertialRadiusOffset !== 0;
  100223. };
  100224. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  100225. if (!this._attachedCamera) {
  100226. return false;
  100227. }
  100228. var zoomHasHitLimit = false;
  100229. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  100230. zoomHasHitLimit = true;
  100231. }
  100232. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  100233. this._lastFrameRadius = this._attachedCamera.radius;
  100234. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  100235. };
  100236. /**
  100237. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100238. */
  100239. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  100240. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  100241. this._lastInteractionTime = BABYLON.Tools.Now;
  100242. }
  100243. };
  100244. // Tools
  100245. AutoRotationBehavior.prototype._userIsMoving = function () {
  100246. if (!this._attachedCamera) {
  100247. return false;
  100248. }
  100249. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100250. this._attachedCamera.inertialBetaOffset !== 0 ||
  100251. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100252. this._attachedCamera.inertialPanningX !== 0 ||
  100253. this._attachedCamera.inertialPanningY !== 0 ||
  100254. this._isPointerDown;
  100255. };
  100256. return AutoRotationBehavior;
  100257. }());
  100258. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100259. })(BABYLON || (BABYLON = {}));
  100260. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100261. var BABYLON;
  100262. (function (BABYLON) {
  100263. var NullEngineOptions = /** @class */ (function () {
  100264. function NullEngineOptions() {
  100265. this.renderWidth = 512;
  100266. this.renderHeight = 256;
  100267. this.textureSize = 512;
  100268. this.deterministicLockstep = false;
  100269. this.lockstepMaxSteps = 4;
  100270. }
  100271. return NullEngineOptions;
  100272. }());
  100273. BABYLON.NullEngineOptions = NullEngineOptions;
  100274. /**
  100275. * The null engine class provides support for headless version of babylon.js.
  100276. * This can be used in server side scenario or for testing purposes
  100277. */
  100278. var NullEngine = /** @class */ (function (_super) {
  100279. __extends(NullEngine, _super);
  100280. function NullEngine(options) {
  100281. if (options === void 0) { options = new NullEngineOptions(); }
  100282. var _this = _super.call(this, null) || this;
  100283. if (options.deterministicLockstep === undefined) {
  100284. options.deterministicLockstep = false;
  100285. }
  100286. if (options.lockstepMaxSteps === undefined) {
  100287. options.lockstepMaxSteps = 4;
  100288. }
  100289. _this._options = options;
  100290. // Init caps
  100291. // We consider we are on a webgl1 capable device
  100292. _this._caps = new BABYLON.EngineCapabilities();
  100293. _this._caps.maxTexturesImageUnits = 16;
  100294. _this._caps.maxVertexTextureImageUnits = 16;
  100295. _this._caps.maxTextureSize = 512;
  100296. _this._caps.maxCubemapTextureSize = 512;
  100297. _this._caps.maxRenderTextureSize = 512;
  100298. _this._caps.maxVertexAttribs = 16;
  100299. _this._caps.maxVaryingVectors = 16;
  100300. _this._caps.maxFragmentUniformVectors = 16;
  100301. _this._caps.maxVertexUniformVectors = 16;
  100302. // Extensions
  100303. _this._caps.standardDerivatives = false;
  100304. _this._caps.astc = null;
  100305. _this._caps.s3tc = null;
  100306. _this._caps.pvrtc = null;
  100307. _this._caps.etc1 = null;
  100308. _this._caps.etc2 = null;
  100309. _this._caps.textureAnisotropicFilterExtension = null;
  100310. _this._caps.maxAnisotropy = 0;
  100311. _this._caps.uintIndices = false;
  100312. _this._caps.fragmentDepthSupported = false;
  100313. _this._caps.highPrecisionShaderSupported = true;
  100314. _this._caps.colorBufferFloat = false;
  100315. _this._caps.textureFloat = false;
  100316. _this._caps.textureFloatLinearFiltering = false;
  100317. _this._caps.textureFloatRender = false;
  100318. _this._caps.textureHalfFloat = false;
  100319. _this._caps.textureHalfFloatLinearFiltering = false;
  100320. _this._caps.textureHalfFloatRender = false;
  100321. _this._caps.textureLOD = false;
  100322. _this._caps.drawBuffersExtension = false;
  100323. _this._caps.depthTextureExtension = false;
  100324. _this._caps.vertexArrayObject = false;
  100325. _this._caps.instancedArrays = false;
  100326. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100327. // Wrappers
  100328. if (typeof URL === "undefined") {
  100329. URL = {
  100330. createObjectURL: function () { },
  100331. revokeObjectURL: function () { }
  100332. };
  100333. }
  100334. if (typeof Blob === "undefined") {
  100335. Blob = function () { };
  100336. }
  100337. return _this;
  100338. }
  100339. NullEngine.prototype.isDeterministicLockStep = function () {
  100340. return this._options.deterministicLockstep;
  100341. };
  100342. NullEngine.prototype.getLockstepMaxSteps = function () {
  100343. return this._options.lockstepMaxSteps;
  100344. };
  100345. NullEngine.prototype.getHardwareScalingLevel = function () {
  100346. return 1.0;
  100347. };
  100348. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100349. return {
  100350. capacity: 0,
  100351. references: 1,
  100352. is32Bits: false
  100353. };
  100354. };
  100355. NullEngine.prototype.createIndexBuffer = function (indices) {
  100356. return {
  100357. capacity: 0,
  100358. references: 1,
  100359. is32Bits: false
  100360. };
  100361. };
  100362. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100363. if (stencil === void 0) { stencil = false; }
  100364. };
  100365. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100366. if (useScreen === void 0) { useScreen = false; }
  100367. if (!useScreen && this._currentRenderTarget) {
  100368. return this._currentRenderTarget.width;
  100369. }
  100370. return this._options.renderWidth;
  100371. };
  100372. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100373. if (useScreen === void 0) { useScreen = false; }
  100374. if (!useScreen && this._currentRenderTarget) {
  100375. return this._currentRenderTarget.height;
  100376. }
  100377. return this._options.renderHeight;
  100378. };
  100379. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100380. this._cachedViewport = viewport;
  100381. };
  100382. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100383. return {
  100384. transformFeedback: null,
  100385. __SPECTOR_rebuildProgram: null
  100386. };
  100387. };
  100388. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100389. return [];
  100390. };
  100391. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100392. return [];
  100393. };
  100394. NullEngine.prototype.bindSamplers = function (effect) {
  100395. this._currentEffect = null;
  100396. };
  100397. NullEngine.prototype.enableEffect = function (effect) {
  100398. this._currentEffect = effect;
  100399. if (effect.onBind) {
  100400. effect.onBind(effect);
  100401. }
  100402. effect.onBindObservable.notifyObservers(effect);
  100403. };
  100404. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100405. if (zOffset === void 0) { zOffset = 0; }
  100406. if (reverseSide === void 0) { reverseSide = false; }
  100407. };
  100408. NullEngine.prototype.setIntArray = function (uniform, array) {
  100409. };
  100410. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100411. };
  100412. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100413. };
  100414. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100415. };
  100416. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100417. };
  100418. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100419. };
  100420. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100421. };
  100422. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100423. };
  100424. NullEngine.prototype.setArray = function (uniform, array) {
  100425. };
  100426. NullEngine.prototype.setArray2 = function (uniform, array) {
  100427. };
  100428. NullEngine.prototype.setArray3 = function (uniform, array) {
  100429. };
  100430. NullEngine.prototype.setArray4 = function (uniform, array) {
  100431. };
  100432. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100433. };
  100434. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100435. };
  100436. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100437. };
  100438. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100439. };
  100440. NullEngine.prototype.setFloat = function (uniform, value) {
  100441. };
  100442. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100443. };
  100444. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100445. };
  100446. NullEngine.prototype.setBool = function (uniform, bool) {
  100447. };
  100448. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100449. };
  100450. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100451. };
  100452. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100453. };
  100454. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100455. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100456. if (this._alphaMode === mode) {
  100457. return;
  100458. }
  100459. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100460. if (!noDepthWriteChange) {
  100461. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100462. }
  100463. this._alphaMode = mode;
  100464. };
  100465. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100466. };
  100467. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100468. if (this.preventCacheWipeBetweenFrames) {
  100469. return;
  100470. }
  100471. this.resetTextureCache();
  100472. this._currentEffect = null;
  100473. if (bruteForce) {
  100474. this._currentProgram = null;
  100475. this._stencilState.reset();
  100476. this._depthCullingState.reset();
  100477. this._alphaState.reset();
  100478. }
  100479. this._cachedVertexBuffers = null;
  100480. this._cachedIndexBuffer = null;
  100481. this._cachedEffectForVertexBuffers = null;
  100482. };
  100483. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100484. };
  100485. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100486. };
  100487. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100488. };
  100489. NullEngine.prototype._createTexture = function () {
  100490. return {};
  100491. };
  100492. NullEngine.prototype._releaseTexture = function (texture) {
  100493. };
  100494. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100495. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100496. if (onLoad === void 0) { onLoad = null; }
  100497. if (onError === void 0) { onError = null; }
  100498. if (buffer === void 0) { buffer = null; }
  100499. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100500. var url = String(urlArg);
  100501. texture.url = url;
  100502. texture.generateMipMaps = !noMipmap;
  100503. texture.samplingMode = samplingMode;
  100504. texture.invertY = invertY;
  100505. texture.baseWidth = this._options.textureSize;
  100506. texture.baseHeight = this._options.textureSize;
  100507. texture.width = this._options.textureSize;
  100508. texture.height = this._options.textureSize;
  100509. if (format) {
  100510. texture.format = format;
  100511. }
  100512. texture.isReady = true;
  100513. if (onLoad) {
  100514. onLoad();
  100515. }
  100516. this._internalTexturesCache.push(texture);
  100517. return texture;
  100518. };
  100519. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100520. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100521. if (options !== undefined && typeof options === "object") {
  100522. fullOptions.generateMipMaps = options.generateMipMaps;
  100523. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100524. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100525. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100526. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100527. }
  100528. else {
  100529. fullOptions.generateMipMaps = options;
  100530. fullOptions.generateDepthBuffer = true;
  100531. fullOptions.generateStencilBuffer = false;
  100532. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100533. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100534. }
  100535. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100536. var width = size.width || size;
  100537. var height = size.height || size;
  100538. texture._depthStencilBuffer = {};
  100539. texture._framebuffer = {};
  100540. texture.baseWidth = width;
  100541. texture.baseHeight = height;
  100542. texture.width = width;
  100543. texture.height = height;
  100544. texture.isReady = true;
  100545. texture.samples = 1;
  100546. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100547. texture.samplingMode = fullOptions.samplingMode;
  100548. texture.type = fullOptions.type;
  100549. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100550. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100551. this._internalTexturesCache.push(texture);
  100552. return texture;
  100553. };
  100554. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100555. texture.samplingMode = samplingMode;
  100556. };
  100557. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100558. if (this._currentRenderTarget) {
  100559. this.unBindFramebuffer(this._currentRenderTarget);
  100560. }
  100561. this._currentRenderTarget = texture;
  100562. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100563. if (this._cachedViewport && !forceFullscreenViewport) {
  100564. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100565. }
  100566. };
  100567. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100568. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100569. this._currentRenderTarget = null;
  100570. if (onBeforeUnbind) {
  100571. if (texture._MSAAFramebuffer) {
  100572. this._currentFramebuffer = texture._framebuffer;
  100573. }
  100574. onBeforeUnbind();
  100575. }
  100576. this._currentFramebuffer = null;
  100577. };
  100578. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100579. var vbo = {
  100580. capacity: 1,
  100581. references: 1,
  100582. is32Bits: false
  100583. };
  100584. return vbo;
  100585. };
  100586. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100587. if (premulAlpha === void 0) { premulAlpha = false; }
  100588. };
  100589. /**
  100590. * Get the current error code of the webGL context
  100591. * @returns the error code
  100592. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  100593. */
  100594. NullEngine.prototype.getError = function () {
  100595. return 0;
  100596. };
  100597. /** @hidden */
  100598. NullEngine.prototype._getUnpackAlignement = function () {
  100599. return 1;
  100600. };
  100601. /** @hidden */
  100602. NullEngine.prototype._unpackFlipY = function (value) {
  100603. };
  100604. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100605. if (offset === void 0) { offset = 0; }
  100606. };
  100607. /**
  100608. * Updates a dynamic vertex buffer.
  100609. * @param vertexBuffer the vertex buffer to update
  100610. * @param data the data used to update the vertex buffer
  100611. * @param byteOffset the byte offset of the data (optional)
  100612. * @param byteLength the byte length of the data (optional)
  100613. */
  100614. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100615. };
  100616. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100617. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100618. this._boundTexturesCache[this._activeChannel] = texture;
  100619. return true;
  100620. }
  100621. return false;
  100622. };
  100623. NullEngine.prototype._bindTexture = function (channel, texture) {
  100624. if (channel < 0) {
  100625. return;
  100626. }
  100627. this._bindTextureDirectly(0, texture);
  100628. };
  100629. NullEngine.prototype._releaseBuffer = function (buffer) {
  100630. buffer.references--;
  100631. if (buffer.references === 0) {
  100632. return true;
  100633. }
  100634. return false;
  100635. };
  100636. NullEngine.prototype.releaseEffects = function () {
  100637. };
  100638. NullEngine.prototype.displayLoadingUI = function () {
  100639. };
  100640. NullEngine.prototype.hideLoadingUI = function () {
  100641. };
  100642. /** @hidden */
  100643. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  100644. if (faceIndex === void 0) { faceIndex = 0; }
  100645. if (lod === void 0) { lod = 0; }
  100646. };
  100647. /** @hidden */
  100648. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, width, height, imageData, faceIndex, lod) {
  100649. if (faceIndex === void 0) { faceIndex = 0; }
  100650. if (lod === void 0) { lod = 0; }
  100651. };
  100652. /** @hidden */
  100653. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  100654. if (faceIndex === void 0) { faceIndex = 0; }
  100655. if (lod === void 0) { lod = 0; }
  100656. };
  100657. /** @hidden */
  100658. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  100659. if (faceIndex === void 0) { faceIndex = 0; }
  100660. if (lod === void 0) { lod = 0; }
  100661. };
  100662. return NullEngine;
  100663. }(BABYLON.Engine));
  100664. BABYLON.NullEngine = NullEngine;
  100665. })(BABYLON || (BABYLON = {}));
  100666. //# sourceMappingURL=babylon.nullEngine.js.map
  100667. var BABYLON;
  100668. (function (BABYLON) {
  100669. /**
  100670. * This class can be used to get instrumentation data from a Babylon engine
  100671. */
  100672. var EngineInstrumentation = /** @class */ (function () {
  100673. function EngineInstrumentation(engine) {
  100674. this.engine = engine;
  100675. this._captureGPUFrameTime = false;
  100676. this._gpuFrameTime = new BABYLON.PerfCounter();
  100677. this._captureShaderCompilationTime = false;
  100678. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100679. // Observers
  100680. this._onBeginFrameObserver = null;
  100681. this._onEndFrameObserver = null;
  100682. this._onBeforeShaderCompilationObserver = null;
  100683. this._onAfterShaderCompilationObserver = null;
  100684. }
  100685. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100686. // Properties
  100687. /**
  100688. * Gets the perf counter used for GPU frame time
  100689. */
  100690. get: function () {
  100691. return this._gpuFrameTime;
  100692. },
  100693. enumerable: true,
  100694. configurable: true
  100695. });
  100696. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100697. /**
  100698. * Gets the GPU frame time capture status
  100699. */
  100700. get: function () {
  100701. return this._captureGPUFrameTime;
  100702. },
  100703. /**
  100704. * Enable or disable the GPU frame time capture
  100705. */
  100706. set: function (value) {
  100707. var _this = this;
  100708. if (value === this._captureGPUFrameTime) {
  100709. return;
  100710. }
  100711. this._captureGPUFrameTime = value;
  100712. if (value) {
  100713. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100714. if (!_this._gpuFrameTimeToken) {
  100715. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100716. }
  100717. });
  100718. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100719. if (!_this._gpuFrameTimeToken) {
  100720. return;
  100721. }
  100722. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100723. if (time > -1) {
  100724. _this._gpuFrameTimeToken = null;
  100725. _this._gpuFrameTime.fetchNewFrame();
  100726. _this._gpuFrameTime.addCount(time, true);
  100727. }
  100728. });
  100729. }
  100730. else {
  100731. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100732. this._onBeginFrameObserver = null;
  100733. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100734. this._onEndFrameObserver = null;
  100735. }
  100736. },
  100737. enumerable: true,
  100738. configurable: true
  100739. });
  100740. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100741. /**
  100742. * Gets the perf counter used for shader compilation time
  100743. */
  100744. get: function () {
  100745. return this._shaderCompilationTime;
  100746. },
  100747. enumerable: true,
  100748. configurable: true
  100749. });
  100750. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100751. /**
  100752. * Gets the shader compilation time capture status
  100753. */
  100754. get: function () {
  100755. return this._captureShaderCompilationTime;
  100756. },
  100757. /**
  100758. * Enable or disable the shader compilation time capture
  100759. */
  100760. set: function (value) {
  100761. var _this = this;
  100762. if (value === this._captureShaderCompilationTime) {
  100763. return;
  100764. }
  100765. this._captureShaderCompilationTime = value;
  100766. if (value) {
  100767. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100768. _this._shaderCompilationTime.fetchNewFrame();
  100769. _this._shaderCompilationTime.beginMonitoring();
  100770. });
  100771. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100772. _this._shaderCompilationTime.endMonitoring();
  100773. });
  100774. }
  100775. else {
  100776. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100777. this._onBeforeShaderCompilationObserver = null;
  100778. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100779. this._onAfterShaderCompilationObserver = null;
  100780. }
  100781. },
  100782. enumerable: true,
  100783. configurable: true
  100784. });
  100785. EngineInstrumentation.prototype.dispose = function () {
  100786. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100787. this._onBeginFrameObserver = null;
  100788. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100789. this._onEndFrameObserver = null;
  100790. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100791. this._onBeforeShaderCompilationObserver = null;
  100792. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100793. this._onAfterShaderCompilationObserver = null;
  100794. this.engine = null;
  100795. };
  100796. return EngineInstrumentation;
  100797. }());
  100798. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100799. })(BABYLON || (BABYLON = {}));
  100800. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100801. var BABYLON;
  100802. (function (BABYLON) {
  100803. /**
  100804. * This class can be used to get instrumentation data from a Babylon engine
  100805. */
  100806. var SceneInstrumentation = /** @class */ (function () {
  100807. function SceneInstrumentation(scene) {
  100808. var _this = this;
  100809. this.scene = scene;
  100810. this._captureActiveMeshesEvaluationTime = false;
  100811. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100812. this._captureRenderTargetsRenderTime = false;
  100813. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100814. this._captureFrameTime = false;
  100815. this._frameTime = new BABYLON.PerfCounter();
  100816. this._captureRenderTime = false;
  100817. this._renderTime = new BABYLON.PerfCounter();
  100818. this._captureInterFrameTime = false;
  100819. this._interFrameTime = new BABYLON.PerfCounter();
  100820. this._captureParticlesRenderTime = false;
  100821. this._particlesRenderTime = new BABYLON.PerfCounter();
  100822. this._captureSpritesRenderTime = false;
  100823. this._spritesRenderTime = new BABYLON.PerfCounter();
  100824. this._capturePhysicsTime = false;
  100825. this._physicsTime = new BABYLON.PerfCounter();
  100826. this._captureAnimationsTime = false;
  100827. this._animationsTime = new BABYLON.PerfCounter();
  100828. this._captureCameraRenderTime = false;
  100829. this._cameraRenderTime = new BABYLON.PerfCounter();
  100830. // Observers
  100831. this._onBeforeActiveMeshesEvaluationObserver = null;
  100832. this._onAfterActiveMeshesEvaluationObserver = null;
  100833. this._onBeforeRenderTargetsRenderObserver = null;
  100834. this._onAfterRenderTargetsRenderObserver = null;
  100835. this._onAfterRenderObserver = null;
  100836. this._onBeforeDrawPhaseObserver = null;
  100837. this._onAfterDrawPhaseObserver = null;
  100838. this._onBeforeAnimationsObserver = null;
  100839. this._onBeforeParticlesRenderingObserver = null;
  100840. this._onAfterParticlesRenderingObserver = null;
  100841. this._onBeforeSpritesRenderingObserver = null;
  100842. this._onAfterSpritesRenderingObserver = null;
  100843. this._onBeforePhysicsObserver = null;
  100844. this._onAfterPhysicsObserver = null;
  100845. this._onAfterAnimationsObserver = null;
  100846. this._onBeforeCameraRenderObserver = null;
  100847. this._onAfterCameraRenderObserver = null;
  100848. // Before render
  100849. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100850. if (_this._captureActiveMeshesEvaluationTime) {
  100851. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100852. }
  100853. if (_this._captureRenderTargetsRenderTime) {
  100854. _this._renderTargetsRenderTime.fetchNewFrame();
  100855. }
  100856. if (_this._captureFrameTime) {
  100857. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100858. _this._frameTime.beginMonitoring();
  100859. }
  100860. if (_this._captureInterFrameTime) {
  100861. _this._interFrameTime.endMonitoring();
  100862. }
  100863. if (_this._captureParticlesRenderTime) {
  100864. _this._particlesRenderTime.fetchNewFrame();
  100865. }
  100866. if (_this._captureSpritesRenderTime) {
  100867. _this._spritesRenderTime.fetchNewFrame();
  100868. }
  100869. if (_this._captureAnimationsTime) {
  100870. _this._animationsTime.beginMonitoring();
  100871. }
  100872. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100873. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100874. });
  100875. // After render
  100876. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100877. if (_this._captureFrameTime) {
  100878. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100879. _this._frameTime.endMonitoring();
  100880. }
  100881. if (_this._captureRenderTime) {
  100882. _this._renderTime.endMonitoring(false);
  100883. }
  100884. if (_this._captureInterFrameTime) {
  100885. _this._interFrameTime.beginMonitoring();
  100886. }
  100887. });
  100888. }
  100889. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  100890. // Properties
  100891. /**
  100892. * Gets the perf counter used for active meshes evaluation time
  100893. */
  100894. get: function () {
  100895. return this._activeMeshesEvaluationTime;
  100896. },
  100897. enumerable: true,
  100898. configurable: true
  100899. });
  100900. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  100901. /**
  100902. * Gets the active meshes evaluation time capture status
  100903. */
  100904. get: function () {
  100905. return this._captureActiveMeshesEvaluationTime;
  100906. },
  100907. /**
  100908. * Enable or disable the active meshes evaluation time capture
  100909. */
  100910. set: function (value) {
  100911. var _this = this;
  100912. if (value === this._captureActiveMeshesEvaluationTime) {
  100913. return;
  100914. }
  100915. this._captureActiveMeshesEvaluationTime = value;
  100916. if (value) {
  100917. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  100918. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  100919. _this._activeMeshesEvaluationTime.beginMonitoring();
  100920. });
  100921. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  100922. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  100923. _this._activeMeshesEvaluationTime.endMonitoring();
  100924. });
  100925. }
  100926. else {
  100927. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100928. this._onBeforeActiveMeshesEvaluationObserver = null;
  100929. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100930. this._onAfterActiveMeshesEvaluationObserver = null;
  100931. }
  100932. },
  100933. enumerable: true,
  100934. configurable: true
  100935. });
  100936. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  100937. /**
  100938. * Gets the perf counter used for render targets render time
  100939. */
  100940. get: function () {
  100941. return this._renderTargetsRenderTime;
  100942. },
  100943. enumerable: true,
  100944. configurable: true
  100945. });
  100946. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  100947. /**
  100948. * Gets the render targets render time capture status
  100949. */
  100950. get: function () {
  100951. return this._captureRenderTargetsRenderTime;
  100952. },
  100953. /**
  100954. * Enable or disable the render targets render time capture
  100955. */
  100956. set: function (value) {
  100957. var _this = this;
  100958. if (value === this._captureRenderTargetsRenderTime) {
  100959. return;
  100960. }
  100961. this._captureRenderTargetsRenderTime = value;
  100962. if (value) {
  100963. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  100964. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  100965. _this._renderTargetsRenderTime.beginMonitoring();
  100966. });
  100967. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  100968. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  100969. _this._renderTargetsRenderTime.endMonitoring(false);
  100970. });
  100971. }
  100972. else {
  100973. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100974. this._onBeforeRenderTargetsRenderObserver = null;
  100975. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100976. this._onAfterRenderTargetsRenderObserver = null;
  100977. }
  100978. },
  100979. enumerable: true,
  100980. configurable: true
  100981. });
  100982. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  100983. /**
  100984. * Gets the perf counter used for particles render time
  100985. */
  100986. get: function () {
  100987. return this._particlesRenderTime;
  100988. },
  100989. enumerable: true,
  100990. configurable: true
  100991. });
  100992. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  100993. /**
  100994. * Gets the particles render time capture status
  100995. */
  100996. get: function () {
  100997. return this._captureParticlesRenderTime;
  100998. },
  100999. /**
  101000. * Enable or disable the particles render time capture
  101001. */
  101002. set: function (value) {
  101003. var _this = this;
  101004. if (value === this._captureParticlesRenderTime) {
  101005. return;
  101006. }
  101007. this._captureParticlesRenderTime = value;
  101008. if (value) {
  101009. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101010. BABYLON.Tools.StartPerformanceCounter("Particles");
  101011. _this._particlesRenderTime.beginMonitoring();
  101012. });
  101013. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101014. BABYLON.Tools.EndPerformanceCounter("Particles");
  101015. _this._particlesRenderTime.endMonitoring(false);
  101016. });
  101017. }
  101018. else {
  101019. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101020. this._onBeforeParticlesRenderingObserver = null;
  101021. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101022. this._onAfterParticlesRenderingObserver = null;
  101023. }
  101024. },
  101025. enumerable: true,
  101026. configurable: true
  101027. });
  101028. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101029. /**
  101030. * Gets the perf counter used for sprites render time
  101031. */
  101032. get: function () {
  101033. return this._spritesRenderTime;
  101034. },
  101035. enumerable: true,
  101036. configurable: true
  101037. });
  101038. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101039. /**
  101040. * Gets the sprites render time capture status
  101041. */
  101042. get: function () {
  101043. return this._captureSpritesRenderTime;
  101044. },
  101045. /**
  101046. * Enable or disable the sprites render time capture
  101047. */
  101048. set: function (value) {
  101049. var _this = this;
  101050. if (value === this._captureSpritesRenderTime) {
  101051. return;
  101052. }
  101053. this._captureSpritesRenderTime = value;
  101054. if (value) {
  101055. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101056. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101057. _this._spritesRenderTime.beginMonitoring();
  101058. });
  101059. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101060. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101061. _this._spritesRenderTime.endMonitoring(false);
  101062. });
  101063. }
  101064. else {
  101065. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101066. this._onBeforeSpritesRenderingObserver = null;
  101067. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101068. this._onAfterSpritesRenderingObserver = null;
  101069. }
  101070. },
  101071. enumerable: true,
  101072. configurable: true
  101073. });
  101074. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101075. /**
  101076. * Gets the perf counter used for physics time
  101077. */
  101078. get: function () {
  101079. return this._physicsTime;
  101080. },
  101081. enumerable: true,
  101082. configurable: true
  101083. });
  101084. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101085. /**
  101086. * Gets the physics time capture status
  101087. */
  101088. get: function () {
  101089. return this._capturePhysicsTime;
  101090. },
  101091. /**
  101092. * Enable or disable the physics time capture
  101093. */
  101094. set: function (value) {
  101095. var _this = this;
  101096. if (value === this._capturePhysicsTime) {
  101097. return;
  101098. }
  101099. this._capturePhysicsTime = value;
  101100. if (value) {
  101101. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101102. BABYLON.Tools.StartPerformanceCounter("Physics");
  101103. _this._physicsTime.beginMonitoring();
  101104. });
  101105. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101106. BABYLON.Tools.EndPerformanceCounter("Physics");
  101107. _this._physicsTime.endMonitoring();
  101108. });
  101109. }
  101110. else {
  101111. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101112. this._onBeforePhysicsObserver = null;
  101113. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101114. this._onAfterPhysicsObserver = null;
  101115. }
  101116. },
  101117. enumerable: true,
  101118. configurable: true
  101119. });
  101120. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101121. /**
  101122. * Gets the perf counter used for animations time
  101123. */
  101124. get: function () {
  101125. return this._animationsTime;
  101126. },
  101127. enumerable: true,
  101128. configurable: true
  101129. });
  101130. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101131. /**
  101132. * Gets the animations time capture status
  101133. */
  101134. get: function () {
  101135. return this._captureAnimationsTime;
  101136. },
  101137. /**
  101138. * Enable or disable the animations time capture
  101139. */
  101140. set: function (value) {
  101141. var _this = this;
  101142. if (value === this._captureAnimationsTime) {
  101143. return;
  101144. }
  101145. this._captureAnimationsTime = value;
  101146. if (value) {
  101147. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101148. _this._animationsTime.endMonitoring();
  101149. });
  101150. }
  101151. else {
  101152. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101153. this._onAfterAnimationsObserver = null;
  101154. }
  101155. },
  101156. enumerable: true,
  101157. configurable: true
  101158. });
  101159. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101160. /**
  101161. * Gets the perf counter used for frame time capture
  101162. */
  101163. get: function () {
  101164. return this._frameTime;
  101165. },
  101166. enumerable: true,
  101167. configurable: true
  101168. });
  101169. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  101170. /**
  101171. * Gets the frame time capture status
  101172. */
  101173. get: function () {
  101174. return this._captureFrameTime;
  101175. },
  101176. /**
  101177. * Enable or disable the frame time capture
  101178. */
  101179. set: function (value) {
  101180. this._captureFrameTime = value;
  101181. },
  101182. enumerable: true,
  101183. configurable: true
  101184. });
  101185. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  101186. /**
  101187. * Gets the perf counter used for inter-frames time capture
  101188. */
  101189. get: function () {
  101190. return this._interFrameTime;
  101191. },
  101192. enumerable: true,
  101193. configurable: true
  101194. });
  101195. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  101196. /**
  101197. * Gets the inter-frames time capture status
  101198. */
  101199. get: function () {
  101200. return this._captureInterFrameTime;
  101201. },
  101202. /**
  101203. * Enable or disable the inter-frames time capture
  101204. */
  101205. set: function (value) {
  101206. this._captureInterFrameTime = value;
  101207. },
  101208. enumerable: true,
  101209. configurable: true
  101210. });
  101211. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  101212. /**
  101213. * Gets the perf counter used for render time capture
  101214. */
  101215. get: function () {
  101216. return this._renderTime;
  101217. },
  101218. enumerable: true,
  101219. configurable: true
  101220. });
  101221. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  101222. /**
  101223. * Gets the render time capture status
  101224. */
  101225. get: function () {
  101226. return this._captureRenderTime;
  101227. },
  101228. /**
  101229. * Enable or disable the render time capture
  101230. */
  101231. set: function (value) {
  101232. var _this = this;
  101233. if (value === this._captureRenderTime) {
  101234. return;
  101235. }
  101236. this._captureRenderTime = value;
  101237. if (value) {
  101238. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  101239. _this._renderTime.beginMonitoring();
  101240. BABYLON.Tools.StartPerformanceCounter("Main render");
  101241. });
  101242. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  101243. _this._renderTime.endMonitoring(false);
  101244. BABYLON.Tools.EndPerformanceCounter("Main render");
  101245. });
  101246. }
  101247. else {
  101248. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101249. this._onBeforeDrawPhaseObserver = null;
  101250. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101251. this._onAfterDrawPhaseObserver = null;
  101252. }
  101253. },
  101254. enumerable: true,
  101255. configurable: true
  101256. });
  101257. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  101258. /**
  101259. * Gets the perf counter used for camera render time capture
  101260. */
  101261. get: function () {
  101262. return this._cameraRenderTime;
  101263. },
  101264. enumerable: true,
  101265. configurable: true
  101266. });
  101267. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  101268. /**
  101269. * Gets the camera render time capture status
  101270. */
  101271. get: function () {
  101272. return this._captureCameraRenderTime;
  101273. },
  101274. /**
  101275. * Enable or disable the camera render time capture
  101276. */
  101277. set: function (value) {
  101278. var _this = this;
  101279. if (value === this._captureCameraRenderTime) {
  101280. return;
  101281. }
  101282. this._captureCameraRenderTime = value;
  101283. if (value) {
  101284. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  101285. _this._cameraRenderTime.beginMonitoring();
  101286. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  101287. });
  101288. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  101289. _this._cameraRenderTime.endMonitoring(false);
  101290. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  101291. });
  101292. }
  101293. else {
  101294. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101295. this._onBeforeCameraRenderObserver = null;
  101296. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101297. this._onAfterCameraRenderObserver = null;
  101298. }
  101299. },
  101300. enumerable: true,
  101301. configurable: true
  101302. });
  101303. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101304. /**
  101305. * Gets the perf counter used for draw calls
  101306. */
  101307. get: function () {
  101308. return this.scene.getEngine()._drawCalls;
  101309. },
  101310. enumerable: true,
  101311. configurable: true
  101312. });
  101313. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101314. /**
  101315. * Gets the perf counter used for texture collisions
  101316. */
  101317. get: function () {
  101318. return this.scene.getEngine()._textureCollisions;
  101319. },
  101320. enumerable: true,
  101321. configurable: true
  101322. });
  101323. SceneInstrumentation.prototype.dispose = function () {
  101324. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101325. this._onAfterRenderObserver = null;
  101326. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101327. this._onBeforeActiveMeshesEvaluationObserver = null;
  101328. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101329. this._onAfterActiveMeshesEvaluationObserver = null;
  101330. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101331. this._onBeforeRenderTargetsRenderObserver = null;
  101332. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101333. this._onAfterRenderTargetsRenderObserver = null;
  101334. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101335. this._onBeforeAnimationsObserver = null;
  101336. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101337. this._onBeforeParticlesRenderingObserver = null;
  101338. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101339. this._onAfterParticlesRenderingObserver = null;
  101340. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101341. this._onBeforeSpritesRenderingObserver = null;
  101342. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101343. this._onAfterSpritesRenderingObserver = null;
  101344. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101345. this._onBeforeDrawPhaseObserver = null;
  101346. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101347. this._onAfterDrawPhaseObserver = null;
  101348. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101349. this._onBeforePhysicsObserver = null;
  101350. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101351. this._onAfterPhysicsObserver = null;
  101352. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101353. this._onAfterAnimationsObserver = null;
  101354. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101355. this._onBeforeCameraRenderObserver = null;
  101356. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101357. this._onAfterCameraRenderObserver = null;
  101358. this.scene = null;
  101359. };
  101360. return SceneInstrumentation;
  101361. }());
  101362. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101363. })(BABYLON || (BABYLON = {}));
  101364. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101365. var BABYLON;
  101366. (function (BABYLON) {
  101367. /**
  101368. * @hidden
  101369. **/
  101370. var _TimeToken = /** @class */ (function () {
  101371. function _TimeToken() {
  101372. this._timeElapsedQueryEnded = false;
  101373. }
  101374. return _TimeToken;
  101375. }());
  101376. BABYLON._TimeToken = _TimeToken;
  101377. })(BABYLON || (BABYLON = {}));
  101378. //# sourceMappingURL=babylon.timeToken.js.map
  101379. var BABYLON;
  101380. (function (BABYLON) {
  101381. /**
  101382. * Background material defines definition.
  101383. * @hidden Mainly internal Use
  101384. */
  101385. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101386. __extends(BackgroundMaterialDefines, _super);
  101387. /**
  101388. * Constructor of the defines.
  101389. */
  101390. function BackgroundMaterialDefines() {
  101391. var _this = _super.call(this) || this;
  101392. /**
  101393. * True if the diffuse texture is in use.
  101394. */
  101395. _this.DIFFUSE = false;
  101396. /**
  101397. * The direct UV channel to use.
  101398. */
  101399. _this.DIFFUSEDIRECTUV = 0;
  101400. /**
  101401. * True if the diffuse texture is in gamma space.
  101402. */
  101403. _this.GAMMADIFFUSE = false;
  101404. /**
  101405. * True if the diffuse texture has opacity in the alpha channel.
  101406. */
  101407. _this.DIFFUSEHASALPHA = false;
  101408. /**
  101409. * True if you want the material to fade to transparent at grazing angle.
  101410. */
  101411. _this.OPACITYFRESNEL = false;
  101412. /**
  101413. * True if an extra blur needs to be added in the reflection.
  101414. */
  101415. _this.REFLECTIONBLUR = false;
  101416. /**
  101417. * True if you want the material to fade to reflection at grazing angle.
  101418. */
  101419. _this.REFLECTIONFRESNEL = false;
  101420. /**
  101421. * True if you want the material to falloff as far as you move away from the scene center.
  101422. */
  101423. _this.REFLECTIONFALLOFF = false;
  101424. /**
  101425. * False if the current Webgl implementation does not support the texture lod extension.
  101426. */
  101427. _this.TEXTURELODSUPPORT = false;
  101428. /**
  101429. * True to ensure the data are premultiplied.
  101430. */
  101431. _this.PREMULTIPLYALPHA = false;
  101432. /**
  101433. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101434. */
  101435. _this.USERGBCOLOR = false;
  101436. /**
  101437. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101438. * stays aligned with the desired configuration.
  101439. */
  101440. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101441. /**
  101442. * True to add noise in order to reduce the banding effect.
  101443. */
  101444. _this.NOISE = false;
  101445. /**
  101446. * is the reflection texture in BGR color scheme?
  101447. * Mainly used to solve a bug in ios10 video tag
  101448. */
  101449. _this.REFLECTIONBGR = false;
  101450. _this.IMAGEPROCESSING = false;
  101451. _this.VIGNETTE = false;
  101452. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101453. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101454. _this.TONEMAPPING = false;
  101455. _this.CONTRAST = false;
  101456. _this.COLORCURVES = false;
  101457. _this.COLORGRADING = false;
  101458. _this.COLORGRADING3D = false;
  101459. _this.SAMPLER3DGREENDEPTH = false;
  101460. _this.SAMPLER3DBGRMAP = false;
  101461. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101462. _this.EXPOSURE = false;
  101463. // Reflection.
  101464. _this.REFLECTION = false;
  101465. _this.REFLECTIONMAP_3D = false;
  101466. _this.REFLECTIONMAP_SPHERICAL = false;
  101467. _this.REFLECTIONMAP_PLANAR = false;
  101468. _this.REFLECTIONMAP_CUBIC = false;
  101469. _this.REFLECTIONMAP_PROJECTION = false;
  101470. _this.REFLECTIONMAP_SKYBOX = false;
  101471. _this.REFLECTIONMAP_EXPLICIT = false;
  101472. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101473. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101474. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101475. _this.INVERTCUBICMAP = false;
  101476. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101477. _this.LODINREFLECTIONALPHA = false;
  101478. _this.GAMMAREFLECTION = false;
  101479. _this.RGBDREFLECTION = false;
  101480. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101481. // Default BJS.
  101482. _this.MAINUV1 = false;
  101483. _this.MAINUV2 = false;
  101484. _this.UV1 = false;
  101485. _this.UV2 = false;
  101486. _this.CLIPPLANE = false;
  101487. _this.POINTSIZE = false;
  101488. _this.FOG = false;
  101489. _this.NORMAL = false;
  101490. _this.NUM_BONE_INFLUENCERS = 0;
  101491. _this.BonesPerMesh = 0;
  101492. _this.INSTANCES = false;
  101493. _this.SHADOWFLOAT = false;
  101494. _this.rebuild();
  101495. return _this;
  101496. }
  101497. return BackgroundMaterialDefines;
  101498. }(BABYLON.MaterialDefines));
  101499. /**
  101500. * Background material used to create an efficient environement around your scene.
  101501. */
  101502. var BackgroundMaterial = /** @class */ (function (_super) {
  101503. __extends(BackgroundMaterial, _super);
  101504. /**
  101505. * Instantiates a Background Material in the given scene
  101506. * @param name The friendly name of the material
  101507. * @param scene The scene to add the material to
  101508. */
  101509. function BackgroundMaterial(name, scene) {
  101510. var _this = _super.call(this, name, scene) || this;
  101511. /**
  101512. * Key light Color (multiply against the environement texture)
  101513. */
  101514. _this.primaryColor = BABYLON.Color3.White();
  101515. _this._primaryColorShadowLevel = 0;
  101516. _this._primaryColorHighlightLevel = 0;
  101517. /**
  101518. * Reflection Texture used in the material.
  101519. * Should be author in a specific way for the best result (refer to the documentation).
  101520. */
  101521. _this.reflectionTexture = null;
  101522. /**
  101523. * Reflection Texture level of blur.
  101524. *
  101525. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101526. * texture twice.
  101527. */
  101528. _this.reflectionBlur = 0;
  101529. /**
  101530. * Diffuse Texture used in the material.
  101531. * Should be author in a specific way for the best result (refer to the documentation).
  101532. */
  101533. _this.diffuseTexture = null;
  101534. _this._shadowLights = null;
  101535. /**
  101536. * Specify the list of lights casting shadow on the material.
  101537. * All scene shadow lights will be included if null.
  101538. */
  101539. _this.shadowLights = null;
  101540. /**
  101541. * Helps adjusting the shadow to a softer level if required.
  101542. * 0 means black shadows and 1 means no shadows.
  101543. */
  101544. _this.shadowLevel = 0;
  101545. /**
  101546. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101547. * It is usually zero but might be interesting to modify according to your setup.
  101548. */
  101549. _this.sceneCenter = BABYLON.Vector3.Zero();
  101550. /**
  101551. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101552. * This helps ensuring a nice transition when the camera goes under the ground.
  101553. */
  101554. _this.opacityFresnel = true;
  101555. /**
  101556. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101557. * This helps adding a mirror texture on the ground.
  101558. */
  101559. _this.reflectionFresnel = false;
  101560. /**
  101561. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101562. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101563. */
  101564. _this.reflectionFalloffDistance = 0.0;
  101565. /**
  101566. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101567. */
  101568. _this.reflectionAmount = 1.0;
  101569. /**
  101570. * This specifies the weight of the reflection at grazing angle.
  101571. */
  101572. _this.reflectionReflectance0 = 0.05;
  101573. /**
  101574. * This specifies the weight of the reflection at a perpendicular point of view.
  101575. */
  101576. _this.reflectionReflectance90 = 0.5;
  101577. /**
  101578. * Helps to directly use the maps channels instead of their level.
  101579. */
  101580. _this.useRGBColor = true;
  101581. /**
  101582. * This helps reducing the banding effect that could occur on the background.
  101583. */
  101584. _this.enableNoise = false;
  101585. _this._fovMultiplier = 1.0;
  101586. /**
  101587. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101588. */
  101589. _this.useEquirectangularFOV = false;
  101590. _this._maxSimultaneousLights = 4;
  101591. /**
  101592. * Number of Simultaneous lights allowed on the material.
  101593. */
  101594. _this.maxSimultaneousLights = 4;
  101595. /**
  101596. * Keep track of the image processing observer to allow dispose and replace.
  101597. */
  101598. _this._imageProcessingObserver = null;
  101599. /**
  101600. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101601. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101602. */
  101603. _this.switchToBGR = false;
  101604. // Temp values kept as cache in the material.
  101605. _this._renderTargets = new BABYLON.SmartArray(16);
  101606. _this._reflectionControls = BABYLON.Vector4.Zero();
  101607. _this._white = BABYLON.Color3.White();
  101608. _this._primaryShadowColor = BABYLON.Color3.Black();
  101609. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101610. // Setup the default processing configuration to the scene.
  101611. _this._attachImageProcessingConfiguration(null);
  101612. _this.getRenderTargetTextures = function () {
  101613. _this._renderTargets.reset();
  101614. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101615. _this._renderTargets.push(_this._diffuseTexture);
  101616. }
  101617. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101618. _this._renderTargets.push(_this._reflectionTexture);
  101619. }
  101620. return _this._renderTargets;
  101621. };
  101622. return _this;
  101623. }
  101624. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101625. /**
  101626. * Experimental Internal Use Only.
  101627. *
  101628. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101629. * This acts as a helper to set the primary color to a more "human friendly" value.
  101630. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101631. * output color as close as possible from the chosen value.
  101632. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101633. * part of lighting setup.)
  101634. */
  101635. get: function () {
  101636. return this.__perceptualColor;
  101637. },
  101638. set: function (value) {
  101639. this.__perceptualColor = value;
  101640. this._computePrimaryColorFromPerceptualColor();
  101641. this._markAllSubMeshesAsLightsDirty();
  101642. },
  101643. enumerable: true,
  101644. configurable: true
  101645. });
  101646. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101647. /**
  101648. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101649. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101650. */
  101651. get: function () {
  101652. return this._primaryColorShadowLevel;
  101653. },
  101654. set: function (value) {
  101655. this._primaryColorShadowLevel = value;
  101656. this._computePrimaryColors();
  101657. this._markAllSubMeshesAsLightsDirty();
  101658. },
  101659. enumerable: true,
  101660. configurable: true
  101661. });
  101662. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101663. /**
  101664. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101665. * The primary color is used at the level chosen to define what the white area would look.
  101666. */
  101667. get: function () {
  101668. return this._primaryColorHighlightLevel;
  101669. },
  101670. set: function (value) {
  101671. this._primaryColorHighlightLevel = value;
  101672. this._computePrimaryColors();
  101673. this._markAllSubMeshesAsLightsDirty();
  101674. },
  101675. enumerable: true,
  101676. configurable: true
  101677. });
  101678. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101679. /**
  101680. * Sets the reflection reflectance fresnel values according to the default standard
  101681. * empirically know to work well :-)
  101682. */
  101683. set: function (value) {
  101684. var reflectionWeight = value;
  101685. if (reflectionWeight < 0.5) {
  101686. reflectionWeight = reflectionWeight * 2.0;
  101687. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101688. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101689. }
  101690. else {
  101691. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101692. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101693. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101694. }
  101695. },
  101696. enumerable: true,
  101697. configurable: true
  101698. });
  101699. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101700. /**
  101701. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101702. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101703. * Recommended to be keep at 1.0 except for special cases.
  101704. */
  101705. get: function () {
  101706. return this._fovMultiplier;
  101707. },
  101708. set: function (value) {
  101709. if (isNaN(value)) {
  101710. value = 1.0;
  101711. }
  101712. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101713. },
  101714. enumerable: true,
  101715. configurable: true
  101716. });
  101717. /**
  101718. * Attaches a new image processing configuration to the PBR Material.
  101719. * @param configuration (if null the scene configuration will be use)
  101720. */
  101721. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101722. var _this = this;
  101723. if (configuration === this._imageProcessingConfiguration) {
  101724. return;
  101725. }
  101726. // Detaches observer.
  101727. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101728. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101729. }
  101730. // Pick the scene configuration if needed.
  101731. if (!configuration) {
  101732. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101733. }
  101734. else {
  101735. this._imageProcessingConfiguration = configuration;
  101736. }
  101737. // Attaches observer.
  101738. if (this._imageProcessingConfiguration) {
  101739. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101740. _this._computePrimaryColorFromPerceptualColor();
  101741. _this._markAllSubMeshesAsImageProcessingDirty();
  101742. });
  101743. }
  101744. };
  101745. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101746. /**
  101747. * Gets the image processing configuration used either in this material.
  101748. */
  101749. get: function () {
  101750. return this._imageProcessingConfiguration;
  101751. },
  101752. /**
  101753. * Sets the Default image processing configuration used either in the this material.
  101754. *
  101755. * If sets to null, the scene one is in use.
  101756. */
  101757. set: function (value) {
  101758. this._attachImageProcessingConfiguration(value);
  101759. // Ensure the effect will be rebuilt.
  101760. this._markAllSubMeshesAsTexturesDirty();
  101761. },
  101762. enumerable: true,
  101763. configurable: true
  101764. });
  101765. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101766. /**
  101767. * Gets wether the color curves effect is enabled.
  101768. */
  101769. get: function () {
  101770. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101771. },
  101772. /**
  101773. * Sets wether the color curves effect is enabled.
  101774. */
  101775. set: function (value) {
  101776. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101777. },
  101778. enumerable: true,
  101779. configurable: true
  101780. });
  101781. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101782. /**
  101783. * Gets wether the color grading effect is enabled.
  101784. */
  101785. get: function () {
  101786. return this.imageProcessingConfiguration.colorGradingEnabled;
  101787. },
  101788. /**
  101789. * Gets wether the color grading effect is enabled.
  101790. */
  101791. set: function (value) {
  101792. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101793. },
  101794. enumerable: true,
  101795. configurable: true
  101796. });
  101797. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101798. /**
  101799. * Gets wether tonemapping is enabled or not.
  101800. */
  101801. get: function () {
  101802. return this._imageProcessingConfiguration.toneMappingEnabled;
  101803. },
  101804. /**
  101805. * Sets wether tonemapping is enabled or not
  101806. */
  101807. set: function (value) {
  101808. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101809. },
  101810. enumerable: true,
  101811. configurable: true
  101812. });
  101813. ;
  101814. ;
  101815. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101816. /**
  101817. * The camera exposure used on this material.
  101818. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101819. * This corresponds to a photographic exposure.
  101820. */
  101821. get: function () {
  101822. return this._imageProcessingConfiguration.exposure;
  101823. },
  101824. /**
  101825. * The camera exposure used on this material.
  101826. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101827. * This corresponds to a photographic exposure.
  101828. */
  101829. set: function (value) {
  101830. this._imageProcessingConfiguration.exposure = value;
  101831. },
  101832. enumerable: true,
  101833. configurable: true
  101834. });
  101835. ;
  101836. ;
  101837. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101838. /**
  101839. * Gets The camera contrast used on this material.
  101840. */
  101841. get: function () {
  101842. return this._imageProcessingConfiguration.contrast;
  101843. },
  101844. /**
  101845. * Sets The camera contrast used on this material.
  101846. */
  101847. set: function (value) {
  101848. this._imageProcessingConfiguration.contrast = value;
  101849. },
  101850. enumerable: true,
  101851. configurable: true
  101852. });
  101853. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101854. /**
  101855. * Gets the Color Grading 2D Lookup Texture.
  101856. */
  101857. get: function () {
  101858. return this._imageProcessingConfiguration.colorGradingTexture;
  101859. },
  101860. /**
  101861. * Sets the Color Grading 2D Lookup Texture.
  101862. */
  101863. set: function (value) {
  101864. this.imageProcessingConfiguration.colorGradingTexture = value;
  101865. },
  101866. enumerable: true,
  101867. configurable: true
  101868. });
  101869. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101870. /**
  101871. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101872. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101873. * 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;
  101874. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101875. */
  101876. get: function () {
  101877. return this.imageProcessingConfiguration.colorCurves;
  101878. },
  101879. /**
  101880. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101881. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101882. * 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;
  101883. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101884. */
  101885. set: function (value) {
  101886. this.imageProcessingConfiguration.colorCurves = value;
  101887. },
  101888. enumerable: true,
  101889. configurable: true
  101890. });
  101891. /**
  101892. * The entire material has been created in order to prevent overdraw.
  101893. * @returns false
  101894. */
  101895. BackgroundMaterial.prototype.needAlphaTesting = function () {
  101896. return true;
  101897. };
  101898. /**
  101899. * The entire material has been created in order to prevent overdraw.
  101900. * @returns true if blending is enable
  101901. */
  101902. BackgroundMaterial.prototype.needAlphaBlending = function () {
  101903. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  101904. };
  101905. /**
  101906. * Checks wether the material is ready to be rendered for a given mesh.
  101907. * @param mesh The mesh to render
  101908. * @param subMesh The submesh to check against
  101909. * @param useInstances Specify wether or not the material is used with instances
  101910. * @returns true if all the dependencies are ready (Textures, Effects...)
  101911. */
  101912. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  101913. var _this = this;
  101914. if (useInstances === void 0) { useInstances = false; }
  101915. if (subMesh.effect && this.isFrozen) {
  101916. if (this._wasPreviouslyReady) {
  101917. return true;
  101918. }
  101919. }
  101920. if (!subMesh._materialDefines) {
  101921. subMesh._materialDefines = new BackgroundMaterialDefines();
  101922. }
  101923. var scene = this.getScene();
  101924. var defines = subMesh._materialDefines;
  101925. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  101926. if (defines._renderId === scene.getRenderId()) {
  101927. return true;
  101928. }
  101929. }
  101930. var engine = scene.getEngine();
  101931. // Lights
  101932. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  101933. defines._needNormals = true;
  101934. // Textures
  101935. if (defines._areTexturesDirty) {
  101936. defines._needUVs = false;
  101937. if (scene.texturesEnabled) {
  101938. if (scene.getEngine().getCaps().textureLOD) {
  101939. defines.TEXTURELODSUPPORT = true;
  101940. }
  101941. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101942. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  101943. return false;
  101944. }
  101945. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  101946. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  101947. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  101948. defines.OPACITYFRESNEL = this._opacityFresnel;
  101949. }
  101950. else {
  101951. defines.DIFFUSE = false;
  101952. defines.DIFFUSEHASALPHA = false;
  101953. defines.GAMMADIFFUSE = false;
  101954. defines.OPACITYFRESNEL = false;
  101955. }
  101956. var reflectionTexture = this._reflectionTexture;
  101957. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101958. if (!reflectionTexture.isReadyOrNotBlocking()) {
  101959. return false;
  101960. }
  101961. defines.REFLECTION = true;
  101962. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  101963. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  101964. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  101965. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  101966. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  101967. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  101968. defines.REFLECTIONBGR = this.switchToBGR;
  101969. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  101970. defines.INVERTCUBICMAP = true;
  101971. }
  101972. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  101973. switch (reflectionTexture.coordinatesMode) {
  101974. case BABYLON.Texture.EXPLICIT_MODE:
  101975. defines.REFLECTIONMAP_EXPLICIT = true;
  101976. break;
  101977. case BABYLON.Texture.PLANAR_MODE:
  101978. defines.REFLECTIONMAP_PLANAR = true;
  101979. break;
  101980. case BABYLON.Texture.PROJECTION_MODE:
  101981. defines.REFLECTIONMAP_PROJECTION = true;
  101982. break;
  101983. case BABYLON.Texture.SKYBOX_MODE:
  101984. defines.REFLECTIONMAP_SKYBOX = true;
  101985. break;
  101986. case BABYLON.Texture.SPHERICAL_MODE:
  101987. defines.REFLECTIONMAP_SPHERICAL = true;
  101988. break;
  101989. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  101990. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  101991. break;
  101992. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  101993. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  101994. break;
  101995. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  101996. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  101997. break;
  101998. case BABYLON.Texture.CUBIC_MODE:
  101999. case BABYLON.Texture.INVCUBIC_MODE:
  102000. default:
  102001. defines.REFLECTIONMAP_CUBIC = true;
  102002. break;
  102003. }
  102004. if (this.reflectionFresnel) {
  102005. defines.REFLECTIONFRESNEL = true;
  102006. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102007. this._reflectionControls.x = this.reflectionAmount;
  102008. this._reflectionControls.y = this.reflectionReflectance0;
  102009. this._reflectionControls.z = this.reflectionReflectance90;
  102010. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102011. }
  102012. else {
  102013. defines.REFLECTIONFRESNEL = false;
  102014. defines.REFLECTIONFALLOFF = false;
  102015. }
  102016. }
  102017. else {
  102018. defines.REFLECTION = false;
  102019. defines.REFLECTIONFRESNEL = false;
  102020. defines.REFLECTIONFALLOFF = false;
  102021. defines.REFLECTIONBLUR = false;
  102022. defines.REFLECTIONMAP_3D = false;
  102023. defines.REFLECTIONMAP_SPHERICAL = false;
  102024. defines.REFLECTIONMAP_PLANAR = false;
  102025. defines.REFLECTIONMAP_CUBIC = false;
  102026. defines.REFLECTIONMAP_PROJECTION = false;
  102027. defines.REFLECTIONMAP_SKYBOX = false;
  102028. defines.REFLECTIONMAP_EXPLICIT = false;
  102029. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102030. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102031. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102032. defines.INVERTCUBICMAP = false;
  102033. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102034. defines.LODINREFLECTIONALPHA = false;
  102035. defines.GAMMAREFLECTION = false;
  102036. defines.RGBDREFLECTION = false;
  102037. }
  102038. }
  102039. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102040. defines.USERGBCOLOR = this._useRGBColor;
  102041. defines.NOISE = this._enableNoise;
  102042. }
  102043. if (defines._areLightsDirty) {
  102044. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102045. }
  102046. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102047. if (!this._imageProcessingConfiguration.isReady()) {
  102048. return false;
  102049. }
  102050. this._imageProcessingConfiguration.prepareDefines(defines);
  102051. }
  102052. // Misc.
  102053. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102054. // Values that need to be evaluated on every frame
  102055. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102056. // Attribs
  102057. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102058. if (mesh) {
  102059. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102060. mesh.createNormals(true);
  102061. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102062. }
  102063. }
  102064. }
  102065. // Get correct effect
  102066. if (defines.isDirty) {
  102067. defines.markAsProcessed();
  102068. scene.resetCachedMaterial();
  102069. // Fallbacks
  102070. var fallbacks = new BABYLON.EffectFallbacks();
  102071. if (defines.FOG) {
  102072. fallbacks.addFallback(0, "FOG");
  102073. }
  102074. if (defines.POINTSIZE) {
  102075. fallbacks.addFallback(1, "POINTSIZE");
  102076. }
  102077. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102078. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102079. fallbacks.addCPUSkinningFallback(0, mesh);
  102080. }
  102081. //Attributes
  102082. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102083. if (defines.NORMAL) {
  102084. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102085. }
  102086. if (defines.UV1) {
  102087. attribs.push(BABYLON.VertexBuffer.UVKind);
  102088. }
  102089. if (defines.UV2) {
  102090. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102091. }
  102092. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102093. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102094. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102095. "vFogInfos", "vFogColor", "pointSize",
  102096. "vClipPlane", "mBones",
  102097. "vPrimaryColor", "vPrimaryColorShadow",
  102098. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102099. "shadowLevel", "alpha",
  102100. "vBackgroundCenter", "vReflectionControl",
  102101. "vDiffuseInfos", "diffuseMatrix",
  102102. ];
  102103. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102104. var uniformBuffers = ["Material", "Scene"];
  102105. if (BABYLON.ImageProcessingConfiguration) {
  102106. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102107. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102108. }
  102109. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102110. uniformsNames: uniforms,
  102111. uniformBuffersNames: uniformBuffers,
  102112. samplers: samplers,
  102113. defines: defines,
  102114. maxSimultaneousLights: this._maxSimultaneousLights
  102115. });
  102116. var onCompiled = function (effect) {
  102117. if (_this.onCompiled) {
  102118. _this.onCompiled(effect);
  102119. }
  102120. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102121. };
  102122. var join = defines.toString();
  102123. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102124. attributes: attribs,
  102125. uniformsNames: uniforms,
  102126. uniformBuffersNames: uniformBuffers,
  102127. samplers: samplers,
  102128. defines: join,
  102129. fallbacks: fallbacks,
  102130. onCompiled: onCompiled,
  102131. onError: this.onError,
  102132. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102133. }, engine), defines);
  102134. this.buildUniformLayout();
  102135. }
  102136. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102137. return false;
  102138. }
  102139. defines._renderId = scene.getRenderId();
  102140. this._wasPreviouslyReady = true;
  102141. return true;
  102142. };
  102143. /**
  102144. * Compute the primary color according to the chosen perceptual color.
  102145. */
  102146. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102147. if (!this.__perceptualColor) {
  102148. return;
  102149. }
  102150. this._primaryColor.copyFrom(this.__perceptualColor);
  102151. // Revert gamma space.
  102152. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102153. // Revert image processing configuration.
  102154. if (this._imageProcessingConfiguration) {
  102155. // Revert Exposure.
  102156. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102157. }
  102158. this._computePrimaryColors();
  102159. };
  102160. /**
  102161. * Compute the highlights and shadow colors according to their chosen levels.
  102162. */
  102163. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102164. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  102165. return;
  102166. }
  102167. // Find the highlight color based on the configuration.
  102168. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  102169. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  102170. // Find the shadow color based on the configuration.
  102171. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  102172. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  102173. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  102174. };
  102175. /**
  102176. * Build the uniform buffer used in the material.
  102177. */
  102178. BackgroundMaterial.prototype.buildUniformLayout = function () {
  102179. // Order is important !
  102180. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  102181. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  102182. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  102183. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  102184. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  102185. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  102186. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  102187. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  102188. this._uniformBuffer.addUniform("pointSize", 1);
  102189. this._uniformBuffer.addUniform("shadowLevel", 1);
  102190. this._uniformBuffer.addUniform("alpha", 1);
  102191. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  102192. this._uniformBuffer.addUniform("vReflectionControl", 4);
  102193. this._uniformBuffer.create();
  102194. };
  102195. /**
  102196. * Unbind the material.
  102197. */
  102198. BackgroundMaterial.prototype.unbind = function () {
  102199. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  102200. this._uniformBuffer.setTexture("diffuseSampler", null);
  102201. }
  102202. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  102203. this._uniformBuffer.setTexture("reflectionSampler", null);
  102204. }
  102205. _super.prototype.unbind.call(this);
  102206. };
  102207. /**
  102208. * Bind only the world matrix to the material.
  102209. * @param world The world matrix to bind.
  102210. */
  102211. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  102212. this._activeEffect.setMatrix("world", world);
  102213. };
  102214. /**
  102215. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  102216. * @param world The world matrix to bind.
  102217. * @param subMesh The submesh to bind for.
  102218. */
  102219. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  102220. var scene = this.getScene();
  102221. var defines = subMesh._materialDefines;
  102222. if (!defines) {
  102223. return;
  102224. }
  102225. var effect = subMesh.effect;
  102226. if (!effect) {
  102227. return;
  102228. }
  102229. this._activeEffect = effect;
  102230. // Matrices
  102231. this.bindOnlyWorldMatrix(world);
  102232. // Bones
  102233. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  102234. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  102235. if (mustRebind) {
  102236. this._uniformBuffer.bindToEffect(effect, "Material");
  102237. this.bindViewProjection(effect);
  102238. var reflectionTexture = this._reflectionTexture;
  102239. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  102240. // Texture uniforms
  102241. if (scene.texturesEnabled) {
  102242. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102243. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  102244. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  102245. }
  102246. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102247. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  102248. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  102249. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  102250. }
  102251. }
  102252. if (this.shadowLevel > 0) {
  102253. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  102254. }
  102255. this._uniformBuffer.updateFloat("alpha", this.alpha);
  102256. // Point size
  102257. if (this.pointsCloud) {
  102258. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  102259. }
  102260. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  102261. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  102262. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  102263. }
  102264. else {
  102265. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  102266. }
  102267. }
  102268. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  102269. // Textures
  102270. if (scene.texturesEnabled) {
  102271. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102272. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  102273. }
  102274. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102275. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  102276. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102277. }
  102278. else if (!defines.REFLECTIONBLUR) {
  102279. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102280. }
  102281. else {
  102282. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  102283. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  102284. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  102285. }
  102286. if (defines.REFLECTIONFRESNEL) {
  102287. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  102288. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  102289. }
  102290. }
  102291. }
  102292. // Clip plane
  102293. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102294. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102295. }
  102296. if (mustRebind || !this.isFrozen) {
  102297. if (scene.lightsEnabled) {
  102298. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102299. }
  102300. // View
  102301. this.bindView(effect);
  102302. // Fog
  102303. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102304. // image processing
  102305. if (this._imageProcessingConfiguration) {
  102306. this._imageProcessingConfiguration.bind(this._activeEffect);
  102307. }
  102308. }
  102309. this._uniformBuffer.update();
  102310. this._afterBind(mesh, this._activeEffect);
  102311. };
  102312. /**
  102313. * Dispose the material.
  102314. * @param forceDisposeEffect Force disposal of the associated effect.
  102315. * @param forceDisposeTextures Force disposal of the associated textures.
  102316. */
  102317. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102318. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102319. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102320. if (forceDisposeTextures) {
  102321. if (this.diffuseTexture) {
  102322. this.diffuseTexture.dispose();
  102323. }
  102324. if (this.reflectionTexture) {
  102325. this.reflectionTexture.dispose();
  102326. }
  102327. }
  102328. this._renderTargets.dispose();
  102329. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102330. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102331. }
  102332. _super.prototype.dispose.call(this, forceDisposeEffect);
  102333. };
  102334. /**
  102335. * Clones the material.
  102336. * @param name The cloned name.
  102337. * @returns The cloned material.
  102338. */
  102339. BackgroundMaterial.prototype.clone = function (name) {
  102340. var _this = this;
  102341. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102342. };
  102343. /**
  102344. * Serializes the current material to its JSON representation.
  102345. * @returns The JSON representation.
  102346. */
  102347. BackgroundMaterial.prototype.serialize = function () {
  102348. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102349. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102350. return serializationObject;
  102351. };
  102352. /**
  102353. * Gets the class name of the material
  102354. * @returns "BackgroundMaterial"
  102355. */
  102356. BackgroundMaterial.prototype.getClassName = function () {
  102357. return "BackgroundMaterial";
  102358. };
  102359. /**
  102360. * Parse a JSON input to create back a background material.
  102361. * @param source The JSON data to parse
  102362. * @param scene The scene to create the parsed material in
  102363. * @param rootUrl The root url of the assets the material depends upon
  102364. * @returns the instantiated BackgroundMaterial.
  102365. */
  102366. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102367. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102368. };
  102369. /**
  102370. * Standard reflectance value at parallel view angle.
  102371. */
  102372. BackgroundMaterial.StandardReflectance0 = 0.05;
  102373. /**
  102374. * Standard reflectance value at grazing angle.
  102375. */
  102376. BackgroundMaterial.StandardReflectance90 = 0.5;
  102377. __decorate([
  102378. BABYLON.serializeAsColor3()
  102379. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102380. __decorate([
  102381. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102382. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102383. __decorate([
  102384. BABYLON.serializeAsColor3()
  102385. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102386. __decorate([
  102387. BABYLON.serialize()
  102388. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102389. __decorate([
  102390. BABYLON.serialize()
  102391. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102392. __decorate([
  102393. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102394. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102395. __decorate([
  102396. BABYLON.serializeAsTexture()
  102397. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102398. __decorate([
  102399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102400. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102401. __decorate([
  102402. BABYLON.serialize()
  102403. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102404. __decorate([
  102405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102406. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102407. __decorate([
  102408. BABYLON.serializeAsTexture()
  102409. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102410. __decorate([
  102411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102412. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102413. __decorate([
  102414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102415. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102416. __decorate([
  102417. BABYLON.serialize()
  102418. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102419. __decorate([
  102420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102421. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102422. __decorate([
  102423. BABYLON.serializeAsVector3()
  102424. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102425. __decorate([
  102426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102427. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102428. __decorate([
  102429. BABYLON.serialize()
  102430. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102431. __decorate([
  102432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102433. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102434. __decorate([
  102435. BABYLON.serialize()
  102436. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102437. __decorate([
  102438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102439. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102440. __decorate([
  102441. BABYLON.serialize()
  102442. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102443. __decorate([
  102444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102445. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102446. __decorate([
  102447. BABYLON.serialize()
  102448. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102449. __decorate([
  102450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102451. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102452. __decorate([
  102453. BABYLON.serialize()
  102454. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102455. __decorate([
  102456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102457. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102458. __decorate([
  102459. BABYLON.serialize()
  102460. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102461. __decorate([
  102462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102463. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102464. __decorate([
  102465. BABYLON.serialize()
  102466. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102467. __decorate([
  102468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102469. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102470. __decorate([
  102471. BABYLON.serialize()
  102472. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102473. __decorate([
  102474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102475. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102476. __decorate([
  102477. BABYLON.serialize()
  102478. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102479. __decorate([
  102480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102481. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102482. __decorate([
  102483. BABYLON.serializeAsImageProcessingConfiguration()
  102484. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102485. return BackgroundMaterial;
  102486. }(BABYLON.PushMaterial));
  102487. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102488. })(BABYLON || (BABYLON = {}));
  102489. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102490. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102491. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102492. s = arguments[i];
  102493. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102494. t[p] = s[p];
  102495. }
  102496. return t;
  102497. };
  102498. var BABYLON;
  102499. (function (BABYLON) {
  102500. /**
  102501. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102502. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102503. * It also helps with the default setup of your imageProcessing configuration.
  102504. */
  102505. var EnvironmentHelper = /** @class */ (function () {
  102506. /**
  102507. * constructor
  102508. * @param options
  102509. * @param scene The scene to add the material to
  102510. */
  102511. function EnvironmentHelper(options, scene) {
  102512. var _this = this;
  102513. this._errorHandler = function (message, exception) {
  102514. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102515. };
  102516. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102517. this._scene = scene;
  102518. this.onErrorObservable = new BABYLON.Observable();
  102519. this._setupBackground();
  102520. this._setupImageProcessing();
  102521. }
  102522. /**
  102523. * Creates the default options for the helper.
  102524. */
  102525. EnvironmentHelper._getDefaultOptions = function () {
  102526. return {
  102527. createGround: true,
  102528. groundSize: 15,
  102529. groundTexture: this._groundTextureCDNUrl,
  102530. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102531. groundOpacity: 0.9,
  102532. enableGroundShadow: true,
  102533. groundShadowLevel: 0.5,
  102534. enableGroundMirror: false,
  102535. groundMirrorSizeRatio: 0.3,
  102536. groundMirrorBlurKernel: 64,
  102537. groundMirrorAmount: 1,
  102538. groundMirrorFresnelWeight: 1,
  102539. groundMirrorFallOffDistance: 0,
  102540. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102541. groundYBias: 0.00001,
  102542. createSkybox: true,
  102543. skyboxSize: 20,
  102544. skyboxTexture: this._skyboxTextureCDNUrl,
  102545. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102546. backgroundYRotation: 0,
  102547. sizeAuto: true,
  102548. rootPosition: BABYLON.Vector3.Zero(),
  102549. setupImageProcessing: true,
  102550. environmentTexture: this._environmentTextureCDNUrl,
  102551. cameraExposure: 0.8,
  102552. cameraContrast: 1.2,
  102553. toneMappingEnabled: true,
  102554. };
  102555. };
  102556. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102557. /**
  102558. * Gets the root mesh created by the helper.
  102559. */
  102560. get: function () {
  102561. return this._rootMesh;
  102562. },
  102563. enumerable: true,
  102564. configurable: true
  102565. });
  102566. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102567. /**
  102568. * Gets the skybox created by the helper.
  102569. */
  102570. get: function () {
  102571. return this._skybox;
  102572. },
  102573. enumerable: true,
  102574. configurable: true
  102575. });
  102576. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102577. /**
  102578. * Gets the skybox texture created by the helper.
  102579. */
  102580. get: function () {
  102581. return this._skyboxTexture;
  102582. },
  102583. enumerable: true,
  102584. configurable: true
  102585. });
  102586. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102587. /**
  102588. * Gets the skybox material created by the helper.
  102589. */
  102590. get: function () {
  102591. return this._skyboxMaterial;
  102592. },
  102593. enumerable: true,
  102594. configurable: true
  102595. });
  102596. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102597. /**
  102598. * Gets the ground mesh created by the helper.
  102599. */
  102600. get: function () {
  102601. return this._ground;
  102602. },
  102603. enumerable: true,
  102604. configurable: true
  102605. });
  102606. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102607. /**
  102608. * Gets the ground texture created by the helper.
  102609. */
  102610. get: function () {
  102611. return this._groundTexture;
  102612. },
  102613. enumerable: true,
  102614. configurable: true
  102615. });
  102616. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102617. /**
  102618. * Gets the ground mirror created by the helper.
  102619. */
  102620. get: function () {
  102621. return this._groundMirror;
  102622. },
  102623. enumerable: true,
  102624. configurable: true
  102625. });
  102626. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102627. /**
  102628. * Gets the ground mirror render list to helps pushing the meshes
  102629. * you wish in the ground reflection.
  102630. */
  102631. get: function () {
  102632. if (this._groundMirror) {
  102633. return this._groundMirror.renderList;
  102634. }
  102635. return null;
  102636. },
  102637. enumerable: true,
  102638. configurable: true
  102639. });
  102640. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102641. /**
  102642. * Gets the ground material created by the helper.
  102643. */
  102644. get: function () {
  102645. return this._groundMaterial;
  102646. },
  102647. enumerable: true,
  102648. configurable: true
  102649. });
  102650. /**
  102651. * Updates the background according to the new options
  102652. * @param options
  102653. */
  102654. EnvironmentHelper.prototype.updateOptions = function (options) {
  102655. var newOptions = __assign({}, this._options, options);
  102656. if (this._ground && !newOptions.createGround) {
  102657. this._ground.dispose();
  102658. this._ground = null;
  102659. }
  102660. if (this._groundMaterial && !newOptions.createGround) {
  102661. this._groundMaterial.dispose();
  102662. this._groundMaterial = null;
  102663. }
  102664. if (this._groundTexture) {
  102665. if (this._options.groundTexture != newOptions.groundTexture) {
  102666. this._groundTexture.dispose();
  102667. this._groundTexture = null;
  102668. }
  102669. }
  102670. if (this._skybox && !newOptions.createSkybox) {
  102671. this._skybox.dispose();
  102672. this._skybox = null;
  102673. }
  102674. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102675. this._skyboxMaterial.dispose();
  102676. this._skyboxMaterial = null;
  102677. }
  102678. if (this._skyboxTexture) {
  102679. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102680. this._skyboxTexture.dispose();
  102681. this._skyboxTexture = null;
  102682. }
  102683. }
  102684. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102685. this._groundMirror.dispose();
  102686. this._groundMirror = null;
  102687. }
  102688. if (this._scene.environmentTexture) {
  102689. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102690. this._scene.environmentTexture.dispose();
  102691. }
  102692. }
  102693. this._options = newOptions;
  102694. this._setupBackground();
  102695. this._setupImageProcessing();
  102696. };
  102697. /**
  102698. * Sets the primary color of all the available elements.
  102699. * @param color the main color to affect to the ground and the background
  102700. */
  102701. EnvironmentHelper.prototype.setMainColor = function (color) {
  102702. if (this.groundMaterial) {
  102703. this.groundMaterial.primaryColor = color;
  102704. }
  102705. if (this.skyboxMaterial) {
  102706. this.skyboxMaterial.primaryColor = color;
  102707. }
  102708. if (this.groundMirror) {
  102709. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102710. }
  102711. };
  102712. /**
  102713. * Setup the image processing according to the specified options.
  102714. */
  102715. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102716. if (this._options.setupImageProcessing) {
  102717. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102718. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102719. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102720. this._setupEnvironmentTexture();
  102721. }
  102722. };
  102723. /**
  102724. * Setup the environment texture according to the specified options.
  102725. */
  102726. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102727. if (this._scene.environmentTexture) {
  102728. return;
  102729. }
  102730. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102731. this._scene.environmentTexture = this._options.environmentTexture;
  102732. return;
  102733. }
  102734. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102735. this._scene.environmentTexture = environmentTexture;
  102736. };
  102737. /**
  102738. * Setup the background according to the specified options.
  102739. */
  102740. EnvironmentHelper.prototype._setupBackground = function () {
  102741. if (!this._rootMesh) {
  102742. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102743. }
  102744. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102745. var sceneSize = this._getSceneSize();
  102746. if (this._options.createGround) {
  102747. this._setupGround(sceneSize);
  102748. this._setupGroundMaterial();
  102749. this._setupGroundDiffuseTexture();
  102750. if (this._options.enableGroundMirror) {
  102751. this._setupGroundMirrorTexture(sceneSize);
  102752. }
  102753. this._setupMirrorInGroundMaterial();
  102754. }
  102755. if (this._options.createSkybox) {
  102756. this._setupSkybox(sceneSize);
  102757. this._setupSkyboxMaterial();
  102758. this._setupSkyboxReflectionTexture();
  102759. }
  102760. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102761. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102762. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102763. };
  102764. /**
  102765. * Get the scene sizes according to the setup.
  102766. */
  102767. EnvironmentHelper.prototype._getSceneSize = function () {
  102768. var _this = this;
  102769. var groundSize = this._options.groundSize;
  102770. var skyboxSize = this._options.skyboxSize;
  102771. var rootPosition = this._options.rootPosition;
  102772. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102773. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102774. }
  102775. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102776. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102777. });
  102778. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102779. if (this._options.sizeAuto) {
  102780. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102781. this._scene.activeCamera.upperRadiusLimit) {
  102782. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102783. skyboxSize = groundSize;
  102784. }
  102785. var sceneDiagonalLenght = sceneDiagonal.length();
  102786. if (sceneDiagonalLenght > groundSize) {
  102787. groundSize = sceneDiagonalLenght * 2;
  102788. skyboxSize = groundSize;
  102789. }
  102790. // 10 % bigger.
  102791. groundSize *= 1.1;
  102792. skyboxSize *= 1.5;
  102793. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102794. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102795. }
  102796. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102797. };
  102798. /**
  102799. * Setup the ground according to the specified options.
  102800. */
  102801. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102802. var _this = this;
  102803. if (!this._ground || this._ground.isDisposed()) {
  102804. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102805. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102806. this._ground.parent = this._rootMesh;
  102807. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102808. }
  102809. this._ground.receiveShadows = this._options.enableGroundShadow;
  102810. };
  102811. /**
  102812. * Setup the ground material according to the specified options.
  102813. */
  102814. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102815. if (!this._groundMaterial) {
  102816. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102817. }
  102818. this._groundMaterial.alpha = this._options.groundOpacity;
  102819. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102820. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102821. this._groundMaterial.primaryColor = this._options.groundColor;
  102822. this._groundMaterial.useRGBColor = false;
  102823. this._groundMaterial.enableNoise = true;
  102824. if (this._ground) {
  102825. this._ground.material = this._groundMaterial;
  102826. }
  102827. };
  102828. /**
  102829. * Setup the ground diffuse texture according to the specified options.
  102830. */
  102831. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102832. if (!this._groundMaterial) {
  102833. return;
  102834. }
  102835. if (this._groundTexture) {
  102836. return;
  102837. }
  102838. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102839. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102840. return;
  102841. }
  102842. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102843. diffuseTexture.gammaSpace = false;
  102844. diffuseTexture.hasAlpha = true;
  102845. this._groundMaterial.diffuseTexture = diffuseTexture;
  102846. };
  102847. /**
  102848. * Setup the ground mirror texture according to the specified options.
  102849. */
  102850. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102851. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102852. if (!this._groundMirror) {
  102853. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102854. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102855. this._groundMirror.anisotropicFilteringLevel = 1;
  102856. this._groundMirror.wrapU = wrapping;
  102857. this._groundMirror.wrapV = wrapping;
  102858. this._groundMirror.gammaSpace = false;
  102859. if (this._groundMirror.renderList) {
  102860. for (var i = 0; i < this._scene.meshes.length; i++) {
  102861. var mesh = this._scene.meshes[i];
  102862. if (mesh !== this._ground &&
  102863. mesh !== this._skybox &&
  102864. mesh !== this._rootMesh) {
  102865. this._groundMirror.renderList.push(mesh);
  102866. }
  102867. }
  102868. }
  102869. }
  102870. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102871. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102872. };
  102873. /**
  102874. * Setup the ground to receive the mirror texture.
  102875. */
  102876. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102877. if (this._groundMaterial) {
  102878. this._groundMaterial.reflectionTexture = this._groundMirror;
  102879. this._groundMaterial.reflectionFresnel = true;
  102880. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  102881. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  102882. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  102883. }
  102884. };
  102885. /**
  102886. * Setup the skybox according to the specified options.
  102887. */
  102888. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  102889. var _this = this;
  102890. if (!this._skybox || this._skybox.isDisposed()) {
  102891. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  102892. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  102893. }
  102894. this._skybox.parent = this._rootMesh;
  102895. };
  102896. /**
  102897. * Setup the skybox material according to the specified options.
  102898. */
  102899. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  102900. if (!this._skybox) {
  102901. return;
  102902. }
  102903. if (!this._skyboxMaterial) {
  102904. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  102905. }
  102906. this._skyboxMaterial.useRGBColor = false;
  102907. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  102908. this._skyboxMaterial.enableNoise = true;
  102909. this._skybox.material = this._skyboxMaterial;
  102910. };
  102911. /**
  102912. * Setup the skybox reflection texture according to the specified options.
  102913. */
  102914. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  102915. if (!this._skyboxMaterial) {
  102916. return;
  102917. }
  102918. if (this._skyboxTexture) {
  102919. return;
  102920. }
  102921. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  102922. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  102923. return;
  102924. }
  102925. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102926. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  102927. this._skyboxTexture.gammaSpace = false;
  102928. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  102929. };
  102930. /**
  102931. * Dispose all the elements created by the Helper.
  102932. */
  102933. EnvironmentHelper.prototype.dispose = function () {
  102934. if (this._groundMaterial) {
  102935. this._groundMaterial.dispose(true, true);
  102936. }
  102937. if (this._skyboxMaterial) {
  102938. this._skyboxMaterial.dispose(true, true);
  102939. }
  102940. this._rootMesh.dispose(false);
  102941. };
  102942. /**
  102943. * Default ground texture URL.
  102944. */
  102945. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  102946. /**
  102947. * Default skybox texture URL.
  102948. */
  102949. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  102950. /**
  102951. * Default environment texture URL.
  102952. */
  102953. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  102954. return EnvironmentHelper;
  102955. }());
  102956. BABYLON.EnvironmentHelper = EnvironmentHelper;
  102957. })(BABYLON || (BABYLON = {}));
  102958. //# sourceMappingURL=babylon.environmentHelper.js.map
  102959. var BABYLON;
  102960. (function (BABYLON) {
  102961. /** Internal class used to store shapes for emitters */
  102962. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  102963. function ParticleSystemSetEmitterCreationOptions() {
  102964. }
  102965. return ParticleSystemSetEmitterCreationOptions;
  102966. }());
  102967. /**
  102968. * Represents a set of particle systems working together to create a specific effect
  102969. */
  102970. var ParticleSystemSet = /** @class */ (function () {
  102971. function ParticleSystemSet() {
  102972. /**
  102973. * Gets the particle system list
  102974. */
  102975. this.systems = new Array();
  102976. }
  102977. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  102978. /**
  102979. * Gets the emitter node used with this set
  102980. */
  102981. get: function () {
  102982. return this._emitterNode;
  102983. },
  102984. enumerable: true,
  102985. configurable: true
  102986. });
  102987. /**
  102988. * Creates a new emitter mesh as a sphere
  102989. * @param options defines the options used to create the sphere
  102990. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  102991. * @param scene defines the hosting scene
  102992. */
  102993. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  102994. if (this._emitterNode) {
  102995. this._emitterNode.dispose();
  102996. }
  102997. this._emitterCreationOptions = {
  102998. kind: "Sphere",
  102999. options: options,
  103000. renderingGroupId: renderingGroupId
  103001. };
  103002. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103003. emitterMesh.renderingGroupId = renderingGroupId;
  103004. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103005. material.emissiveColor = options.color;
  103006. emitterMesh.material = material;
  103007. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103008. var system = _a[_i];
  103009. system.emitter = emitterMesh;
  103010. }
  103011. this._emitterNode = emitterMesh;
  103012. };
  103013. /**
  103014. * Starts all particle systems of the set
  103015. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103016. */
  103017. ParticleSystemSet.prototype.start = function (emitter) {
  103018. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103019. var system = _a[_i];
  103020. if (emitter) {
  103021. system.emitter = emitter;
  103022. }
  103023. system.start();
  103024. }
  103025. };
  103026. /**
  103027. * Release all associated resources
  103028. */
  103029. ParticleSystemSet.prototype.dispose = function () {
  103030. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103031. var system = _a[_i];
  103032. system.dispose();
  103033. }
  103034. this.systems = [];
  103035. if (this._emitterNode) {
  103036. this._emitterNode.dispose();
  103037. this._emitterNode = null;
  103038. }
  103039. };
  103040. /**
  103041. * Serialize the set into a JSON compatible object
  103042. * @returns a JSON compatible representation of the set
  103043. */
  103044. ParticleSystemSet.prototype.serialize = function () {
  103045. var result = {};
  103046. result.systems = [];
  103047. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103048. var system = _a[_i];
  103049. result.systems.push(system.serialize());
  103050. }
  103051. if (this._emitterNode) {
  103052. result.emitter = this._emitterCreationOptions;
  103053. }
  103054. return result;
  103055. };
  103056. /**
  103057. * Parse a new ParticleSystemSet from a serialized source
  103058. * @param data defines a JSON compatible representation of the set
  103059. * @param scene defines the hosting scene
  103060. * @param gpu defines if we want GPU particles or CPU particles
  103061. * @returns a new ParticleSystemSet
  103062. */
  103063. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103064. if (gpu === void 0) { gpu = false; }
  103065. var result = new ParticleSystemSet();
  103066. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103067. scene = scene || BABYLON.Engine.LastCreatedScene;
  103068. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103069. var system = _a[_i];
  103070. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103071. }
  103072. if (data.emitter) {
  103073. var options = data.emitter.options;
  103074. switch (data.emitter.kind) {
  103075. case "Sphere":
  103076. result.setEmitterAsSphere({
  103077. diameter: options.diameter,
  103078. segments: options.segments,
  103079. color: BABYLON.Color3.FromArray(options.color)
  103080. }, data.emitter.renderingGroupId, scene);
  103081. break;
  103082. }
  103083. }
  103084. return result;
  103085. };
  103086. return ParticleSystemSet;
  103087. }());
  103088. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103089. })(BABYLON || (BABYLON = {}));
  103090. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103091. var BABYLON;
  103092. (function (BABYLON) {
  103093. /**
  103094. * This class is made for on one-liner static method to help creating particle system set.
  103095. */
  103096. var ParticleHelper = /** @class */ (function () {
  103097. function ParticleHelper() {
  103098. }
  103099. /**
  103100. * This is the main static method (one-liner) of this helper to create different particle systems
  103101. * @param type This string represents the type to the particle system to create
  103102. * @param scene The scene where the particle system should live
  103103. * @param gpu If the system will use gpu
  103104. * @returns the ParticleSystemSet created
  103105. */
  103106. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103107. if (gpu === void 0) { gpu = false; }
  103108. if (!scene) {
  103109. scene = BABYLON.Engine.LastCreatedScene;
  103110. ;
  103111. }
  103112. var token = {};
  103113. scene._addPendingData(token);
  103114. return new Promise(function (resolve, reject) {
  103115. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103116. scene._removePendingData(token);
  103117. return reject("Particle system with GPU is not supported.");
  103118. }
  103119. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103120. scene._removePendingData(token);
  103121. var newData = JSON.parse(data.toString());
  103122. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103123. }, undefined, undefined, undefined, function (req, exception) {
  103124. scene._removePendingData(token);
  103125. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103126. });
  103127. });
  103128. };
  103129. /**
  103130. * Static function used to export a particle system to a ParticleSystemSet variable.
  103131. * Please note that the emitter shape is not exported
  103132. * @param system defines the particle systems to export
  103133. */
  103134. ParticleHelper.ExportSet = function (systems) {
  103135. var set = new BABYLON.ParticleSystemSet();
  103136. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103137. var system = systems_1[_i];
  103138. set.systems.push(system);
  103139. }
  103140. return set;
  103141. };
  103142. /**
  103143. * Gets or sets base Assets URL
  103144. */
  103145. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103146. return ParticleHelper;
  103147. }());
  103148. BABYLON.ParticleHelper = ParticleHelper;
  103149. })(BABYLON || (BABYLON = {}));
  103150. //# sourceMappingURL=babylon.particleHelper.js.map
  103151. var BABYLON;
  103152. (function (BABYLON) {
  103153. /**
  103154. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103155. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103156. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103157. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103158. */
  103159. var VideoDome = /** @class */ (function (_super) {
  103160. __extends(VideoDome, _super);
  103161. /**
  103162. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103163. * @param name Element's name, child elements will append suffixes for their own names.
  103164. * @param urlsOrVideo defines the url(s) or the video element to use
  103165. * @param options An object containing optional or exposed sub element properties
  103166. */
  103167. function VideoDome(name, urlsOrVideo, options, scene) {
  103168. var _this = _super.call(this, name, scene) || this;
  103169. _this._useDirectMapping = false;
  103170. // set defaults and manage values
  103171. name = name || "videoDome";
  103172. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103173. options.clickToPlay = Boolean(options.clickToPlay);
  103174. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  103175. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  103176. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103177. if (options.useDirectMapping === undefined) {
  103178. _this._useDirectMapping = true;
  103179. }
  103180. else {
  103181. _this._useDirectMapping = options.useDirectMapping;
  103182. }
  103183. // create
  103184. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  103185. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103186. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  103187. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103188. // configure material
  103189. material.useEquirectangularFOV = true;
  103190. material.fovMultiplier = 1.0;
  103191. material.opacityFresnel = false;
  103192. if (_this._useDirectMapping) {
  103193. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103194. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103195. material.diffuseTexture = texture;
  103196. }
  103197. else {
  103198. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103199. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103200. material.reflectionTexture = texture;
  103201. }
  103202. // configure mesh
  103203. _this._mesh.material = material;
  103204. _this._mesh.parent = _this;
  103205. // optional configuration
  103206. if (options.clickToPlay) {
  103207. scene.onPointerUp = function () {
  103208. _this._videoTexture.video.play();
  103209. };
  103210. }
  103211. return _this;
  103212. }
  103213. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  103214. /**
  103215. * Gets the video texture being displayed on the sphere
  103216. */
  103217. get: function () {
  103218. return this._videoTexture;
  103219. },
  103220. enumerable: true,
  103221. configurable: true
  103222. });
  103223. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  103224. /**
  103225. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103226. * Also see the options.resolution property.
  103227. */
  103228. get: function () {
  103229. return this._material.fovMultiplier;
  103230. },
  103231. set: function (value) {
  103232. this._material.fovMultiplier = value;
  103233. },
  103234. enumerable: true,
  103235. configurable: true
  103236. });
  103237. /**
  103238. * Releases resources associated with this node.
  103239. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103240. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103241. */
  103242. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103243. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103244. this._videoTexture.dispose();
  103245. this._mesh.dispose();
  103246. this._material.dispose();
  103247. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103248. };
  103249. return VideoDome;
  103250. }(BABYLON.Node));
  103251. BABYLON.VideoDome = VideoDome;
  103252. })(BABYLON || (BABYLON = {}));
  103253. //# sourceMappingURL=babylon.videoDome.js.map
  103254. var BABYLON;
  103255. (function (BABYLON) {
  103256. /**
  103257. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  103258. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  103259. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  103260. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103261. */
  103262. var PhotoDome = /** @class */ (function (_super) {
  103263. __extends(PhotoDome, _super);
  103264. /**
  103265. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  103266. * @param name Element's name, child elements will append suffixes for their own names.
  103267. * @param urlsOfPhoto define the url of the photo to display
  103268. * @param options An object containing optional or exposed sub element properties
  103269. */
  103270. function PhotoDome(name, urlOfPhoto, options, scene) {
  103271. var _this = _super.call(this, name, scene) || this;
  103272. _this._useDirectMapping = false;
  103273. // set defaults and manage values
  103274. name = name || "photoDome";
  103275. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103276. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103277. if (options.useDirectMapping === undefined) {
  103278. _this._useDirectMapping = true;
  103279. }
  103280. else {
  103281. _this._useDirectMapping = options.useDirectMapping;
  103282. }
  103283. // create
  103284. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103285. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103286. // configure material
  103287. material.opacityFresnel = false;
  103288. material.useEquirectangularFOV = true;
  103289. material.fovMultiplier = 1.0;
  103290. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  103291. // configure mesh
  103292. _this._mesh.material = material;
  103293. _this._mesh.parent = _this;
  103294. return _this;
  103295. }
  103296. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103297. /**
  103298. * Gets or sets the texture being displayed on the sphere
  103299. */
  103300. get: function () {
  103301. return this._photoTexture;
  103302. },
  103303. set: function (value) {
  103304. if (this._photoTexture === value) {
  103305. return;
  103306. }
  103307. this._photoTexture = value;
  103308. if (this._useDirectMapping) {
  103309. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103310. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103311. this._material.diffuseTexture = this._photoTexture;
  103312. }
  103313. else {
  103314. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103315. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103316. this._material.reflectionTexture = this._photoTexture;
  103317. }
  103318. },
  103319. enumerable: true,
  103320. configurable: true
  103321. });
  103322. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103323. /**
  103324. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103325. * Also see the options.resolution property.
  103326. */
  103327. get: function () {
  103328. return this._material.fovMultiplier;
  103329. },
  103330. set: function (value) {
  103331. this._material.fovMultiplier = value;
  103332. },
  103333. enumerable: true,
  103334. configurable: true
  103335. });
  103336. /**
  103337. * Releases resources associated with this node.
  103338. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103339. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103340. */
  103341. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103342. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103343. this._photoTexture.dispose();
  103344. this._mesh.dispose();
  103345. this._material.dispose();
  103346. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103347. };
  103348. return PhotoDome;
  103349. }(BABYLON.Node));
  103350. BABYLON.PhotoDome = PhotoDome;
  103351. })(BABYLON || (BABYLON = {}));
  103352. //# sourceMappingURL=babylon.photoDome.js.map
  103353. 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\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=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.rgb*=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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \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 mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\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 mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,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;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*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(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-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;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction;\n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\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}","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\nvec4 reflectionColor=vec4(1.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=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.rgb*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.rgb,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"};
  103354. 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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\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=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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};"};
  103355. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  103356. globalObject["BABYLON"] = BABYLON;
  103357. //backwards compatibility
  103358. if(typeof earcut !== 'undefined') {
  103359. globalObject["Earcut"] = {
  103360. earcut: earcut
  103361. };
  103362. }
  103363. return BABYLON;
  103364. });
  103365. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21)))
  103366. /***/ }),
  103367. /* 1 */
  103368. /***/ (function(module, exports, __webpack_require__) {
  103369. "use strict";
  103370. Object.defineProperty(exports, "__esModule", { value: true });
  103371. var deepmerge = __webpack_require__(25);
  103372. var expDm = deepmerge['default'];
  103373. exports.deepmerge = expDm;
  103374. /**
  103375. * Is the provided string a URL?
  103376. *
  103377. * @param urlToCheck the url to inspect
  103378. */
  103379. function isUrl(urlToCheck) {
  103380. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  103381. return true;
  103382. }
  103383. return false;
  103384. }
  103385. exports.isUrl = isUrl;
  103386. /**
  103387. * Convert a string from kebab-case to camelCase
  103388. * @param s string to convert
  103389. */
  103390. function kebabToCamel(s) {
  103391. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  103392. }
  103393. exports.kebabToCamel = kebabToCamel;
  103394. //https://gist.github.com/youssman/745578062609e8acac9f
  103395. /**
  103396. * Convert a string from camelCase to kebab-case
  103397. * @param str string to convert
  103398. */
  103399. function camelToKebab(str) {
  103400. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  103401. }
  103402. exports.camelToKebab = camelToKebab;
  103403. /**
  103404. * This will extend an object with configuration values.
  103405. * What it practically does it take the keys from the configuration and set them on the object.
  103406. * I the configuration is a tree, it will traverse into the tree.
  103407. * @param object the object to extend
  103408. * @param config the configuration object that will extend the object
  103409. */
  103410. function extendClassWithConfig(object, config) {
  103411. if (!config)
  103412. return;
  103413. Object.keys(config).forEach(function (key) {
  103414. if (key in object && typeof object[key] !== 'function') {
  103415. // if (typeof object[key] === 'function') return;
  103416. // if it is an object, iterate internally until reaching basic types
  103417. if (typeof object[key] === 'object') {
  103418. extendClassWithConfig(object[key], config[key]);
  103419. }
  103420. else {
  103421. if (config[key] !== undefined) {
  103422. object[key] = config[key];
  103423. }
  103424. }
  103425. }
  103426. });
  103427. }
  103428. exports.extendClassWithConfig = extendClassWithConfig;
  103429. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQXVDO0FBRXZDLElBQUksS0FBSyxHQUFHLFNBQVMsQ0FBQyxTQUFTLENBQUMsQ0FBQztBQUNmLDBCQUFTO0FBRTNCOzs7O0dBSUc7QUFDSCxlQUFzQixVQUFrQjtJQUNwQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0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QU8sTUFBTSxDQUFDLEdBQUcsQ0FBQyxLQUFLLFVBQVUsRUFBRTtZQUNwRCxpREFBaUQ7WUFDakQsb0VBQW9FO1lBQ3BFLElBQUksT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssUUFBUSxFQUFFO2dCQUNqQyxxQkFBcUIsQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7YUFDbkQ7aUJBQU07Z0JBQ0gsSUFBSSxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO29CQUMzQixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO2lCQUM3QjthQUNKO1NBQ0o7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9
  103430. /***/ }),
  103431. /* 2 */
  103432. /***/ (function(module, exports, __webpack_require__) {
  103433. "use strict";
  103434. function __export(m) {
  103435. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  103436. }
  103437. Object.defineProperty(exports, "__esModule", { value: true });
  103438. __export(__webpack_require__(30));
  103439. __export(__webpack_require__(32));
  103440. __export(__webpack_require__(38));
  103441. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  103442. /***/ }),
  103443. /* 3 */
  103444. /***/ (function(module, exports, __webpack_require__) {
  103445. "use strict";
  103446. Object.defineProperty(exports, "__esModule", { value: true });
  103447. var babylonjs_1 = __webpack_require__(0);
  103448. var _1 = __webpack_require__(1);
  103449. /**
  103450. * This is a simple HTML mapper.
  103451. * This mapper parses a single HTML element and returns the configuration from its attributes.
  103452. * it parses numbers and boolean values to the corresponding variable types.
  103453. * The following HTML element:
  103454. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  103455. *
  103456. * {
  103457. * test: 1, //a number!
  103458. * randomFlag: boolean, //camelCase and boolean
  103459. * a: {
  103460. * string: {
  103461. * object: "test" //dot-separated object levels
  103462. * }
  103463. * }
  103464. * }
  103465. */
  103466. var HTMLMapper = /** @class */ (function () {
  103467. function HTMLMapper() {
  103468. }
  103469. /**
  103470. * Map a specific element and get configuration from it
  103471. * @param element the HTML element to analyze.
  103472. */
  103473. HTMLMapper.prototype.map = function (element) {
  103474. var config = {};
  103475. var _loop_1 = function (attrIdx) {
  103476. var attr = element.attributes.item(attrIdx);
  103477. if (!attr) {
  103478. return "continue";
  103479. }
  103480. // map "object.property" to the right configuration place.
  103481. var split = attr.nodeName.split('.');
  103482. split.reduce(function (currentConfig, key, idx) {
  103483. //convert html-style to json-style
  103484. var camelKey = _1.kebabToCamel(key);
  103485. if (idx === split.length - 1) {
  103486. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  103487. if (val === "true") {
  103488. val = true;
  103489. }
  103490. else if (val === "false") {
  103491. val = false;
  103492. }
  103493. else if (val === "undefined") {
  103494. val = undefined;
  103495. }
  103496. else if (val === "null") {
  103497. val = null;
  103498. }
  103499. else {
  103500. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  103501. if (isnum) {
  103502. var number = parseFloat(val);
  103503. if (!isNaN(number)) {
  103504. val = number;
  103505. }
  103506. }
  103507. }
  103508. currentConfig[camelKey] = val;
  103509. }
  103510. else {
  103511. currentConfig[camelKey] = currentConfig[camelKey] || {};
  103512. }
  103513. return currentConfig[camelKey];
  103514. }, config);
  103515. };
  103516. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  103517. _loop_1(attrIdx);
  103518. }
  103519. return config;
  103520. };
  103521. return HTMLMapper;
  103522. }());
  103523. /**
  103524. * A simple string-to-JSON mapper.
  103525. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  103526. */
  103527. var JSONMapper = /** @class */ (function () {
  103528. function JSONMapper() {
  103529. }
  103530. JSONMapper.prototype.map = function (rawSource) {
  103531. return JSON.parse(rawSource);
  103532. };
  103533. return JSONMapper;
  103534. }());
  103535. /**
  103536. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  103537. * DOM elements and attributes.
  103538. */
  103539. var DOMMapper = /** @class */ (function () {
  103540. function DOMMapper() {
  103541. }
  103542. /**
  103543. * The mapping function that will convert HTML data to a viewer configuration object
  103544. * @param baseElement the baseElement from which to start traversing
  103545. * @returns a ViewerCOnfiguration object from the provided HTML Element
  103546. */
  103547. DOMMapper.prototype.map = function (baseElement) {
  103548. var htmlMapper = new HTMLMapper();
  103549. var config = htmlMapper.map(baseElement);
  103550. var traverseChildren = function (element, partConfig) {
  103551. var children = element.children;
  103552. if (children.length) {
  103553. for (var i = 0; i < children.length; ++i) {
  103554. var item = children.item(i);
  103555. // use the HTML Mapper to read configuration from a single element
  103556. var configMapped = htmlMapper.map(item);
  103557. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  103558. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  103559. partConfig[key] = [];
  103560. }
  103561. else {
  103562. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  103563. partConfig.push(configMapped);
  103564. }
  103565. else if (partConfig[key]) {
  103566. //exists already! probably an array
  103567. element.setAttribute('array', 'true');
  103568. var oldItem = partConfig[key];
  103569. partConfig = [oldItem, configMapped];
  103570. }
  103571. else {
  103572. partConfig[key] = configMapped;
  103573. }
  103574. }
  103575. traverseChildren(item, partConfig[key] || configMapped);
  103576. }
  103577. }
  103578. return partConfig;
  103579. };
  103580. traverseChildren(baseElement, config);
  103581. return config;
  103582. };
  103583. return DOMMapper;
  103584. }());
  103585. /**
  103586. * The MapperManager manages the different implemented mappers.
  103587. * It allows the user to register new mappers as well and use them to parse their own configuration data
  103588. */
  103589. var MapperManager = /** @class */ (function () {
  103590. function MapperManager() {
  103591. this._mappers = {
  103592. "html": new HTMLMapper(),
  103593. "json": new JSONMapper(),
  103594. "dom": new DOMMapper()
  103595. };
  103596. }
  103597. /**
  103598. * Get a specific configuration mapper.
  103599. *
  103600. * @param type the name of the mapper to load
  103601. */
  103602. MapperManager.prototype.getMapper = function (type) {
  103603. if (!this._mappers[type]) {
  103604. babylonjs_1.Tools.Error("No mapper defined for " + type);
  103605. }
  103606. return this._mappers[type];
  103607. };
  103608. /**
  103609. * Use this functio to register your own configuration mapper.
  103610. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  103611. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  103612. * @param mapper The implemented mapper
  103613. */
  103614. MapperManager.prototype.registerMapper = function (type, mapper) {
  103615. this._mappers[type] = mapper;
  103616. };
  103617. /**
  103618. * Dispose the mapper manager and all of its mappers.
  103619. */
  103620. MapperManager.prototype.dispose = function () {
  103621. this._mappers = {};
  103622. };
  103623. /**
  103624. * The default mapper is the JSON mapper.
  103625. */
  103626. MapperManager.DefaultMapper = 'json';
  103627. return MapperManager;
  103628. }());
  103629. exports.MapperManager = MapperManager;
  103630. /**
  103631. * mapperManager is a singleton of the type MapperManager.
  103632. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  103633. * or indirectly with using BabylonViewer.disposeAll()
  103634. */
  103635. exports.mapperManager = new MapperManager();
  103636. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFwcGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL21hcHBlcnMudHMiXSwibmFtZXM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BTSxFQUFFLElBQUksVUFBVSxFQUFFO1lBQ3hCLEtBQUssRUFBRSxJQUFJLFNBQVMsRUFBRTtTQUN6QixDQUFBO0lBQ0wsQ0FBQztJQUVEOzs7O09BSUc7SUFDSSxpQ0FBUyxHQUFoQixVQUFpQixJQUFZO1FBQ3pCLElBQUksQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxFQUFFO1lBQ3RCLGlCQUFLLENBQUMsS0FBSyxDQUFDLHdCQUF3QixHQUFHLElBQUksQ0FBQyxDQUFDO1NBQ2hEO1FBQ0QsT0FBTyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQy9CLENBQUM7SUFFRDs7Ozs7T0FLRztJQUNJLHNDQUFjLEdBQXJCLFVBQXNCLElBQVksRUFBRSxNQUFlO1FBQy9DLElBQUksQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLEdBQUcsTUFBTSxDQUFDO0lBQ2pDLENBQUM7SUFFRDs7T0FFRztJQUNJLCtCQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsUUFBUSxHQUFHLEVBQUUsQ0FBQztJQUN2QixDQUFDO0lBeENEOztPQUVHO0lBQ1csMkJBQWEsR0FBRyxNQUFNLENBQUM7SUF1Q3pDLG9CQUFDO0NBQUEsQUE3Q0QsSUE2Q0M7QUE3Q1ksc0NBQWE7QUErQzFCOzs7O0dBSUc7QUFDUSxRQUFBLGFBQWEsR0FBRyxJQUFJLGFBQWEsRUFBRSxDQUFDIn0=
  103637. /***/ }),
  103638. /* 4 */
  103639. /***/ (function(module, exports, __webpack_require__) {
  103640. "use strict";
  103641. Object.defineProperty(exports, "__esModule", { value: true });
  103642. var babylonjs_1 = __webpack_require__(0);
  103643. var ViewerGlobals = /** @class */ (function () {
  103644. function ViewerGlobals() {
  103645. this.disableInit = false;
  103646. this.disableWebGL2Support = false;
  103647. }
  103648. Object.defineProperty(ViewerGlobals.prototype, "version", {
  103649. get: function () {
  103650. return babylonjs_1.Engine.Version;
  103651. },
  103652. enumerable: true,
  103653. configurable: true
  103654. });
  103655. return ViewerGlobals;
  103656. }());
  103657. exports.ViewerGlobals = ViewerGlobals;
  103658. exports.viewerGlobals = new ViewerGlobals();
  103659. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  103660. /***/ }),
  103661. /* 5 */
  103662. /***/ (function(module, exports, __webpack_require__) {
  103663. "use strict";
  103664. Object.defineProperty(exports, "__esModule", { value: true });
  103665. var babylonjs_1 = __webpack_require__(0);
  103666. var modelAnimation_1 = __webpack_require__(52);
  103667. var _1 = __webpack_require__(1);
  103668. /**
  103669. * The current state of the model
  103670. */
  103671. var ModelState;
  103672. (function (ModelState) {
  103673. ModelState[ModelState["INIT"] = 0] = "INIT";
  103674. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  103675. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  103676. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  103677. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  103678. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  103679. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  103680. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  103681. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  103682. /**
  103683. * The viewer model is a container for all assets representing a sngle loaded model.
  103684. */
  103685. var ViewerModel = /** @class */ (function () {
  103686. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  103687. var _this = this;
  103688. this._observablesManager = _observablesManager;
  103689. this._configurationContainer = _configurationContainer;
  103690. /**
  103691. * the list of meshes that are a part of this model
  103692. */
  103693. this._meshes = [];
  103694. /**
  103695. * ParticleSystems connected to this model
  103696. */
  103697. this.particleSystems = [];
  103698. /**
  103699. * Skeletons defined in this model
  103700. */
  103701. this.skeletons = [];
  103702. this._loaderDone = false;
  103703. this._animatables = [];
  103704. this._frameRate = 60;
  103705. this._shadowsRenderedAfterLoad = false;
  103706. this.onLoadedObservable = new babylonjs_1.Observable();
  103707. this.onLoadErrorObservable = new babylonjs_1.Observable();
  103708. this.onLoadProgressObservable = new babylonjs_1.Observable();
  103709. this.onCompleteObservable = new babylonjs_1.Observable();
  103710. this.onAfterConfigure = new babylonjs_1.Observable();
  103711. this.state = ModelState.INIT;
  103712. var scene = this._configurationContainer && this._configurationContainer.scene;
  103713. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", scene);
  103714. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", scene);
  103715. this._pivotMesh.parent = this.rootMesh;
  103716. // rotate 180, gltf fun
  103717. this._pivotMesh.rotation.y += Math.PI;
  103718. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103719. this._animations = [];
  103720. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  103721. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  103722. if (this._observablesManager) {
  103723. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  103724. }
  103725. if (this._modelConfiguration.entryAnimation) {
  103726. this.rootMesh.setEnabled(false);
  103727. }
  103728. this.onLoadedObservable.add(function () {
  103729. _this.updateConfiguration(_this._modelConfiguration);
  103730. if (_this._observablesManager) {
  103731. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  103732. }
  103733. _this._initAnimations();
  103734. });
  103735. this.onCompleteObservable.add(function () {
  103736. _this.state = ModelState.COMPLETE;
  103737. });
  103738. }
  103739. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  103740. get: function () {
  103741. return this._shadowsRenderedAfterLoad;
  103742. },
  103743. set: function (rendered) {
  103744. if (!rendered) {
  103745. throw new Error("can only be enabled");
  103746. }
  103747. else {
  103748. this._shadowsRenderedAfterLoad = rendered;
  103749. }
  103750. },
  103751. enumerable: true,
  103752. configurable: true
  103753. });
  103754. ViewerModel.prototype.getViewerId = function () {
  103755. return this._configurationContainer && this._configurationContainer.viewerId;
  103756. };
  103757. Object.defineProperty(ViewerModel.prototype, "enabled", {
  103758. /**
  103759. * Is this model enabled?
  103760. */
  103761. get: function () {
  103762. return this.rootMesh.isEnabled();
  103763. },
  103764. /**
  103765. * Set whether this model is enabled or not.
  103766. */
  103767. set: function (enable) {
  103768. this.rootMesh.setEnabled(enable);
  103769. },
  103770. enumerable: true,
  103771. configurable: true
  103772. });
  103773. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  103774. set: function (done) {
  103775. this._loaderDone = done;
  103776. this._checkCompleteState();
  103777. },
  103778. enumerable: true,
  103779. configurable: true
  103780. });
  103781. ViewerModel.prototype._checkCompleteState = function () {
  103782. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  103783. this._modelComplete();
  103784. }
  103785. };
  103786. /**
  103787. * Add a mesh to this model.
  103788. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  103789. *
  103790. * @param mesh the new mesh to add
  103791. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  103792. */
  103793. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  103794. if (!mesh.parent) {
  103795. mesh.parent = this._pivotMesh;
  103796. }
  103797. mesh.receiveShadows = !!this.configuration.receiveShadows;
  103798. this._meshes.push(mesh);
  103799. if (triggerLoaded) {
  103800. return this.onLoadedObservable.notifyObserversWithPromise(this);
  103801. }
  103802. };
  103803. Object.defineProperty(ViewerModel.prototype, "meshes", {
  103804. /**
  103805. * get the list of meshes (excluding the root mesh)
  103806. */
  103807. get: function () {
  103808. return this._meshes;
  103809. },
  103810. enumerable: true,
  103811. configurable: true
  103812. });
  103813. Object.defineProperty(ViewerModel.prototype, "configuration", {
  103814. /**
  103815. * Get the model's configuration
  103816. */
  103817. get: function () {
  103818. return this._modelConfiguration;
  103819. },
  103820. /**
  103821. * (Re-)set the model's entire configuration
  103822. * @param newConfiguration the new configuration to replace the new one
  103823. */
  103824. set: function (newConfiguration) {
  103825. this._modelConfiguration = newConfiguration;
  103826. this._configureModel();
  103827. },
  103828. enumerable: true,
  103829. configurable: true
  103830. });
  103831. /**
  103832. * Update the current configuration with new values.
  103833. * Configuration will not be overwritten, but merged with the new configuration.
  103834. * Priority is to the new configuration
  103835. * @param newConfiguration the configuration to be merged into the current configuration;
  103836. */
  103837. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  103838. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  103839. this._configureModel();
  103840. };
  103841. ViewerModel.prototype._initAnimations = function () {
  103842. var _this = this;
  103843. // check if this is not a gltf loader and init the animations
  103844. if (this.skeletons.length) {
  103845. this.skeletons.forEach(function (skeleton, idx) {
  103846. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._configurationContainer && _this._configurationContainer.scene);
  103847. var add = false;
  103848. skeleton.getAnimatables().forEach(function (a) {
  103849. if (a.animations[0]) {
  103850. ag.addTargetedAnimation(a.animations[0], a);
  103851. add = true;
  103852. }
  103853. });
  103854. if (add) {
  103855. _this.addAnimationGroup(ag);
  103856. }
  103857. });
  103858. }
  103859. var completeCallback = function () {
  103860. };
  103861. if (this._modelConfiguration.animation) {
  103862. if (this._modelConfiguration.animation.playOnce) {
  103863. this._animations.forEach(function (a) {
  103864. a.playMode = 0 /* ONCE */;
  103865. });
  103866. }
  103867. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  103868. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  103869. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  103870. completeCallback = function () {
  103871. _this.playAnimation(animationName_1);
  103872. };
  103873. }
  103874. }
  103875. this._enterScene(completeCallback);
  103876. };
  103877. /**
  103878. * Animates the model from the current position to the default position
  103879. * @param completeCallback A function to call when the animation has completed
  103880. */
  103881. ViewerModel.prototype._enterScene = function (completeCallback) {
  103882. var _this = this;
  103883. var scene = this.rootMesh.getScene();
  103884. var previousValue = scene.animationPropertiesOverride.enableBlending;
  103885. var callback = function () {
  103886. _this.state = ModelState.ENTRYDONE;
  103887. scene.animationPropertiesOverride.enableBlending = previousValue;
  103888. _this._checkCompleteState();
  103889. if (completeCallback)
  103890. completeCallback();
  103891. };
  103892. if (!this._entryAnimation) {
  103893. callback();
  103894. return;
  103895. }
  103896. this.rootMesh.setEnabled(true);
  103897. // disable blending for the sake of the entry animation;
  103898. scene.animationPropertiesOverride.enableBlending = false;
  103899. this._applyAnimation(this._entryAnimation, true, callback);
  103900. };
  103901. /**
  103902. * Animates the model from the current position to the exit-screen position
  103903. * @param completeCallback A function to call when the animation has completed
  103904. */
  103905. ViewerModel.prototype._exitScene = function (completeCallback) {
  103906. if (!this._exitAnimation) {
  103907. completeCallback();
  103908. return;
  103909. }
  103910. this._applyAnimation(this._exitAnimation, false, completeCallback);
  103911. };
  103912. ViewerModel.prototype._modelComplete = function () {
  103913. var _this = this;
  103914. //reapply material defines to be sure:
  103915. var meshes = this._pivotMesh.getChildMeshes(false);
  103916. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  103917. _this._applyModelMaterialConfiguration(mesh.material);
  103918. });
  103919. this.state = ModelState.COMPLETE;
  103920. this.onCompleteObservable.notifyObservers(this);
  103921. };
  103922. /**
  103923. * Add a new animation group to this model.
  103924. * @param animationGroup the new animation group to be added
  103925. */
  103926. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  103927. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  103928. };
  103929. /**
  103930. * Get the ModelAnimation array
  103931. */
  103932. ViewerModel.prototype.getAnimations = function () {
  103933. return this._animations;
  103934. };
  103935. /**
  103936. * Get the animations' names. Using the names you can play a specific animation.
  103937. */
  103938. ViewerModel.prototype.getAnimationNames = function () {
  103939. return this._animations.map(function (a) { return a.name; });
  103940. };
  103941. /**
  103942. * Get an animation by the provided name. Used mainly when playing n animation.
  103943. * @param name the name of the animation to find
  103944. */
  103945. ViewerModel.prototype._getAnimationByName = function (name) {
  103946. // can't use .find, noe available on IE
  103947. var filtered = this._animations.filter(function (a) { return a.name === name; });
  103948. // what the next line means - if two animations have the same name, they will not be returned!
  103949. if (filtered.length === 1) {
  103950. return filtered[0];
  103951. }
  103952. else {
  103953. return null;
  103954. }
  103955. };
  103956. /**
  103957. * Choose an initialized animation using its name and start playing it
  103958. * @param name the name of the animation to play
  103959. * @returns The model aniamtion to be played.
  103960. */
  103961. ViewerModel.prototype.playAnimation = function (name) {
  103962. var animation = this.setCurrentAnimationByName(name);
  103963. if (animation) {
  103964. animation.start();
  103965. }
  103966. return animation;
  103967. };
  103968. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  103969. var animation = this._getAnimationByName(name);
  103970. if (animation) {
  103971. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  103972. this.currentAnimation.stop();
  103973. }
  103974. this.currentAnimation = animation;
  103975. return animation;
  103976. }
  103977. else {
  103978. throw new Error("animation not found - " + name);
  103979. }
  103980. };
  103981. ViewerModel.prototype._configureModel = function () {
  103982. var _this = this;
  103983. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  103984. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  103985. var updateMeshesWithNoParent = function (variable, value, param) {
  103986. meshesWithNoParent.forEach(function (mesh) {
  103987. if (param) {
  103988. mesh[variable][param] = value;
  103989. }
  103990. else {
  103991. mesh[variable] = value;
  103992. }
  103993. });
  103994. };
  103995. var updateXYZ = function (variable, configValues) {
  103996. if (configValues.x !== undefined) {
  103997. updateMeshesWithNoParent(variable, configValues.x, 'x');
  103998. }
  103999. if (configValues.y !== undefined) {
  104000. updateMeshesWithNoParent(variable, configValues.y, 'y');
  104001. }
  104002. if (configValues.z !== undefined) {
  104003. updateMeshesWithNoParent(variable, configValues.z, 'z');
  104004. }
  104005. if (configValues.w !== undefined) {
  104006. updateMeshesWithNoParent(variable, configValues.w, 'w');
  104007. }
  104008. };
  104009. if (this._modelConfiguration.normalize) {
  104010. var center = false;
  104011. var unitSize = false;
  104012. var parentIndex = void 0;
  104013. if (this._modelConfiguration.normalize === true) {
  104014. center = true;
  104015. unitSize = true;
  104016. }
  104017. else {
  104018. center = !!this._modelConfiguration.normalize.center;
  104019. unitSize = !!this._modelConfiguration.normalize.unitSize;
  104020. parentIndex = this._modelConfiguration.normalize.parentIndex;
  104021. }
  104022. var meshesToNormalize = [];
  104023. if (parentIndex !== undefined) {
  104024. meshesToNormalize.push(this._meshes[parentIndex]);
  104025. }
  104026. else {
  104027. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  104028. }
  104029. if (unitSize) {
  104030. meshesToNormalize.forEach(function (mesh) {
  104031. mesh.normalizeToUnitCube(true);
  104032. mesh.computeWorldMatrix(true);
  104033. });
  104034. }
  104035. if (center) {
  104036. meshesToNormalize.forEach(function (mesh) {
  104037. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  104038. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  104039. var halfSizeVec = sizeVec.scale(0.5);
  104040. var center = boundingInfo.min.add(halfSizeVec);
  104041. mesh.position = center.scale(-1);
  104042. mesh.position.y += halfSizeVec.y;
  104043. // Recompute Info.
  104044. mesh.computeWorldMatrix(true);
  104045. });
  104046. }
  104047. }
  104048. else {
  104049. // if centered, should be done here
  104050. }
  104051. // position?
  104052. if (this._modelConfiguration.position) {
  104053. updateXYZ('position', this._modelConfiguration.position);
  104054. }
  104055. if (this._modelConfiguration.rotation) {
  104056. //quaternion?
  104057. if (this._modelConfiguration.rotation.w) {
  104058. meshesWithNoParent.forEach(function (mesh) {
  104059. if (!mesh.rotationQuaternion) {
  104060. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  104061. }
  104062. });
  104063. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  104064. }
  104065. else {
  104066. updateXYZ('rotation', this._modelConfiguration.rotation);
  104067. }
  104068. }
  104069. if (this._modelConfiguration.rotationOffsetAxis) {
  104070. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  104071. meshesWithNoParent.forEach(function (m) {
  104072. if (_this._modelConfiguration.rotationOffsetAngle) {
  104073. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  104074. }
  104075. });
  104076. }
  104077. if (this._modelConfiguration.scaling) {
  104078. updateXYZ('scaling', this._modelConfiguration.scaling);
  104079. }
  104080. if (this._modelConfiguration.castShadow) {
  104081. this._meshes.forEach(function (mesh) {
  104082. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  104083. });
  104084. }
  104085. var meshes = this._pivotMesh.getChildMeshes(false);
  104086. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  104087. _this._applyModelMaterialConfiguration(mesh.material);
  104088. });
  104089. if (this._modelConfiguration.entryAnimation) {
  104090. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  104091. }
  104092. if (this._modelConfiguration.exitAnimation) {
  104093. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  104094. }
  104095. this.onAfterConfigure.notifyObservers(this);
  104096. };
  104097. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  104098. var anim = {
  104099. time: 0.5
  104100. };
  104101. if (animConfig.scaling) {
  104102. anim.scaling = babylonjs_1.Vector3.Zero();
  104103. }
  104104. if (animConfig.easingFunction !== undefined) {
  104105. anim.easingFunction = animConfig.easingFunction;
  104106. }
  104107. if (animConfig.easingMode !== undefined) {
  104108. anim.easingMode = animConfig.easingMode;
  104109. }
  104110. _1.extendClassWithConfig(anim, animConfig);
  104111. return anim;
  104112. };
  104113. /**
  104114. * Apply a material configuration to a material
  104115. * @param material Material to apply configuration to
  104116. */
  104117. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  104118. if (!this._modelConfiguration.material)
  104119. return;
  104120. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  104121. if (material instanceof babylonjs_1.PBRMaterial) {
  104122. if (this._modelConfiguration.material.directIntensity !== undefined) {
  104123. material.directIntensity = this._modelConfiguration.material.directIntensity;
  104124. }
  104125. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  104126. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  104127. }
  104128. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  104129. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  104130. }
  104131. if (this._modelConfiguration.material.directEnabled !== undefined) {
  104132. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  104133. }
  104134. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  104135. material.reflectionColor = this._configurationContainer.reflectionColor;
  104136. }
  104137. }
  104138. else if (material instanceof babylonjs_1.MultiMaterial) {
  104139. for (var i = 0; i < material.subMaterials.length; i++) {
  104140. var subMaterial = material.subMaterials[i];
  104141. if (subMaterial) {
  104142. this._applyModelMaterialConfiguration(subMaterial);
  104143. }
  104144. }
  104145. }
  104146. };
  104147. /**
  104148. * Start entry/exit animation given an animation configuration
  104149. * @param animationConfiguration Entry/Exit animation configuration
  104150. * @param isEntry Pass true if the animation is an entry animation
  104151. * @param completeCallback Callback to execute when the animation completes
  104152. */
  104153. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  104154. var animations = [];
  104155. //scale
  104156. if (animationConfiguration.scaling) {
  104157. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  104158. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  104159. if (!scaleStart.equals(scaleEnd)) {
  104160. this.rootMesh.scaling = scaleStart;
  104161. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  104162. animations.push(this._scaleTransition);
  104163. }
  104164. }
  104165. //Start the animation(s)
  104166. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  104167. completeCallback(); });
  104168. };
  104169. /**
  104170. * Begin @animations with the specified @easingFunction
  104171. * @param animations The BABYLON Animations to begin
  104172. * @param duration of transition, in seconds
  104173. * @param easingFunction An easing function to apply
  104174. * @param easingMode A easing mode to apply to the easingFunction
  104175. * @param onAnimationEnd Call back trigger at the end of the animation.
  104176. */
  104177. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  104178. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  104179. if (easingFunction) {
  104180. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  104181. var animation = animations_1[_i];
  104182. easingFunction.setEasingMode(easingMode);
  104183. animation.setEasingFunction(easingFunction);
  104184. }
  104185. }
  104186. //Stop any current animations before starting the new one - merging not yet supported.
  104187. this.stopAllAnimations();
  104188. this.rootMesh.animations = animations;
  104189. if (this.rootMesh.getScene().beginAnimation) {
  104190. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  104191. if (onAnimationEnd) {
  104192. onAnimationEnd();
  104193. }
  104194. });
  104195. this._animatables.push(animatable);
  104196. }
  104197. };
  104198. /**
  104199. * Sets key values on an Animation from first to last frame.
  104200. * @param animation The Babylon animation object to set keys on
  104201. * @param startValue The value of the first key
  104202. * @param endValue The value of the last key
  104203. * @param duration The duration of the animation, used to determine the end frame
  104204. */
  104205. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  104206. animation.setKeys([
  104207. {
  104208. frame: 0,
  104209. value: startValue
  104210. },
  104211. {
  104212. frame: this._frameRate * duration,
  104213. value: endValue
  104214. }
  104215. ]);
  104216. };
  104217. /**
  104218. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  104219. * @param easingFunctionID The enum of the easing funtion to create
  104220. * @return The newly created Babylon easing function object
  104221. */
  104222. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  104223. var easingFunction;
  104224. switch (easingFunctionID) {
  104225. case 1 /* CircleEase */:
  104226. easingFunction = new babylonjs_1.CircleEase();
  104227. break;
  104228. case 2 /* BackEase */:
  104229. easingFunction = new babylonjs_1.BackEase(0.3);
  104230. break;
  104231. case 3 /* BounceEase */:
  104232. easingFunction = new babylonjs_1.BounceEase();
  104233. break;
  104234. case 4 /* CubicEase */:
  104235. easingFunction = new babylonjs_1.CubicEase();
  104236. break;
  104237. case 5 /* ElasticEase */:
  104238. easingFunction = new babylonjs_1.ElasticEase();
  104239. break;
  104240. case 6 /* ExponentialEase */:
  104241. easingFunction = new babylonjs_1.ExponentialEase();
  104242. break;
  104243. case 7 /* PowerEase */:
  104244. easingFunction = new babylonjs_1.PowerEase();
  104245. break;
  104246. case 8 /* QuadraticEase */:
  104247. easingFunction = new babylonjs_1.QuadraticEase();
  104248. break;
  104249. case 9 /* QuarticEase */:
  104250. easingFunction = new babylonjs_1.QuarticEase();
  104251. break;
  104252. case 10 /* QuinticEase */:
  104253. easingFunction = new babylonjs_1.QuinticEase();
  104254. break;
  104255. case 11 /* SineEase */:
  104256. easingFunction = new babylonjs_1.SineEase();
  104257. break;
  104258. default:
  104259. babylonjs_1.Tools.Log("No ease function found");
  104260. break;
  104261. }
  104262. return easingFunction;
  104263. };
  104264. /**
  104265. * Stops and removes all animations that have been applied to the model
  104266. */
  104267. ViewerModel.prototype.stopAllAnimations = function () {
  104268. if (this.rootMesh) {
  104269. this.rootMesh.animations = [];
  104270. }
  104271. if (this.currentAnimation) {
  104272. this.currentAnimation.stop();
  104273. }
  104274. while (this._animatables.length) {
  104275. this._animatables[0].onAnimationEnd = null;
  104276. this._animatables[0].stop();
  104277. this._animatables.shift();
  104278. }
  104279. };
  104280. /**
  104281. * Will remove this model from the viewer (but NOT dispose it).
  104282. */
  104283. ViewerModel.prototype.remove = function () {
  104284. this.stopAllAnimations();
  104285. // hide it
  104286. this.rootMesh.isVisible = false;
  104287. if (this._observablesManager) {
  104288. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  104289. }
  104290. };
  104291. /**
  104292. * Dispose this model, including all of its associated assets.
  104293. */
  104294. ViewerModel.prototype.dispose = function () {
  104295. this.remove();
  104296. this.onAfterConfigure.clear();
  104297. this.onLoadedObservable.clear();
  104298. this.onLoadErrorObservable.clear();
  104299. this.onLoadProgressObservable.clear();
  104300. if (this.loader && this.loader.name === "gltf") {
  104301. this.loader.dispose();
  104302. }
  104303. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  104304. this.particleSystems.length = 0;
  104305. this.skeletons.forEach(function (s) { return s.dispose(); });
  104306. this.skeletons.length = 0;
  104307. this._animations.forEach(function (ag) { return ag.dispose(); });
  104308. this._animations.length = 0;
  104309. this.rootMesh.dispose(false, true);
  104310. };
  104311. return ViewerModel;
  104312. }());
  104313. exports.ViewerModel = ViewerModel;
  104314. //# sourceMappingURL=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LEVBQUUsQ0FBQyxPQUFPLEVBQUUsRUFBWixDQUFZLENBQUMsQ0FBQztRQUM3QyxJQUFJLENBQUMsV0FBVyxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUM7UUFDNUIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFsdUJELElBa3VCQztBQWx1Qlksa0NBQVcifQ==
  104315. /***/ }),
  104316. /* 6 */
  104317. /***/ (function(module, exports, __webpack_require__) {
  104318. "use strict";
  104319. Object.defineProperty(exports, "__esModule", { value: true });
  104320. var babylonjs_1 = __webpack_require__(0);
  104321. /**
  104322. * Receives Telemetry events and raises events to the API
  104323. */
  104324. var TelemetryManager = /** @class */ (function () {
  104325. function TelemetryManager() {
  104326. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  104327. this._event = this._eventEnabled;
  104328. }
  104329. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  104330. /**
  104331. * Receives a telemetry event
  104332. * @param event The name of the Telemetry event
  104333. * @param details An additional value, or an object containing a list of property/value pairs
  104334. */
  104335. get: function () {
  104336. return this._event;
  104337. },
  104338. enumerable: true,
  104339. configurable: true
  104340. });
  104341. /**
  104342. * Log a Telemetry event for errors raised on the WebGL context.
  104343. * @param engine The Babylon engine with the WebGL context.
  104344. */
  104345. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  104346. if (!engine) {
  104347. return;
  104348. }
  104349. var logErrors = true;
  104350. while (logErrors) {
  104351. var error = engine.getError();
  104352. if (error === 0) {
  104353. logErrors = false;
  104354. }
  104355. else {
  104356. this.broadcast("WebGL Error", viewerId, { error: error });
  104357. }
  104358. }
  104359. };
  104360. Object.defineProperty(TelemetryManager.prototype, "enable", {
  104361. /**
  104362. * Enable or disable telemetry events
  104363. * @param enabled Boolan, true if events are enabled
  104364. */
  104365. set: function (enabled) {
  104366. if (enabled) {
  104367. this._event = this._eventEnabled;
  104368. }
  104369. else {
  104370. this._event = this._eventDisabled;
  104371. }
  104372. },
  104373. enumerable: true,
  104374. configurable: true
  104375. });
  104376. /**
  104377. * Called on event when disabled, typically do nothing here
  104378. */
  104379. TelemetryManager.prototype._eventDisabled = function () {
  104380. // nothing to do
  104381. };
  104382. /**
  104383. * Called on event when enabled
  104384. * @param event - The name of the Telemetry event
  104385. * @param details An additional value, or an object containing a list of property/value pairs
  104386. */
  104387. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  104388. var telemetryData = {
  104389. viewerId: viewerId,
  104390. event: event,
  104391. session: this.session,
  104392. date: new Date(),
  104393. now: window.performance ? window.performance.now() : Date.now(),
  104394. detail: null
  104395. };
  104396. if (typeof details === "object") {
  104397. for (var attr in details) {
  104398. if (details.hasOwnProperty(attr)) {
  104399. telemetryData[attr] = details[attr];
  104400. }
  104401. }
  104402. }
  104403. else if (details) {
  104404. telemetryData.detail = details;
  104405. }
  104406. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  104407. };
  104408. Object.defineProperty(TelemetryManager.prototype, "session", {
  104409. /**
  104410. * Returns the current session ID or creates one if it doesn't exixt
  104411. * @return The current session ID
  104412. */
  104413. get: function () {
  104414. if (!this._currentSessionId) {
  104415. //String + Timestamp + Random Integer
  104416. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  104417. }
  104418. return this._currentSessionId;
  104419. },
  104420. enumerable: true,
  104421. configurable: true
  104422. });
  104423. /**
  104424. * Disposes the telemetry manager
  104425. */
  104426. TelemetryManager.prototype.dispose = function () {
  104427. this.onEventBroadcastedObservable.clear();
  104428. delete this.onEventBroadcastedObservable;
  104429. };
  104430. return TelemetryManager;
  104431. }());
  104432. exports.TelemetryManager = TelemetryManager;
  104433. exports.telemetryManager = new TelemetryManager();
  104434. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1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QztJQU1ELHNCQUFXLHFDQUFPO1FBSmxCOzs7V0FHRzthQUNIO1lBQ0ksSUFBSSxDQUFDLElBQUksQ0FBQyxpQkFBaUIsRUFBRTtnQkFDekIscUNBQXFDO2dCQUNyQyxJQUFJLENBQUMsaUJBQWlCLEdBQUcsVUFBVSxHQUFHLElBQUksQ0FBQyxHQUFHLEVBQUUsR0FBRyxJQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxNQUFNLEVBQUUsR0FBRyxPQUFPLENBQUMsQ0FBQzthQUMxRjtZQUNELE9BQU8sSUFBSSxDQUFDLGlCQUFpQixDQUFDO1FBQ2xDLENBQUM7OztPQUFBO0lBRUQ7O09BRUc7SUFDSSxrQ0FBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLDRCQUE0QixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQzFDLE9BQU8sSUFBSSxDQUFDLDRCQUE0QixDQUFDO0lBQzdDLENBQUM7SUFDTCx1QkFBQztBQUFELENBQUMsQUF2R0QsSUF1R0M7QUF2R1ksNENBQWdCO0FBeUdoQixRQUFBLGdCQUFnQixHQUFHLElBQUksZ0JBQWdCLEVBQUUsQ0FBQyJ9
  104435. /***/ }),
  104436. /* 7 */
  104437. /***/ (function(module, exports, __webpack_require__) {
  104438. "use strict";
  104439. Object.defineProperty(exports, "__esModule", { value: true });
  104440. var babylonjs_1 = __webpack_require__(0);
  104441. /**
  104442. * The viewer manager is the container for all viewers currently registered on this page.
  104443. * It is possible to have more than one viewer on a single page.
  104444. */
  104445. var ViewerManager = /** @class */ (function () {
  104446. function ViewerManager() {
  104447. this._viewers = {};
  104448. this.onViewerAddedObservable = new babylonjs_1.Observable();
  104449. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  104450. }
  104451. /**
  104452. * Adding a new viewer to the viewer manager and start tracking it.
  104453. * @param viewer the viewer to add
  104454. */
  104455. ViewerManager.prototype.addViewer = function (viewer) {
  104456. this._viewers[viewer.getBaseId()] = viewer;
  104457. this._onViewerAdded(viewer);
  104458. };
  104459. /**
  104460. * remove a viewer from the viewer manager
  104461. * @param viewer the viewer to remove
  104462. */
  104463. ViewerManager.prototype.removeViewer = function (viewer) {
  104464. var id = viewer.getBaseId();
  104465. delete this._viewers[id];
  104466. this.onViewerRemovedObservable.notifyObservers(id);
  104467. };
  104468. /**
  104469. * 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)
  104470. * @param id the id of the HTMl element (or the viewer's, if none provided)
  104471. */
  104472. ViewerManager.prototype.getViewerById = function (id) {
  104473. return this._viewers[id];
  104474. };
  104475. /**
  104476. * Get a viewer using a container element
  104477. * @param element the HTML element to search viewers associated with
  104478. */
  104479. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  104480. for (var id in this._viewers) {
  104481. if (this._viewers[id].containerElement === element) {
  104482. return this.getViewerById(id);
  104483. }
  104484. }
  104485. };
  104486. /**
  104487. * Get a promise that will fullfil when this viewer was initialized.
  104488. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  104489. * you will get the viewer after everything was already configured.
  104490. * @param id the viewer id to find
  104491. */
  104492. ViewerManager.prototype.getViewerPromiseById = function (id) {
  104493. var _this = this;
  104494. return new Promise(function (resolve, reject) {
  104495. var localViewer = _this.getViewerById(id);
  104496. if (localViewer) {
  104497. return resolve(localViewer);
  104498. }
  104499. var viewerFunction = function (viewer) {
  104500. if (viewer.getBaseId() === id) {
  104501. resolve(viewer);
  104502. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  104503. }
  104504. };
  104505. _this.onViewerAddedObservable.add(viewerFunction);
  104506. });
  104507. };
  104508. ViewerManager.prototype._onViewerAdded = function (viewer) {
  104509. this.onViewerAdded && this.onViewerAdded(viewer);
  104510. this.onViewerAddedObservable.notifyObservers(viewer);
  104511. };
  104512. /**
  104513. * dispose the manager and all of its associated viewers
  104514. */
  104515. ViewerManager.prototype.dispose = function () {
  104516. delete this._onViewerAdded;
  104517. for (var id in this._viewers) {
  104518. this._viewers[id].dispose();
  104519. }
  104520. this.onViewerAddedObservable.clear();
  104521. this.onViewerRemovedObservable.clear();
  104522. };
  104523. return ViewerManager;
  104524. }());
  104525. exports.ViewerManager = ViewerManager;
  104526. exports.viewerManager = new ViewerManager();
  104527. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUcsRUFBRSxDQUFDO1FBQ25CLElBQUksQ0FBQyx1QkFBdUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNoRCxJQUFJLENBQUMseUJBQXlCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7SUFDdEQsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGlDQUFTLEdBQWhCLFVBQWlCLE1BQXNCO1FBQ25DLElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLFNBQVMsRUFBRSxDQUFDLEdBQUcsTUFBTSxDQUFDO1FBQzNDLElBQUksQ0FBQyxjQUFjLENBQUMsTUFBTSxDQUFDLENBQUM7SUFDaEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLG9DQUFZLEdBQW5CLFVBQW9CLE1BQXNCO1FBQ3RDLElBQUksRUFBRSxHQUFHLE1BQU0sQ0FBQyxTQUFTLEVBQUUsQ0FBQztRQUM1QixPQUFPLElBQUksQ0FBQyxRQUFRLENBQUMsRUFBRSxDQUFDLENBQUM7UUFDekIsSUFBSSxDQUFDLHlCQUF5QixDQUFDLGVBQWUsQ0FBQyxFQUFFLENBQUMsQ0FBQztJQUN2RCxDQUFDO0lBRU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RCxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFFTyxzQ0FBYyxHQUF0QixVQUF1QixNQUFzQjtRQUN6QyxJQUFJLENBQUMsYUFBYSxJQUFJLElBQUksQ0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLENBQUM7UUFDakQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLGVBQWUsQ0FBQyxNQUFNLENBQUMsQ0FBQztJQUN6RCxDQUFDO0lBRUQ7O09BRUc7SUFDSSwrQkFBTyxHQUFkO1FBQ0ksT0FBTyxJQUFJLENBQUMsY0FBYyxDQUFDO1FBRTNCLEtBQUssSUFBSSxFQUFFLElBQUksSUFBSSxDQUFDLFFBQVEsRUFBRTtZQUMxQixJQUFJLENBQUMsUUFBUSxDQUFDLEVBQUUsQ0FBQyxDQUFDLE9BQU8sRUFBRSxDQUFDO1NBQy9CO1FBRUQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3JDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBdEdELElBc0dDO0FBdEdZLHNDQUFhO0FBd0dmLFFBQUEsYUFBYSxHQUFHLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  104528. /***/ }),
  104529. /* 8 */
  104530. /***/ (function(module, exports, __webpack_require__) {
  104531. "use strict";
  104532. var __extends = (this && this.__extends) || (function () {
  104533. var extendStatics = Object.setPrototypeOf ||
  104534. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  104535. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  104536. return function (d, b) {
  104537. extendStatics(d, b);
  104538. function __() { this.constructor = d; }
  104539. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  104540. };
  104541. })();
  104542. Object.defineProperty(exports, "__esModule", { value: true });
  104543. var viewer_1 = __webpack_require__(9);
  104544. var babylonjs_1 = __webpack_require__(0);
  104545. var hdButtonPlugin_1 = __webpack_require__(65);
  104546. /**
  104547. * The Default viewer is the default implementation of the AbstractViewer.
  104548. * It uses the templating system to render a new canvas and controls.
  104549. */
  104550. var DefaultViewer = /** @class */ (function (_super) {
  104551. __extends(DefaultViewer, _super);
  104552. /**
  104553. * Create a new default viewer
  104554. * @param containerElement the element in which the templates will be rendered
  104555. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  104556. */
  104557. function DefaultViewer(containerElement, initialConfiguration) {
  104558. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  104559. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  104560. _this.containerElement = containerElement;
  104561. _this._registeredPlugins = [];
  104562. _this._handlePointerDown = function (event) {
  104563. var pointerDown = event.event;
  104564. if (pointerDown.button !== 0)
  104565. return;
  104566. var element = event.event.target;
  104567. if (!element) {
  104568. return;
  104569. }
  104570. var parentClasses = element.parentElement.classList;
  104571. var elementClasses = element.classList;
  104572. var elementName = "";
  104573. for (var i = 0; i < elementClasses.length; ++i) {
  104574. var className = elementClasses[i];
  104575. if (className.indexOf("-button") !== -1 || className.indexOf("-wrapper") !== -1) {
  104576. elementName = className;
  104577. break;
  104578. }
  104579. }
  104580. switch (elementName) {
  104581. case "speed-button":
  104582. case "types-button":
  104583. if (parentClasses.contains("open")) {
  104584. parentClasses.remove("open");
  104585. }
  104586. else {
  104587. parentClasses.add("open");
  104588. }
  104589. break;
  104590. case "play-pause-button":
  104591. _this._togglePlayPause();
  104592. break;
  104593. case "label-option-button":
  104594. var value = element.dataset["value"];
  104595. var label = element.querySelector("span.animation-label");
  104596. if (label && value) {
  104597. _this._updateAnimationType({ value: value, label: label.innerHTML });
  104598. }
  104599. break;
  104600. case "speed-option-button":
  104601. if (!_this._currentAnimation) {
  104602. return;
  104603. }
  104604. var speed = element.dataset["value"];
  104605. if (speed)
  104606. _this._updateAnimationSpeed(speed);
  104607. break;
  104608. case "progress-wrapper":
  104609. _this._resumePlay = !_this._isAnimationPaused;
  104610. if (_this._resumePlay) {
  104611. _this._togglePlayPause(true);
  104612. }
  104613. break;
  104614. case "fullscreen-button":
  104615. _this.toggleFullscreen();
  104616. break;
  104617. case "vr-button":
  104618. _this.toggleVR();
  104619. break;
  104620. default:
  104621. return;
  104622. }
  104623. };
  104624. /**
  104625. * Plays or Pauses animation
  104626. */
  104627. _this._togglePlayPause = function (noUiUpdate) {
  104628. if (!_this._currentAnimation) {
  104629. return;
  104630. }
  104631. if (_this._isAnimationPaused) {
  104632. _this._currentAnimation.restart();
  104633. }
  104634. else {
  104635. _this._currentAnimation.pause();
  104636. }
  104637. _this._isAnimationPaused = !_this._isAnimationPaused;
  104638. if (noUiUpdate)
  104639. return;
  104640. var navbar = _this.templateManager.getTemplate('navBar');
  104641. if (!navbar)
  104642. return;
  104643. navbar.updateParams({
  104644. paused: _this._isAnimationPaused,
  104645. });
  104646. };
  104647. /**
  104648. * Control progress bar position based on animation current frame
  104649. */
  104650. _this._updateProgressBar = function () {
  104651. var navbar = _this.templateManager.getTemplate('navBar');
  104652. if (!navbar)
  104653. return;
  104654. var progressSlider = navbar.parent.querySelector("input.progress-wrapper");
  104655. if (progressSlider && _this._currentAnimation) {
  104656. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  104657. var currentValue = progressSlider.valueAsNumber;
  104658. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  104659. progressSlider.value = '' + progress;
  104660. }
  104661. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  104662. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  104663. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  104664. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  104665. }
  104666. }
  104667. else {
  104668. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  104669. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  104670. _this._oldIdleRotationValue = 0;
  104671. }
  104672. }
  104673. }
  104674. };
  104675. /**
  104676. * Update Current Animation Speed
  104677. */
  104678. _this._updateAnimationSpeed = function (speed, paramsObject) {
  104679. var navbar = _this.templateManager.getTemplate('navBar');
  104680. if (!navbar)
  104681. return;
  104682. if (speed && _this._currentAnimation) {
  104683. _this._currentAnimation.speedRatio = parseFloat(speed);
  104684. if (!_this._isAnimationPaused) {
  104685. _this._currentAnimation.restart();
  104686. }
  104687. if (paramsObject) {
  104688. paramsObject.selectedSpeed = speed + "x";
  104689. }
  104690. else {
  104691. navbar.updateParams({
  104692. selectedSpeed: speed + "x",
  104693. });
  104694. }
  104695. }
  104696. };
  104697. /**
  104698. * Update Current Animation Type
  104699. */
  104700. _this._updateAnimationType = function (data, paramsObject) {
  104701. var navbar = _this.templateManager.getTemplate('navBar');
  104702. if (!navbar)
  104703. return;
  104704. if (data) {
  104705. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(data.value);
  104706. }
  104707. if (paramsObject) {
  104708. paramsObject.selectedAnimation = (_this._animationList.indexOf(data.value) + 1);
  104709. paramsObject.selectedAnimationName = data.label;
  104710. }
  104711. else {
  104712. navbar.updateParams({
  104713. selectedAnimation: (_this._animationList.indexOf(data.value) + 1),
  104714. selectedAnimationName: data.label
  104715. });
  104716. }
  104717. _this._updateAnimationSpeed("1.0", paramsObject);
  104718. };
  104719. /**
  104720. * Toggle fullscreen of the entire viewer
  104721. */
  104722. _this.toggleFullscreen = function () {
  104723. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  104724. var viewerElement = viewerTemplate && viewerTemplate.parent;
  104725. var fullscreenElement = _this.fullscreenElement || viewerElement;
  104726. if (fullscreenElement) {
  104727. var currentElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  104728. if (!currentElement) {
  104729. var requestFullScreen = fullscreenElement.requestFullscreen || fullscreenElement.webkitRequestFullscreen || fullscreenElement.msRequestFullscreen || fullscreenElement.mozRequestFullScreen;
  104730. requestFullScreen.call(fullscreenElement);
  104731. if (viewerElement) {
  104732. viewerElement.classList.add("in-fullscreen");
  104733. }
  104734. }
  104735. else {
  104736. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  104737. exitFullscreen.call(document);
  104738. if (viewerElement) {
  104739. viewerElement.classList.remove("in-fullscreen");
  104740. }
  104741. }
  104742. }
  104743. };
  104744. _this._onModelLoaded = function (model) {
  104745. _this._configureTemplate(model);
  104746. // with a short timeout, making sure everything is there already.
  104747. var hideLoadingDelay = 20;
  104748. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  104749. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  104750. }
  104751. setTimeout(function () {
  104752. _this.sceneManager.scene.executeWhenReady(function () {
  104753. _this.hideLoadingScreen();
  104754. });
  104755. }, hideLoadingDelay);
  104756. return;
  104757. };
  104758. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  104759. _this.onModelRemovedObservable.add(function () {
  104760. _this._configureTemplate();
  104761. });
  104762. _this.onEngineInitObservable.add(function () {
  104763. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  104764. _this._configureLights();
  104765. });
  104766. });
  104767. _this.onInitDoneObservable.add(function () {
  104768. if (!_this.sceneManager.models.length) {
  104769. _this.hideLoadingScreen();
  104770. }
  104771. });
  104772. return _this;
  104773. }
  104774. DefaultViewer.prototype.registerTemplatePlugin = function (plugin) {
  104775. var _this = this;
  104776. //validate
  104777. if (!plugin.templateName) {
  104778. throw new Error("No template name provided");
  104779. }
  104780. this._registeredPlugins.push(plugin);
  104781. var template = this.templateManager.getTemplate(plugin.templateName);
  104782. if (!template) {
  104783. throw new Error("Template " + plugin.templateName + " not found");
  104784. }
  104785. if (plugin.addHTMLTemplate) {
  104786. template.onHTMLRendered.add(function (tmpl) {
  104787. plugin.addHTMLTemplate(tmpl);
  104788. });
  104789. template.redraw();
  104790. }
  104791. if (plugin.eventsToAttach) {
  104792. plugin.eventsToAttach.forEach(function (eventName) {
  104793. plugin.onEvent && _this.templateManager.eventManager.registerCallback(plugin.templateName, function (event) {
  104794. if (plugin.onEvent && plugin.interactionPredicate(event)) {
  104795. plugin.onEvent(event);
  104796. }
  104797. }, eventName);
  104798. });
  104799. }
  104800. };
  104801. /**
  104802. * This will be executed when the templates initialize.
  104803. */
  104804. DefaultViewer.prototype._onTemplatesLoaded = function () {
  104805. var _this = this;
  104806. this.showLoadingScreen();
  104807. // navbar
  104808. this._initNavbar();
  104809. // close overlay button
  104810. var template = this.templateManager.getTemplate('overlay');
  104811. if (template) {
  104812. var closeButton = template.parent.querySelector('.close-button');
  104813. if (closeButton) {
  104814. closeButton.addEventListener('pointerdown', function () {
  104815. _this.hideOverlayScreen();
  104816. });
  104817. }
  104818. }
  104819. if (this.configuration.templates && this.configuration.templates.viewer) {
  104820. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  104821. this.onSceneInitObservable.addOnce(function () {
  104822. var filesInput = new babylonjs_1.FilesInput(_this.engine, _this.sceneManager.scene, function () {
  104823. }, function () {
  104824. }, function () {
  104825. }, function () {
  104826. }, function () {
  104827. }, function (file) {
  104828. _this.loadModel(file);
  104829. }, function () {
  104830. });
  104831. filesInput.monitorElementForDragNDrop(_this.templateManager.getCanvas());
  104832. });
  104833. }
  104834. }
  104835. return _super.prototype._onTemplatesLoaded.call(this);
  104836. };
  104837. DefaultViewer.prototype._initNavbar = function () {
  104838. var _this = this;
  104839. var navbar = this.templateManager.getTemplate('navBar');
  104840. if (navbar) {
  104841. this.onFrameRenderedObservable.add(this._updateProgressBar);
  104842. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  104843. // an example how to trigger the help button. publiclly available
  104844. this.templateManager.eventManager.registerCallback("navBar", function () {
  104845. // do your thing
  104846. }, "pointerdown", ".help-button");
  104847. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  104848. var evt = event.event;
  104849. var element = (evt.target);
  104850. if (!_this._currentAnimation)
  104851. return;
  104852. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  104853. if (isNaN(gotoFrame))
  104854. return;
  104855. _this._currentAnimation.goToFrame(gotoFrame);
  104856. }, "input");
  104857. this.templateManager.eventManager.registerCallback("navBar", function () {
  104858. if (_this._resumePlay) {
  104859. _this._togglePlayPause(true);
  104860. }
  104861. _this._resumePlay = false;
  104862. }, "pointerup", ".progress-wrapper");
  104863. if (window.devicePixelRatio === 1 && navbar.configuration.params && !navbar.configuration.params.hideHdButton) {
  104864. navbar.updateParams({
  104865. hideHdButton: true
  104866. });
  104867. }
  104868. this.registerTemplatePlugin(new hdButtonPlugin_1.HDButtonPlugin(this));
  104869. }
  104870. };
  104871. DefaultViewer.prototype.toggleVR = function () {
  104872. _super.prototype.toggleVR.call(this);
  104873. var viewerTemplate = this.templateManager.getTemplate('viewer');
  104874. var viewerElement = viewerTemplate && viewerTemplate.parent;
  104875. if (viewerElement) {
  104876. if (this._vrToggled) {
  104877. viewerElement.classList.add("in-vr");
  104878. }
  104879. else {
  104880. viewerElement.classList.remove("in-vr");
  104881. }
  104882. }
  104883. };
  104884. /**
  104885. * Preparing the container element to present the viewer
  104886. */
  104887. DefaultViewer.prototype._prepareContainerElement = function () {
  104888. this.containerElement.style.position = 'relative';
  104889. this.containerElement.style.height = '100%';
  104890. this.containerElement.style.display = 'flex';
  104891. };
  104892. /**
  104893. * This function will configure the templates and update them after a model was loaded
  104894. * It is mainly responsible to changing the title and subtitle etc'.
  104895. * @param model the model to be used to configure the templates by
  104896. */
  104897. DefaultViewer.prototype._configureTemplate = function (model) {
  104898. var navbar = this.templateManager.getTemplate('navBar');
  104899. if (!navbar)
  104900. return;
  104901. var newParams = navbar.configuration.params || {};
  104902. if (!model) {
  104903. newParams.animations = null;
  104904. }
  104905. else {
  104906. var animationNames = model.getAnimationNames();
  104907. newParams.animations = animationNames.map(function (a) { return { label: a, value: a }; });
  104908. if (animationNames.length) {
  104909. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  104910. this._animationList = animationNames;
  104911. newParams.paused = this._isAnimationPaused;
  104912. var animationIndex = 0;
  104913. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  104914. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  104915. if (animationIndex === -1) {
  104916. animationIndex = 0;
  104917. }
  104918. }
  104919. this._updateAnimationType(newParams.animations[animationIndex], newParams);
  104920. }
  104921. else {
  104922. newParams.animations = null;
  104923. }
  104924. if (model.configuration.thumbnail) {
  104925. newParams.logoImage = model.configuration.thumbnail;
  104926. }
  104927. }
  104928. navbar.updateParams(newParams, false);
  104929. };
  104930. /**
  104931. * This will load a new model to the default viewer
  104932. * overriding the AbstractViewer's loadModel.
  104933. * The scene will automatically be cleared of the old models, if exist.
  104934. * @param model the configuration object (or URL) to load.
  104935. */
  104936. DefaultViewer.prototype.loadModel = function (model) {
  104937. var _this = this;
  104938. if (!model) {
  104939. model = this.configuration.model;
  104940. }
  104941. this.showLoadingScreen();
  104942. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  104943. console.log(error);
  104944. _this.hideLoadingScreen();
  104945. _this.showOverlayScreen('error');
  104946. return Promise.reject(error);
  104947. });
  104948. };
  104949. /**
  104950. * Show the overlay and the defined sub-screen.
  104951. * Mainly used for help and errors
  104952. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  104953. */
  104954. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  104955. var _this = this;
  104956. var template = this.templateManager.getTemplate('overlay');
  104957. if (!template)
  104958. return Promise.resolve('Overlay template not found');
  104959. return template.show((function (template) {
  104960. var canvasRect = _this.containerElement.getBoundingClientRect();
  104961. template.parent.style.display = 'flex';
  104962. template.parent.style.width = canvasRect.width + "px";
  104963. template.parent.style.height = canvasRect.height + "px";
  104964. template.parent.style.opacity = "1";
  104965. var subTemplate = _this.templateManager.getTemplate(subScreen);
  104966. if (!subTemplate) {
  104967. return Promise.reject(subScreen + ' template not found');
  104968. }
  104969. return subTemplate.show((function (template) {
  104970. template.parent.style.display = 'flex';
  104971. return Promise.resolve(template);
  104972. }));
  104973. }));
  104974. };
  104975. /**
  104976. * Hide the overlay screen.
  104977. */
  104978. DefaultViewer.prototype.hideOverlayScreen = function () {
  104979. var template = this.templateManager.getTemplate('overlay');
  104980. if (!template)
  104981. return Promise.resolve('Overlay template not found');
  104982. return template.hide((function (template) {
  104983. template.parent.style.opacity = "0";
  104984. var onTransitionEnd = function () {
  104985. template.parent.removeEventListener("transitionend", onTransitionEnd);
  104986. template.parent.style.display = 'none';
  104987. };
  104988. template.parent.addEventListener("transitionend", onTransitionEnd);
  104989. var overlays = template.parent.querySelectorAll('.overlay');
  104990. if (overlays) {
  104991. for (var i = 0; i < overlays.length; ++i) {
  104992. var htmlElement = overlays.item(i);
  104993. htmlElement.style.display = 'none';
  104994. }
  104995. }
  104996. return Promise.resolve(template);
  104997. }));
  104998. };
  104999. /**
  105000. * show the viewer (in case it was hidden)
  105001. *
  105002. * @param visibilityFunction an optional function to execute in order to show the container
  105003. */
  105004. DefaultViewer.prototype.show = function (visibilityFunction) {
  105005. var template = this.templateManager.getTemplate('main');
  105006. //not possible, but yet:
  105007. if (!template)
  105008. return Promise.reject('Main template not found');
  105009. return template.show(visibilityFunction);
  105010. };
  105011. /**
  105012. * hide the viewer (in case it is visible)
  105013. *
  105014. * @param visibilityFunction an optional function to execute in order to hide the container
  105015. */
  105016. DefaultViewer.prototype.hide = function (visibilityFunction) {
  105017. var template = this.templateManager.getTemplate('main');
  105018. //not possible, but yet:
  105019. if (!template)
  105020. return Promise.reject('Main template not found');
  105021. return template.hide(visibilityFunction);
  105022. };
  105023. /**
  105024. * Show the loading screen.
  105025. * The loading screen can be configured using the configuration object
  105026. */
  105027. DefaultViewer.prototype.showLoadingScreen = function () {
  105028. var _this = this;
  105029. var template = this.templateManager.getTemplate('loadingScreen');
  105030. if (!template)
  105031. return Promise.resolve('Loading Screen template not found');
  105032. return template.show((function (template) {
  105033. var canvasRect = _this.containerElement.getBoundingClientRect();
  105034. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  105035. template.parent.style.display = 'flex';
  105036. template.parent.style.width = canvasRect.width + "px";
  105037. template.parent.style.height = canvasRect.height + "px";
  105038. template.parent.style.opacity = "1";
  105039. // from the configuration!!!
  105040. var color = "black";
  105041. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  105042. color = (_this.configuration.templates.loadingScreen.params &&
  105043. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  105044. }
  105045. template.parent.style.backgroundColor = color;
  105046. return Promise.resolve(template);
  105047. }));
  105048. };
  105049. /**
  105050. * Hide the loading screen
  105051. */
  105052. DefaultViewer.prototype.hideLoadingScreen = function () {
  105053. var template = this.templateManager.getTemplate('loadingScreen');
  105054. if (!template)
  105055. return Promise.resolve('Loading Screen template not found');
  105056. return template.hide((function (template) {
  105057. template.parent.style.opacity = "0";
  105058. var onTransitionEnd = function () {
  105059. template.parent.removeEventListener("transitionend", onTransitionEnd);
  105060. template.parent.style.display = 'none';
  105061. };
  105062. template.parent.addEventListener("transitionend", onTransitionEnd);
  105063. return Promise.resolve(template);
  105064. }));
  105065. };
  105066. DefaultViewer.prototype.dispose = function () {
  105067. this.templateManager.dispose();
  105068. _super.prototype.dispose.call(this);
  105069. };
  105070. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  105071. var _this = this;
  105072. _super.prototype._onConfigurationLoaded.call(this, configuration);
  105073. // initialize the templates
  105074. var templateConfiguration = this.configuration.templates || {};
  105075. this.templateManager.initTemplate(templateConfiguration);
  105076. // when done, execute onTemplatesLoaded()
  105077. this.templateManager.onAllLoaded.add(function () {
  105078. var canvas = _this.templateManager.getCanvas();
  105079. if (canvas) {
  105080. _this._canvas = canvas;
  105081. }
  105082. _this._onTemplateLoaded();
  105083. });
  105084. };
  105085. /**
  105086. * An extension of the light configuration of the abstract viewer.
  105087. * @param lightsConfiguration the light configuration to use
  105088. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  105089. */
  105090. DefaultViewer.prototype._configureLights = function () {
  105091. var _this = this;
  105092. // labs feature - flashlight
  105093. if (this.configuration.lab && this.configuration.lab.flashlight) {
  105094. var lightTarget_1;
  105095. var angle = 0.5;
  105096. var exponent = Math.PI / 2;
  105097. if (typeof this.configuration.lab.flashlight === "object") {
  105098. exponent = this.configuration.lab.flashlight.exponent || exponent;
  105099. angle = this.configuration.lab.flashlight.angle || angle;
  105100. }
  105101. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  105102. if (typeof this.configuration.lab.flashlight === "object") {
  105103. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  105104. if (this.configuration.lab.flashlight.diffuse) {
  105105. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  105106. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  105107. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  105108. }
  105109. if (this.configuration.lab.flashlight.specular) {
  105110. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  105111. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  105112. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  105113. }
  105114. }
  105115. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  105116. this.sceneManager.scene.onPointerObservable.add(function (eventData) {
  105117. if (eventData.type === 4 && eventData.pickInfo) {
  105118. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  105119. }
  105120. else {
  105121. lightTarget_1 = undefined;
  105122. }
  105123. });
  105124. var updateFlashlightFunction = function () {
  105125. if (_this.sceneManager.camera && flashlight) {
  105126. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  105127. if (lightTarget_1) {
  105128. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  105129. }
  105130. }
  105131. };
  105132. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  105133. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  105134. }
  105135. };
  105136. return DefaultViewer;
  105137. }(viewer_1.AbstractViewer));
  105138. exports.DefaultViewer = DefaultViewer;
  105139. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdFZpZXdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvZGVmYXVsdFZpZXdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFJQSxtQ0FBMEM7QUFDMUMsdUNBQTJEO0FBSTNELHVFQUFzRTtBQUV0RTs7O0dBR0c7QUFDSDtJQUFtQyxpQ0FBYztJQUk3Qzs7OztPQUlHO0lBQ0gsdUJBQW1CLGdCQUE2QixFQUFFLG9CQUFrRTtRQUFsRSxxQ0FBQSxFQUFBLHlCQUE4QyxPQUFPLEVBQUUsU0FBUyxFQUFFO1FBQXBILFlBQ0ksa0JBQU0sZ0JBQWdCLEVBQUUsb0JBQW9CLENBQUMsU0FrQmhEO1FBbkJrQixzQkFBZ0IsR0FBaEIsZ0JBQWdCLENBQWE7UUFxQnhDLHdCQUFrQixHQUFpQyxFQUFFLENBQUM7UUFpSHRELHdCQUFrQixHQUFHLFVBQUMsS0FBb0I7WUFFOUMsSUFBSSxXQUFXLEdBQWlCLEtBQUssQ0FBQyxLQUFLLENBQUM7WUFDNUMsSUFBSSxXQUFXLENBQUMsTUFBTSxLQUFLLENBQUM7Z0JBQUUsT0FBTztZQUNyQyxJQUFJLE9BQU8sR0FBaUIsS0FBSyxDQUFDLEtBQUssQ0FBQyxNQUFPLENBQUM7W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RQUFRLENBQUMsS0FBSSxDQUFDLFlBQVksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLENBQUM7b0JBQ2hFLElBQUksYUFBVyxFQUFFO3dCQUNiLGFBQVcsQ0FBQyxhQUFhLENBQUMsVUFBVSxDQUFDLFFBQVEsRUFBRSxVQUFVLENBQUMsU0FBUyxDQUFDLENBQUM7cUJBQ3hFO2lCQUNKO1lBQ0wsQ0FBQyxDQUFBO1lBQ0QsSUFBSSxDQUFDLFlBQVksQ0FBQyxLQUFLLENBQUMsb0JBQW9CLENBQUMsd0JBQXdCLENBQUMsQ0FBQztZQUN2RSxJQUFJLENBQUMsa0NBQWtDLENBQUMsSUFBSSxDQUFDLHdCQUF3QixDQUFDLENBQUM7U0FDMUU7SUFDTCxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBN25CRCxDQUFtQyx1QkFBYyxHQTZuQmhEO0FBN25CWSxzQ0FBYSJ9
  105140. /***/ }),
  105141. /* 9 */
  105142. /***/ (function(module, exports, __webpack_require__) {
  105143. "use strict";
  105144. Object.defineProperty(exports, "__esModule", { value: true });
  105145. var babylonjs_1 = __webpack_require__(0);
  105146. var configurationCompatibility_1 = __webpack_require__(10);
  105147. var configurationContainer_1 = __webpack_require__(26);
  105148. var globals_1 = __webpack_require__(4);
  105149. var loader_1 = __webpack_require__(27);
  105150. var _1 = __webpack_require__(1);
  105151. var modelLoader_1 = __webpack_require__(12);
  105152. var observablesManager_1 = __webpack_require__(58);
  105153. var sceneManager_1 = __webpack_require__(59);
  105154. var telemetryManager_1 = __webpack_require__(6);
  105155. var templateManager_1 = __webpack_require__(63);
  105156. var viewerManager_1 = __webpack_require__(7);
  105157. /**
  105158. * The AbstractViewr is the center of Babylon's viewer.
  105159. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  105160. */
  105161. var AbstractViewer = /** @class */ (function () {
  105162. function AbstractViewer(containerElement, initialConfiguration) {
  105163. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  105164. var _this = this;
  105165. this.containerElement = containerElement;
  105166. /**
  105167. * A flag that controls whether or not the render loop should be executed
  105168. */
  105169. this.runRenderLoop = true;
  105170. /**
  105171. * is this viewer disposed?
  105172. */
  105173. this._isDisposed = false;
  105174. this._hdToggled = false;
  105175. this._vrToggled = false;
  105176. this._vrModelRepositioning = 0;
  105177. this._vrScale = 1;
  105178. /**
  105179. * The resize function that will be registered with the window object
  105180. */
  105181. this._resize = function () {
  105182. // Only resize if Canvas is in the DOM
  105183. if (!_this.isCanvasInDOM()) {
  105184. return;
  105185. }
  105186. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  105187. return;
  105188. }
  105189. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  105190. return;
  105191. }
  105192. _this.engine.resize();
  105193. };
  105194. /**
  105195. * render loop that will be executed by the engine
  105196. */
  105197. this._render = function (force) {
  105198. if (force === void 0) { force = false; }
  105199. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  105200. if (_this.runRenderLoop || force) {
  105201. _this.engine.performanceMonitor.enable();
  105202. _this.sceneManager.scene.render();
  105203. _this.onFrameRenderedObservable.notifyObservers(_this);
  105204. }
  105205. else {
  105206. _this.engine.performanceMonitor.disable();
  105207. // update camera instead of rendering
  105208. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  105209. }
  105210. }
  105211. };
  105212. // if exists, use the container id. otherwise, generate a random string.
  105213. if (containerElement.id) {
  105214. this.baseId = containerElement.id;
  105215. }
  105216. else {
  105217. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  105218. }
  105219. this._registeredOnBeforeRenderFunctions = [];
  105220. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  105221. // add this viewer to the viewer manager
  105222. viewerManager_1.viewerManager.addViewer(this);
  105223. this.observablesManager = new observablesManager_1.ObservablesManager();
  105224. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  105225. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  105226. // extend the configuration
  105227. this._configurationLoader = new loader_1.ConfigurationLoader();
  105228. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  105229. _this._onConfigurationLoaded(configuration);
  105230. });
  105231. this.onSceneInitObservable.add(function () {
  105232. _this.updateConfiguration();
  105233. });
  105234. this.onInitDoneObservable.add(function () {
  105235. _this._isInit = true;
  105236. _this.engine.runRenderLoop(_this._render);
  105237. });
  105238. this._prepareContainerElement();
  105239. }
  105240. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  105241. // observables
  105242. /**
  105243. * Will notify when the scene was initialized
  105244. */
  105245. get: function () {
  105246. return this.observablesManager.onSceneInitObservable;
  105247. },
  105248. enumerable: true,
  105249. configurable: true
  105250. });
  105251. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  105252. /**
  105253. * will notify when the engine was initialized
  105254. */
  105255. get: function () {
  105256. return this.observablesManager.onEngineInitObservable;
  105257. },
  105258. enumerable: true,
  105259. configurable: true
  105260. });
  105261. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  105262. /**
  105263. * Will notify when a new model was added to the scene.
  105264. * Note that added does not neccessarily mean loaded!
  105265. */
  105266. get: function () {
  105267. return this.observablesManager.onModelAddedObservable;
  105268. },
  105269. enumerable: true,
  105270. configurable: true
  105271. });
  105272. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  105273. /**
  105274. * will notify after every model load
  105275. */
  105276. get: function () {
  105277. return this.observablesManager.onModelLoadedObservable;
  105278. },
  105279. enumerable: true,
  105280. configurable: true
  105281. });
  105282. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  105283. /**
  105284. * will notify when any model notify of progress
  105285. */
  105286. get: function () {
  105287. return this.observablesManager.onModelLoadProgressObservable;
  105288. },
  105289. enumerable: true,
  105290. configurable: true
  105291. });
  105292. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  105293. /**
  105294. * will notify when any model load failed.
  105295. */
  105296. get: function () {
  105297. return this.observablesManager.onModelLoadErrorObservable;
  105298. },
  105299. enumerable: true,
  105300. configurable: true
  105301. });
  105302. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  105303. /**
  105304. * Will notify when a model was removed from the scene;
  105305. */
  105306. get: function () {
  105307. return this.observablesManager.onModelRemovedObservable;
  105308. },
  105309. enumerable: true,
  105310. configurable: true
  105311. });
  105312. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  105313. /**
  105314. * will notify when a new loader was initialized.
  105315. * Used mainly to know when a model starts loading.
  105316. */
  105317. get: function () {
  105318. return this.observablesManager.onLoaderInitObservable;
  105319. },
  105320. enumerable: true,
  105321. configurable: true
  105322. });
  105323. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  105324. /**
  105325. * Observers registered here will be executed when the entire load process has finished.
  105326. */
  105327. get: function () {
  105328. return this.observablesManager.onViewerInitDoneObservable;
  105329. },
  105330. enumerable: true,
  105331. configurable: true
  105332. });
  105333. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  105334. /**
  105335. * Functions added to this observable will be executed on each frame rendered.
  105336. */
  105337. get: function () {
  105338. return this.observablesManager.onFrameRenderedObservable;
  105339. },
  105340. enumerable: true,
  105341. configurable: true
  105342. });
  105343. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  105344. /**
  105345. * The (single) canvas of this viewer
  105346. */
  105347. get: function () {
  105348. return this._canvas;
  105349. },
  105350. enumerable: true,
  105351. configurable: true
  105352. });
  105353. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  105354. get: function () {
  105355. return this._configurationContainer;
  105356. },
  105357. enumerable: true,
  105358. configurable: true
  105359. });
  105360. /**
  105361. * get the baseId of this viewer
  105362. */
  105363. AbstractViewer.prototype.getBaseId = function () {
  105364. return this.baseId;
  105365. };
  105366. /**
  105367. * Do we have a canvas to render on, and is it a part of the scene
  105368. */
  105369. AbstractViewer.prototype.isCanvasInDOM = function () {
  105370. return !!this._canvas && !!this._canvas.parentElement;
  105371. };
  105372. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  105373. /**
  105374. * Is the engine currently set to rende even when the page is in background
  105375. */
  105376. get: function () {
  105377. return this.engine && this.engine.renderEvenInBackground;
  105378. },
  105379. /**
  105380. * Set the viewer's background rendering flag.
  105381. */
  105382. set: function (value) {
  105383. if (this.engine) {
  105384. this.engine.renderEvenInBackground = value;
  105385. }
  105386. },
  105387. enumerable: true,
  105388. configurable: true
  105389. });
  105390. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  105391. /**
  105392. * Get the configuration object. This is a reference only.
  105393. * The configuration can ONLY be updated using the updateConfiguration function.
  105394. * changing this object will have no direct effect on the scene.
  105395. */
  105396. get: function () {
  105397. return this._configurationContainer.configuration;
  105398. },
  105399. enumerable: true,
  105400. configurable: true
  105401. });
  105402. /**
  105403. * force resizing the engine.
  105404. */
  105405. AbstractViewer.prototype.forceResize = function () {
  105406. this._resize();
  105407. };
  105408. AbstractViewer.prototype.toggleHD = function () {
  105409. this._hdToggled = !this._hdToggled;
  105410. var scale = this._hdToggled ? Math.max(0.5, 1 / (window.devicePixelRatio || 2)) : 1;
  105411. this.engine.setHardwareScalingLevel(scale);
  105412. };
  105413. AbstractViewer.prototype.toggleVR = function () {
  105414. this._vrToggled = !this._vrToggled;
  105415. if (this._vrToggled && this.sceneManager.vrHelper) {
  105416. // make sure the floor is set
  105417. if (this.sceneManager.environmentHelper && this.sceneManager.environmentHelper.ground) {
  105418. this.sceneManager.vrHelper.addFloorMesh(this.sceneManager.environmentHelper.ground);
  105419. }
  105420. this.sceneManager.vrHelper.enterVR();
  105421. // position the vr camera to be in front of the object or wherever the user has configured it to be
  105422. if (this.sceneManager.vrHelper.currentVRCamera) {
  105423. if (this.configuration.vr && this.configuration.vr.cameraPosition !== undefined) {
  105424. this.sceneManager.vrHelper.currentVRCamera.position.copyFrom(this.configuration.vr.cameraPosition);
  105425. }
  105426. else {
  105427. this.sceneManager.vrHelper.currentVRCamera.position.copyFromFloats(0, this.sceneManager.vrHelper.currentVRCamera.position.y, -1);
  105428. }
  105429. this.sceneManager.vrHelper.currentVRCamera.rotationQuaternion && this.sceneManager.vrHelper.currentVRCamera.rotationQuaternion.copyFromFloats(0, 0, 0, 1);
  105430. // set the height of the model to be what the user has configured, or floating by default
  105431. if (this.configuration.vr && this.configuration.vr.modelHeightCorrection !== undefined) {
  105432. if (typeof this.configuration.vr.modelHeightCorrection === 'number') {
  105433. this._vrModelRepositioning = this.configuration.vr.modelHeightCorrection;
  105434. }
  105435. else if (this.configuration.vr.modelHeightCorrection) {
  105436. this._vrModelRepositioning = this.sceneManager.vrHelper.currentVRCamera.position.y / 2;
  105437. }
  105438. else {
  105439. this._vrModelRepositioning = 0;
  105440. }
  105441. }
  105442. }
  105443. else {
  105444. this._vrModelRepositioning = 0;
  105445. }
  105446. // scale the model
  105447. if (this.sceneManager.models.length) {
  105448. var boundingVectors = this.sceneManager.models[0].rootMesh.getHierarchyBoundingVectors();
  105449. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  105450. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  105451. this._vrScale = (1 / maxDimension);
  105452. if (this.configuration.vr && this.configuration.vr.objectScaleFactor) {
  105453. this._vrScale *= this.configuration.vr.objectScaleFactor;
  105454. }
  105455. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(this._vrScale);
  105456. // reposition the object to "float" in front of the user
  105457. this.sceneManager.models[0].rootMesh.position.y += this._vrModelRepositioning;
  105458. this.sceneManager.models[0].rootMesh.rotationQuaternion = null;
  105459. }
  105460. // scale the environment to match the model
  105461. if (this.sceneManager.environmentHelper) {
  105462. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(this._vrScale);
  105463. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(this._vrScale);
  105464. }
  105465. // post processing
  105466. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  105467. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = false;
  105468. this.sceneManager.defaultRenderingPipeline.prepare();
  105469. }
  105470. }
  105471. else {
  105472. if (this.sceneManager.vrHelper) {
  105473. this.sceneManager.vrHelper.exitVR();
  105474. // undo the scaling of the model
  105475. if (this.sceneManager.models.length) {
  105476. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(1 / this._vrScale);
  105477. this.sceneManager.models[0].rootMesh.position.y -= this._vrModelRepositioning;
  105478. }
  105479. // undo the scaling of the environment
  105480. if (this.sceneManager.environmentHelper) {
  105481. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(1 / this._vrScale);
  105482. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(1 / this._vrScale);
  105483. }
  105484. // post processing
  105485. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  105486. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = true;
  105487. this.sceneManager.defaultRenderingPipeline.prepare();
  105488. }
  105489. }
  105490. }
  105491. };
  105492. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  105493. var _this = this;
  105494. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  105495. if (this.configuration.observers) {
  105496. this._configureObservers(this.configuration.observers);
  105497. }
  105498. // TODO remove this after testing, as this is done in the updateConfiguration as well.
  105499. if (this.configuration.loaderPlugins) {
  105500. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  105501. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  105502. _this.modelLoader.addPlugin(name);
  105503. }
  105504. }));
  105505. }
  105506. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  105507. this.observablesManager.onViewerInitStartedObservable.notifyObservers(this);
  105508. };
  105509. /**
  105510. * Force a single render loop execution.
  105511. */
  105512. AbstractViewer.prototype.forceRender = function () {
  105513. this._render(true);
  105514. };
  105515. /**
  105516. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  105517. * @param callback optional callback that will be triggered when screenshot is done.
  105518. * @param width Optional screenshot width (default to 512).
  105519. * @param height Optional screenshot height (default to 512).
  105520. * @returns a promise with the screenshot data
  105521. */
  105522. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  105523. var _this = this;
  105524. if (width === void 0) { width = 0; }
  105525. if (height === void 0) { height = 0; }
  105526. width = width || this.canvas.clientWidth;
  105527. height = height || this.canvas.clientHeight;
  105528. // Create the screenshot
  105529. return new Promise(function (resolve, reject) {
  105530. try {
  105531. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  105532. if (callback) {
  105533. callback(data);
  105534. }
  105535. resolve(data);
  105536. });
  105537. }
  105538. catch (e) {
  105539. reject(e);
  105540. }
  105541. });
  105542. };
  105543. /**
  105544. * Update the current viewer configuration with new values.
  105545. * Only provided information will be updated, old configuration values will be kept.
  105546. * If this.configuration was manually changed, you can trigger this function with no parameters,
  105547. * and the entire configuration will be updated.
  105548. * @param newConfiguration the partial configuration to update or a URL to a JSON holding the updated configuration
  105549. *
  105550. */
  105551. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  105552. var _this = this;
  105553. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  105554. if (typeof newConfiguration === "string") {
  105555. babylonjs_1.Tools.LoadFile(newConfiguration, function (data) {
  105556. try {
  105557. var newData = JSON.parse(data.toString());
  105558. return _this.updateConfiguration(newData);
  105559. }
  105560. catch (e) {
  105561. console.log("Error parsing file " + newConfiguration);
  105562. }
  105563. }, undefined, undefined, undefined, function (error) {
  105564. console.log("Error parsing file " + newConfiguration, error);
  105565. });
  105566. }
  105567. else {
  105568. //backcompat
  105569. configurationCompatibility_1.processConfigurationCompatibility(newConfiguration);
  105570. // update this.configuration with the new data
  105571. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  105572. this.sceneManager.updateConfiguration(newConfiguration);
  105573. // observers in configuration
  105574. if (newConfiguration.observers) {
  105575. this._configureObservers(newConfiguration.observers);
  105576. }
  105577. if (newConfiguration.loaderPlugins) {
  105578. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  105579. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  105580. _this.modelLoader.addPlugin(name);
  105581. }
  105582. }));
  105583. }
  105584. }
  105585. };
  105586. /**
  105587. * this is used to register native functions using the configuration object.
  105588. * This will configure the observers.
  105589. * @param observersConfiguration observers configuration
  105590. */
  105591. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  105592. if (observersConfiguration.onEngineInit) {
  105593. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  105594. }
  105595. else {
  105596. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  105597. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  105598. }
  105599. }
  105600. if (observersConfiguration.onSceneInit) {
  105601. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  105602. }
  105603. else {
  105604. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  105605. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  105606. }
  105607. }
  105608. if (observersConfiguration.onModelLoaded) {
  105609. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  105610. }
  105611. else {
  105612. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  105613. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  105614. }
  105615. }
  105616. };
  105617. /**
  105618. * Dispoe the entire viewer including the scene and the engine
  105619. */
  105620. AbstractViewer.prototype.dispose = function () {
  105621. if (this._isDisposed) {
  105622. return;
  105623. }
  105624. window.removeEventListener('resize', this._resize);
  105625. if (this.sceneManager) {
  105626. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  105627. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  105628. }
  105629. this.sceneManager.dispose();
  105630. }
  105631. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  105632. this.observablesManager.dispose();
  105633. this.modelLoader.dispose();
  105634. if (this.engine) {
  105635. this.engine.dispose();
  105636. }
  105637. viewerManager_1.viewerManager.removeViewer(this);
  105638. this._isDisposed = true;
  105639. };
  105640. /**
  105641. * This function will execute when the HTML templates finished initializing.
  105642. * It should initialize the engine and continue execution.
  105643. *
  105644. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  105645. */
  105646. AbstractViewer.prototype._onTemplatesLoaded = function () {
  105647. return Promise.resolve(this);
  105648. };
  105649. /**
  105650. * This will force the creation of an engine and a scene.
  105651. * It will also load a model if preconfigured.
  105652. * But first - it will load the extendible onTemplateLoaded()!
  105653. */
  105654. AbstractViewer.prototype._onTemplateLoaded = function () {
  105655. var _this = this;
  105656. // check if viewer was disposed right after created
  105657. if (this._isDisposed) {
  105658. return Promise.reject("viewer was disposed");
  105659. }
  105660. return this._onTemplatesLoaded().then(function () {
  105661. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  105662. return _this._initEngine().then(function (engine) {
  105663. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  105664. }).then(function () {
  105665. _this._initTelemetryEvents();
  105666. if (autoLoad) {
  105667. return _this.loadModel(_this.configuration.model).catch(function () { }).then(function () { return _this.sceneManager.scene; });
  105668. }
  105669. else {
  105670. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  105671. }
  105672. }).then(function () {
  105673. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  105674. }).catch(function (e) {
  105675. babylonjs_1.Tools.Warn(e.toString());
  105676. return _this;
  105677. });
  105678. });
  105679. };
  105680. /**
  105681. * Initialize the engine. Retruns a promise in case async calls are needed.
  105682. *
  105683. * @protected
  105684. * @returns {Promise<Engine>}
  105685. * @memberof Viewer
  105686. */
  105687. AbstractViewer.prototype._initEngine = function () {
  105688. // init custom shaders
  105689. this._injectCustomShaders();
  105690. //let canvasElement = this.templateManager.getCanvas();
  105691. if (!this.canvas) {
  105692. return Promise.reject('Canvas element not found!');
  105693. }
  105694. var config = this.configuration.engine || {};
  105695. // TDO enable further configuration
  105696. // check for webgl2 support, force-disable if needed.
  105697. if (globals_1.viewerGlobals.disableWebGL2Support) {
  105698. config.engineOptions = config.engineOptions || {};
  105699. config.engineOptions.disableWebGL2Support = true;
  105700. }
  105701. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  105702. // Disable manifest checking
  105703. babylonjs_1.Database.IDBStorageEnabled = false;
  105704. if (!config.disableResize) {
  105705. window.addEventListener('resize', this._resize);
  105706. }
  105707. if (this.configuration.engine) {
  105708. if (this.configuration.engine.adaptiveQuality) {
  105709. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  105710. this.engine.setHardwareScalingLevel(scale);
  105711. }
  105712. if (this.configuration.engine.hdEnabled) {
  105713. this.toggleHD();
  105714. }
  105715. }
  105716. // create a new template manager for this viewer
  105717. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  105718. return Promise.resolve(this.engine);
  105719. };
  105720. /**
  105721. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  105722. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  105723. *
  105724. * @param modelConfig model configuration to use when loading the model.
  105725. * @param clearScene should the scene be cleared before loading this model
  105726. * @returns a ViewerModel object that is not yet fully loaded.
  105727. */
  105728. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  105729. var _this = this;
  105730. if (clearScene === void 0) { clearScene = true; }
  105731. var configuration;
  105732. if (typeof modelConfig === 'string') {
  105733. configuration = {
  105734. url: modelConfig
  105735. };
  105736. }
  105737. else if (modelConfig instanceof File) {
  105738. configuration = {
  105739. file: modelConfig,
  105740. root: "file:"
  105741. };
  105742. }
  105743. else {
  105744. configuration = modelConfig;
  105745. }
  105746. if (!configuration.url && !configuration.file) {
  105747. throw new Error("no model provided");
  105748. }
  105749. if (clearScene) {
  105750. this.sceneManager.clearScene(true, false);
  105751. }
  105752. //merge the configuration for future models:
  105753. if (this.configuration.model && typeof this.configuration.model === 'object') {
  105754. var globalConfig = _1.deepmerge({}, this.configuration.model);
  105755. configuration = _1.deepmerge(globalConfig, configuration);
  105756. if (modelConfig instanceof File) {
  105757. configuration.file = modelConfig;
  105758. }
  105759. }
  105760. else {
  105761. this.configuration.model = configuration;
  105762. }
  105763. this._isLoading = true;
  105764. var model = this.modelLoader.load(configuration);
  105765. this.lastUsedLoader = model.loader;
  105766. model.onLoadErrorObservable.add(function (errorObject) {
  105767. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  105768. });
  105769. model.onLoadProgressObservable.add(function (progressEvent) {
  105770. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  105771. });
  105772. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  105773. model.onLoadedObservable.add(function () {
  105774. _this._isLoading = false;
  105775. });
  105776. return model;
  105777. };
  105778. /**
  105779. * load a model using the provided configuration.
  105780. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  105781. * If you want to attach to the observables of the model, use initModle instead.
  105782. *
  105783. * @param modelConfig the model configuration or URL to load.
  105784. * @param clearScene Should the scene be cleared before loading the model
  105785. * @returns a Promise the fulfills when the model finished loading successfully.
  105786. */
  105787. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  105788. var _this = this;
  105789. if (clearScene === void 0) { clearScene = true; }
  105790. if (this._isLoading) {
  105791. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  105792. return Promise.reject("another model is curently being loaded.");
  105793. }
  105794. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  105795. if (!scene)
  105796. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  105797. return scene;
  105798. }).then(function () {
  105799. var model = _this.initModel(modelConfig, clearScene);
  105800. return new Promise(function (resolve, reject) {
  105801. // at this point, configuration.model is an object, not a string
  105802. model.onLoadedObservable.add(function () {
  105803. resolve(model);
  105804. });
  105805. model.onLoadErrorObservable.add(function (error) {
  105806. reject(error);
  105807. });
  105808. });
  105809. });
  105810. };
  105811. AbstractViewer.prototype._initTelemetryEvents = function () {
  105812. var _this = this;
  105813. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  105814. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  105815. userAgent: navigator.userAgent,
  105816. platform: navigator.platform
  105817. });
  105818. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  105819. var trackFPS = function () {
  105820. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  105821. };
  105822. trackFPS();
  105823. // Track the FPS again after 60 seconds
  105824. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  105825. };
  105826. /**
  105827. * Injects all the spectre shader in the babylon shader store
  105828. */
  105829. AbstractViewer.prototype._injectCustomShaders = function () {
  105830. var customShaders = this.configuration.customShaders;
  105831. // Inject all the spectre shader in the babylon shader store.
  105832. if (!customShaders) {
  105833. return;
  105834. }
  105835. if (customShaders.shaders) {
  105836. Object.keys(customShaders.shaders).forEach(function (key) {
  105837. // typescript considers a callback "unsafe", so... '!'
  105838. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  105839. });
  105840. }
  105841. if (customShaders.includes) {
  105842. Object.keys(customShaders.includes).forEach(function (key) {
  105843. // typescript considers a callback "unsafe", so... '!'
  105844. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  105845. });
  105846. }
  105847. };
  105848. return AbstractViewer;
  105849. }());
  105850. exports.AbstractViewer = AbstractViewer;
  105851. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBK0w7QUFFL0wsMEZBQWdHO0FBQ2hHLGtGQUFpRjtBQUNqRixvREFBeUQ7QUFDekQsa0RBQThEO0FBQzlELCtCQUF1QztBQUN2QyxxREFBb0Q7QUFDcEQscUVBQW9FO0FBQ3BFLHlEQUF3RDtBQUN4RCxpRUFBZ0U7QUFFaEUsaUVBQWdFO0FBQ2hFLGlEQUFnRDtBQUdoRDs7O0dBR0c7QUFDSDtJQWdKSSx3QkFBbUIsZ0JBQTZCLEVBQUUsb0JBQThDO1FBQTlDLHFDQUFBLEVBQUEseUJBQThDO1FBQWhHLGlCQXNDQztRQXRDa0IscUJBQWdCLEdBQWhCLGdCQUFnQixDQUFhO1FBckhoRDs7V0FFRztRQUNJLGtCQUFhLEdBQVksSUFBSSxDQUFDO1FBd0ZyQzs7V0FFRztRQUNPLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBNkc3QixlQUFVLEdBQVksS0FBSyxDQUFDO1FBVTVCLGVBQVUsR0FBWSxLQUFLLENBQUM7UUFDOUIsMEJBQXFCLEdBQVcsQ0FBQyxDQUFDO1FBQ2hDLGFBQVEsR0FBVyxDQUFDLENBQUM7UUF3Ri9COztXQUVHO1FBQ08sWUFBTyxHQUFHO1lBQ2hCLHNDQUFzQztZQUN0QyxJQUFJLENBQUMsS0FBSSxDQUFDLGFBQWEsRUFBRSxFQUFFO2dCQUN2QixPQUFPO2FBQ1Y7WUFFRCxJQUFJLEtBQUksQ0FBQyxNQUFNLENBQUM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FDdEQsa0JBQU0sQ0FBQyxvQkFBb0IsQ0FBQyxHQUFHLENBQUMsR0FBRyxhQUFjLENBQUMsUUFBUyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1lBQ3JFLENBQUMsQ0FBQyxDQUFDO1NBQ047SUFDTCxDQUFDO0lBQ0wscUJBQUM7QUFBRCxDQUFDLEFBenZCRCxJQXl2QkM7QUF6dkJxQix3Q0FBYyJ9
  105852. /***/ }),
  105853. /* 10 */
  105854. /***/ (function(module, exports, __webpack_require__) {
  105855. "use strict";
  105856. Object.defineProperty(exports, "__esModule", { value: true });
  105857. var configuration_1 = __webpack_require__(11);
  105858. /**
  105859. * This function will make sure the configuration file is taking deprecated fields into account
  105860. * and is setting them to the correct keys and values.
  105861. *
  105862. * @param configuration The configuration to process. Mutable!
  105863. */
  105864. function processConfigurationCompatibility(configuration) {
  105865. if (configuration.camera) {
  105866. // camera contrast -> image processing contrast
  105867. if (configuration.camera.contrast !== undefined) {
  105868. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  105869. }
  105870. // camera exposure -> image processing exposure
  105871. if (configuration.camera.exposure !== undefined) {
  105872. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  105873. }
  105874. }
  105875. if (configuration.scene) {
  105876. //glow
  105877. if (configuration.scene.glow) {
  105878. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  105879. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  105880. if (enabledProcessing !== false) {
  105881. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  105882. }
  105883. }
  105884. }
  105885. if (configuration.model && typeof configuration.model === 'object') {
  105886. // castShadows === castShadow
  105887. if (configuration.model.castShadows !== undefined && configuration.model.castShadow === undefined) {
  105888. configuration.model.castShadow = configuration.model.castShadows;
  105889. }
  105890. }
  105891. }
  105892. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  105893. function setKeyInObject(object, keys, value, shouldOverwrite) {
  105894. var keySplit = keys.split(".");
  105895. if (keySplit.length === 0)
  105896. return;
  105897. var lastKey = keySplit.pop();
  105898. if (!lastKey)
  105899. return;
  105900. var curObj = object;
  105901. keySplit.forEach(function (key) {
  105902. curObj[key] = curObj[key] || {};
  105903. curObj = curObj[key];
  105904. });
  105905. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  105906. return;
  105907. curObj[lastKey] = value;
  105908. }
  105909. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbXBhdGliaWxpdHkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9jb25maWd1cmF0aW9uQ29tcGF0aWJpbGl0eS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLGlEQUEwRTtBQUMxRTs7Ozs7R0FLRztBQUNILDJDQUFrRCxhQUFrQztJQUVoRixJQUFJLGFBQWEsQ0FBQyxNQUFNLEVBQUU7UUFDdEIsK0NBQStDO1FBQy9DLElBQUksYUFBYSxDQUFDLE1BQU0sQ0FBQyxRQUFRLEtBQUssU0FBUyxFQUFFO1lBQzdDLGNBQWMsQ0FBQyxhQUFhLEVBQUUsNkNBQTZDLEVBQUUsYUFBYSxDQUFDLE1BQU0sQ0FBQyxRQUFRLENBQUMsQ0FBQztTQUMvRztRQUVELCtDQUErQztRQUMvQyxJQUFJLGFBQWEsQ0FBQyxNQUFNLENBQUMsUUFBUSxLQUFLLFNBQVMsRUFBRTtZQUM3QyxjQUFjLENBQUMsYUFBYSxFQUFFLDZDQUE2QyxFQUFFLGFBQWEsQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLENBQUM7U0FDL0c7S0FDSjtJQUVELElBQUksYUFBYSxDQUFDLEtBQUssRUFBRTtRQUNyQixNQUFNO1FBQ04sSU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SxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  105910. /***/ }),
  105911. /* 11 */
  105912. /***/ (function(module, exports, __webpack_require__) {
  105913. "use strict";
  105914. Object.defineProperty(exports, "__esModule", { value: true });
  105915. function getConfigurationKey(key, configObject) {
  105916. var splits = key.split('.');
  105917. if (splits.length === 0 || !configObject)
  105918. return;
  105919. else if (splits.length === 1) {
  105920. if (configObject[key] !== undefined) {
  105921. return configObject[key];
  105922. }
  105923. }
  105924. else {
  105925. var firstKey = splits.shift();
  105926. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  105927. }
  105928. }
  105929. exports.getConfigurationKey = getConfigurationKey;
  105930. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  105931. /***/ }),
  105932. /* 12 */
  105933. /***/ (function(module, exports, __webpack_require__) {
  105934. "use strict";
  105935. Object.defineProperty(exports, "__esModule", { value: true });
  105936. var babylonjs_1 = __webpack_require__(0);
  105937. var babylonjs_loaders_1 = __webpack_require__(13);
  105938. var viewerModel_1 = __webpack_require__(5);
  105939. var _1 = __webpack_require__(53);
  105940. /**
  105941. * An instance of the class is in charge of loading the model correctly.
  105942. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  105943. *
  105944. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  105945. */
  105946. var ModelLoader = /** @class */ (function () {
  105947. /**
  105948. * Create a new Model loader
  105949. * @param _viewer the viewer using this model loader
  105950. */
  105951. function ModelLoader(_observablesManager, _configurationContainer) {
  105952. this._observablesManager = _observablesManager;
  105953. this._configurationContainer = _configurationContainer;
  105954. this._disposed = false;
  105955. this._loaders = [];
  105956. this._loadId = 0;
  105957. this._plugins = [];
  105958. }
  105959. Object.defineProperty(ModelLoader.prototype, "baseUrl", {
  105960. get: function () {
  105961. return this._baseUrl;
  105962. },
  105963. enumerable: true,
  105964. configurable: true
  105965. });
  105966. /**
  105967. * Adds a new plugin to the loader process.
  105968. *
  105969. * @param plugin the plugin name or the plugin itself
  105970. */
  105971. ModelLoader.prototype.addPlugin = function (plugin) {
  105972. var actualPlugin = {};
  105973. if (typeof plugin === 'string') {
  105974. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  105975. if (loadedPlugin) {
  105976. actualPlugin = loadedPlugin;
  105977. }
  105978. }
  105979. else {
  105980. actualPlugin = plugin;
  105981. }
  105982. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  105983. this._plugins.push(actualPlugin);
  105984. }
  105985. };
  105986. /**
  105987. * Load a model using predefined configuration
  105988. * @param modelConfiguration the modelConfiguration to use to load the model
  105989. */
  105990. ModelLoader.prototype.load = function (modelConfiguration) {
  105991. var _this = this;
  105992. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration, this._configurationContainer);
  105993. model.loadId = this._loadId++;
  105994. var filename;
  105995. if (modelConfiguration.file) {
  105996. this._baseUrl = "file:";
  105997. filename = modelConfiguration.file;
  105998. }
  105999. else if (modelConfiguration.url) {
  106000. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  106001. this._baseUrl = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  106002. }
  106003. if (!filename || !this._baseUrl) {
  106004. model.state = viewerModel_1.ModelState.ERROR;
  106005. babylonjs_1.Tools.Error("No URL provided");
  106006. return model;
  106007. }
  106008. var plugin = modelConfiguration.loader;
  106009. var scene = model.rootMesh.getScene();
  106010. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, this._baseUrl, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  106011. meshes.forEach(function (mesh) {
  106012. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  106013. model.addMesh(mesh);
  106014. });
  106015. model.particleSystems = particleSystems;
  106016. model.skeletons = skeletons;
  106017. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  106018. var animationGroup = animationGroups_1[_i];
  106019. model.addAnimationGroup(animationGroup);
  106020. }
  106021. _this._checkAndRun("onLoaded", model);
  106022. scene.executeWhenReady(function () {
  106023. model.onLoadedObservable.notifyObservers(model);
  106024. });
  106025. }, function (progressEvent) {
  106026. _this._checkAndRun("onProgress", progressEvent);
  106027. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  106028. }, function (scene, m, exception) {
  106029. model.state = viewerModel_1.ModelState.ERROR;
  106030. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  106031. _this._checkAndRun("onError", m, exception);
  106032. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  106033. }, plugin);
  106034. if (model.loader.name === "gltf") {
  106035. var gltfLoader_1 = model.loader;
  106036. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  106037. gltfLoader_1.compileMaterials = true;
  106038. if (!modelConfiguration.file) {
  106039. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  106040. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  106041. };
  106042. }
  106043. // if ground is set to "mirror":
  106044. if (this._configurationContainer
  106045. && this._configurationContainer.configuration
  106046. && this._configurationContainer.configuration.ground
  106047. && typeof this._configurationContainer.configuration.ground === 'object'
  106048. && this._configurationContainer.configuration.ground.mirror) {
  106049. gltfLoader_1.useClipPlane = true;
  106050. }
  106051. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  106052. gltfLoader_1[functionName].add(function (payload) {
  106053. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  106054. });
  106055. });
  106056. gltfLoader_1.onParsedObservable.add(function (data) {
  106057. if (data && data.json && data.json['asset']) {
  106058. model.loadInfo = data.json['asset'];
  106059. }
  106060. });
  106061. gltfLoader_1.onCompleteObservable.add(function () {
  106062. model.loaderDone = true;
  106063. });
  106064. }
  106065. else {
  106066. model.loaderDone = true;
  106067. }
  106068. this._checkAndRun("onInit", model.loader, model);
  106069. this._loaders.push(model.loader);
  106070. return model;
  106071. };
  106072. ModelLoader.prototype.cancelLoad = function (model) {
  106073. var loader = model.loader || this._loaders[model.loadId];
  106074. // ATM only available in the GLTF Loader
  106075. if (loader && loader.name === "gltf") {
  106076. var gltfLoader = loader;
  106077. gltfLoader.dispose();
  106078. model.state = viewerModel_1.ModelState.CANCELED;
  106079. }
  106080. else {
  106081. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  106082. }
  106083. };
  106084. /**
  106085. * dispose the model loader.
  106086. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  106087. */
  106088. ModelLoader.prototype.dispose = function () {
  106089. this._loaders.forEach(function (loader) {
  106090. if (loader.name === "gltf") {
  106091. loader.dispose();
  106092. }
  106093. });
  106094. this._loaders.length = 0;
  106095. this._disposed = true;
  106096. };
  106097. ModelLoader.prototype._checkAndRun = function (functionName) {
  106098. var _this = this;
  106099. var payload = [];
  106100. for (var _i = 1; _i < arguments.length; _i++) {
  106101. payload[_i - 1] = arguments[_i];
  106102. }
  106103. if (this._disposed)
  106104. return;
  106105. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  106106. try {
  106107. plugin[functionName].apply(_this, payload);
  106108. }
  106109. catch (e) { }
  106110. });
  106111. };
  106112. return ModelLoader;
  106113. }());
  106114. exports.ModelLoader = ModelLoader;
  106115. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxMb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbG9hZGVyL21vZGVsTG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQWtHO0FBQ2xHLHVEQUFpRjtBQUtqRixvREFBK0Q7QUFDL0QsK0J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z0JBQ1AsTUFBTyxDQUFDLE9BQU8sRUFBRSxDQUFDO2FBQ3RDO1FBQ0wsQ0FBQyxDQUFDLENBQUM7UUFDSCxJQUFJLENBQUMsUUFBUSxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUM7UUFDekIsSUFBSSxDQUFDLFNBQVMsR0FBRyxJQUFJLENBQUM7SUFDMUIsQ0FBQztJQUVPLGtDQUFZLEdBQXBCLFVBQXFCLFlBQW9CO1FBQXpDLGlCQU9DO1FBUDBDLGlCQUFzQjthQUF0QixVQUFzQixFQUF0QixxQkFBc0IsRUFBdEIsSUFBc0I7WUFBdEIsZ0NBQXNCOztRQUM3RCxJQUFJLElBQUksQ0FBQyxTQUFTO1lBQUUsT0FBTztRQUMzQixJQUFJLENBQUMsUUFBUSxDQUFDLE1BQU0sQ0FBQyxVQUFBLENBQUMsSUFBSSxPQUFBLENBQUMsQ0FBQyxZQUFZLENBQUMsRUFBZixDQUFlLENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxNQUFNO1lBQ3JELElBQUk7Z0JBQ0EsTUFBTSxDQUFDLFlBQVksQ0FBQyxDQUFDLEtBQUssQ0FBQyxLQUFJLEVBQUUsT0FBTyxDQUFDLENBQUM7YUFDN0M7WUFBQyxPQUFPLENBQUMsRUFBRSxHQUFHO1FBQ25CLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQztJQUNMLGtCQUFDO0FBQUQsQ0FBQyxBQXBMRCxJQW9MQztBQXBMWSxrQ0FBVyJ9
  106116. /***/ }),
  106117. /* 13 */
  106118. /***/ (function(module, exports, __webpack_require__) {
  106119. (function universalModuleDefinition(root, factory) {
  106120. var amdDependencies = [];
  106121. var BABYLON = root.BABYLON || this.BABYLON;
  106122. if(true) {
  106123. BABYLON = BABYLON || __webpack_require__(0);
  106124. module.exports = factory(BABYLON);
  106125. } else if(typeof define === 'function' && define.amd) {
  106126. amdDependencies.push("babylonjs");
  106127. define("babylonjs-loaders", amdDependencies, factory);
  106128. } else if(typeof exports === 'object') {
  106129. BABYLON = BABYLON || require("babylonjs");
  106130. exports["babylonjs-loaders"] = factory(BABYLON);
  106131. } else {
  106132. root["BABYLON"] = factory(BABYLON);
  106133. }
  106134. })(this, function(BABYLON) {
  106135. BABYLON = BABYLON || this.BABYLON;
  106136. 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};
  106137. 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)}}();
  106138. var BABYLON;
  106139. (function (BABYLON) {
  106140. var STLFileLoader = /** @class */ (function () {
  106141. function STLFileLoader() {
  106142. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  106143. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  106144. 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;
  106145. 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;
  106146. this.name = "stl";
  106147. // force data to come in as an ArrayBuffer
  106148. // we'll convert to string if it looks like it's an ASCII .stl
  106149. this.extensions = {
  106150. ".stl": { isBinary: true },
  106151. };
  106152. }
  106153. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  106154. var matches;
  106155. if (typeof data !== "string") {
  106156. if (this.isBinary(data)) {
  106157. // binary .stl
  106158. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  106159. this.parseBinary(babylonMesh, data);
  106160. if (meshes) {
  106161. meshes.push(babylonMesh);
  106162. }
  106163. return true;
  106164. }
  106165. // ASCII .stl
  106166. // convert to string
  106167. var array_buffer = new Uint8Array(data);
  106168. var str = '';
  106169. for (var i = 0; i < data.byteLength; i++) {
  106170. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  106171. }
  106172. data = str;
  106173. }
  106174. //if arrived here, data is a string, containing the STLA data.
  106175. while (matches = this.solidPattern.exec(data)) {
  106176. var meshName = matches[1];
  106177. var meshNameFromEnd = matches[3];
  106178. if (meshName != meshNameFromEnd) {
  106179. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  106180. return false;
  106181. }
  106182. // check meshesNames
  106183. if (meshesNames && meshName) {
  106184. if (meshesNames instanceof Array) {
  106185. if (!meshesNames.indexOf(meshName)) {
  106186. continue;
  106187. }
  106188. }
  106189. else {
  106190. if (meshName !== meshesNames) {
  106191. continue;
  106192. }
  106193. }
  106194. }
  106195. // stl mesh name can be empty as well
  106196. meshName = meshName || "stlmesh";
  106197. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  106198. this.parseASCII(babylonMesh, matches[2]);
  106199. if (meshes) {
  106200. meshes.push(babylonMesh);
  106201. }
  106202. }
  106203. return true;
  106204. };
  106205. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  106206. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  106207. if (result) {
  106208. scene.createDefaultCameraOrLight();
  106209. }
  106210. return result;
  106211. };
  106212. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  106213. var container = new BABYLON.AssetContainer(scene);
  106214. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  106215. container.removeAllFromScene();
  106216. return container;
  106217. };
  106218. STLFileLoader.prototype.isBinary = function (data) {
  106219. // check if file size is correct for binary stl
  106220. var faceSize, nFaces, reader;
  106221. reader = new DataView(data);
  106222. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  106223. nFaces = reader.getUint32(80, true);
  106224. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  106225. return true;
  106226. }
  106227. // check characters higher than ASCII to confirm binary
  106228. var fileLength = reader.byteLength;
  106229. for (var index = 0; index < fileLength; index++) {
  106230. if (reader.getUint8(index) > 127) {
  106231. return true;
  106232. }
  106233. }
  106234. return false;
  106235. };
  106236. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  106237. var reader = new DataView(data);
  106238. var faces = reader.getUint32(80, true);
  106239. var dataOffset = 84;
  106240. var faceLength = 12 * 4 + 2;
  106241. var offset = 0;
  106242. var positions = new Float32Array(faces * 3 * 3);
  106243. var normals = new Float32Array(faces * 3 * 3);
  106244. var indices = new Uint32Array(faces * 3);
  106245. var indicesCount = 0;
  106246. for (var face = 0; face < faces; face++) {
  106247. var start = dataOffset + face * faceLength;
  106248. var normalX = reader.getFloat32(start, true);
  106249. var normalY = reader.getFloat32(start + 4, true);
  106250. var normalZ = reader.getFloat32(start + 8, true);
  106251. for (var i = 1; i <= 3; i++) {
  106252. var vertexstart = start + i * 12;
  106253. // ordering is intentional to match ascii import
  106254. positions[offset] = reader.getFloat32(vertexstart, true);
  106255. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  106256. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  106257. normals[offset] = normalX;
  106258. normals[offset + 2] = normalY;
  106259. normals[offset + 1] = normalZ;
  106260. offset += 3;
  106261. }
  106262. indices[indicesCount] = indicesCount++;
  106263. indices[indicesCount] = indicesCount++;
  106264. indices[indicesCount] = indicesCount++;
  106265. }
  106266. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  106267. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  106268. mesh.setIndices(indices);
  106269. mesh.computeWorldMatrix(true);
  106270. };
  106271. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  106272. var positions = [];
  106273. var normals = [];
  106274. var indices = [];
  106275. var indicesCount = 0;
  106276. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  106277. var matches;
  106278. while (matches = this.facetsPattern.exec(solidData)) {
  106279. var facet = matches[1];
  106280. //one normal per face
  106281. var normalMatches = this.normalPattern.exec(facet);
  106282. this.normalPattern.lastIndex = 0;
  106283. if (!normalMatches) {
  106284. continue;
  106285. }
  106286. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  106287. var vertexMatch;
  106288. while (vertexMatch = this.vertexPattern.exec(facet)) {
  106289. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  106290. normals.push(normal[0], normal[1], normal[2]);
  106291. }
  106292. indices.push(indicesCount++, indicesCount++, indicesCount++);
  106293. this.vertexPattern.lastIndex = 0;
  106294. }
  106295. this.facetsPattern.lastIndex = 0;
  106296. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  106297. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  106298. mesh.setIndices(indices);
  106299. mesh.computeWorldMatrix(true);
  106300. };
  106301. return STLFileLoader;
  106302. }());
  106303. BABYLON.STLFileLoader = STLFileLoader;
  106304. if (BABYLON.SceneLoader) {
  106305. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  106306. }
  106307. })(BABYLON || (BABYLON = {}));
  106308. //# sourceMappingURL=babylon.stlFileLoader.js.map
  106309. var BABYLON;
  106310. (function (BABYLON) {
  106311. /**
  106312. * Class reading and parsing the MTL file bundled with the obj file.
  106313. */
  106314. var MTLFileLoader = /** @class */ (function () {
  106315. function MTLFileLoader() {
  106316. // All material loaded from the mtl will be set here
  106317. this.materials = [];
  106318. }
  106319. /**
  106320. * This function will read the mtl file and create each material described inside
  106321. * This function could be improve by adding :
  106322. * -some component missing (Ni, Tf...)
  106323. * -including the specific options available
  106324. *
  106325. * @param scene
  106326. * @param data
  106327. * @param rootUrl
  106328. */
  106329. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  106330. if (data instanceof ArrayBuffer) {
  106331. return;
  106332. }
  106333. //Split the lines from the file
  106334. var lines = data.split('\n');
  106335. //Space char
  106336. var delimiter_pattern = /\s+/;
  106337. //Array with RGB colors
  106338. var color;
  106339. //New material
  106340. var material = null;
  106341. //Look at each line
  106342. for (var i = 0; i < lines.length; i++) {
  106343. var line = lines[i].trim();
  106344. // Blank line or comment
  106345. if (line.length === 0 || line.charAt(0) === '#') {
  106346. continue;
  106347. }
  106348. //Get the first parameter (keyword)
  106349. var pos = line.indexOf(' ');
  106350. var key = (pos >= 0) ? line.substring(0, pos) : line;
  106351. key = key.toLowerCase();
  106352. //Get the data following the key
  106353. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  106354. //This mtl keyword will create the new material
  106355. if (key === "newmtl") {
  106356. //Check if it is the first material.
  106357. // Materials specifications are described after this keyword.
  106358. if (material) {
  106359. //Add the previous material in the material array.
  106360. this.materials.push(material);
  106361. }
  106362. //Create a new material.
  106363. // value is the name of the material read in the mtl file
  106364. material = new BABYLON.StandardMaterial(value, scene);
  106365. }
  106366. else if (key === "kd" && material) {
  106367. // Diffuse color (color under white light) using RGB values
  106368. //value = "r g b"
  106369. color = value.split(delimiter_pattern, 3).map(parseFloat);
  106370. //color = [r,g,b]
  106371. //Set tghe color into the material
  106372. material.diffuseColor = BABYLON.Color3.FromArray(color);
  106373. }
  106374. else if (key === "ka" && material) {
  106375. // Ambient color (color under shadow) using RGB values
  106376. //value = "r g b"
  106377. color = value.split(delimiter_pattern, 3).map(parseFloat);
  106378. //color = [r,g,b]
  106379. //Set tghe color into the material
  106380. material.ambientColor = BABYLON.Color3.FromArray(color);
  106381. }
  106382. else if (key === "ks" && material) {
  106383. // Specular color (color when light is reflected from shiny surface) using RGB values
  106384. //value = "r g b"
  106385. color = value.split(delimiter_pattern, 3).map(parseFloat);
  106386. //color = [r,g,b]
  106387. //Set the color into the material
  106388. material.specularColor = BABYLON.Color3.FromArray(color);
  106389. }
  106390. else if (key === "ke" && material) {
  106391. // Emissive color using RGB values
  106392. color = value.split(delimiter_pattern, 3).map(parseFloat);
  106393. material.emissiveColor = BABYLON.Color3.FromArray(color);
  106394. }
  106395. else if (key === "ns" && material) {
  106396. //value = "Integer"
  106397. material.specularPower = parseFloat(value);
  106398. }
  106399. else if (key === "d" && material) {
  106400. //d is dissolve for current material. It mean alpha for BABYLON
  106401. material.alpha = parseFloat(value);
  106402. //Texture
  106403. //This part can be improved by adding the possible options of texture
  106404. }
  106405. else if (key === "map_ka" && material) {
  106406. // ambient texture map with a loaded image
  106407. //We must first get the folder of the image
  106408. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106409. }
  106410. else if (key === "map_kd" && material) {
  106411. // Diffuse texture map with a loaded image
  106412. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106413. }
  106414. else if (key === "map_ks" && material) {
  106415. // Specular texture map with a loaded image
  106416. //We must first get the folder of the image
  106417. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106418. }
  106419. else if (key === "map_ns") {
  106420. //Specular
  106421. //Specular highlight component
  106422. //We must first get the folder of the image
  106423. //
  106424. //Not supported by BABYLON
  106425. //
  106426. // continue;
  106427. }
  106428. else if (key === "map_bump" && material) {
  106429. //The bump texture
  106430. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106431. }
  106432. else if (key === "map_d" && material) {
  106433. // The dissolve of the material
  106434. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106435. //Options for illumination
  106436. }
  106437. else if (key === "illum") {
  106438. //Illumination
  106439. if (value === "0") {
  106440. //That mean Kd == Kd
  106441. }
  106442. else if (value === "1") {
  106443. //Color on and Ambient on
  106444. }
  106445. else if (value === "2") {
  106446. //Highlight on
  106447. }
  106448. else if (value === "3") {
  106449. //Reflection on and Ray trace on
  106450. }
  106451. else if (value === "4") {
  106452. //Transparency: Glass on, Reflection: Ray trace on
  106453. }
  106454. else if (value === "5") {
  106455. //Reflection: Fresnel on and Ray trace on
  106456. }
  106457. else if (value === "6") {
  106458. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  106459. }
  106460. else if (value === "7") {
  106461. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  106462. }
  106463. else if (value === "8") {
  106464. //Reflection on and Ray trace off
  106465. }
  106466. else if (value === "9") {
  106467. //Transparency: Glass on, Reflection: Ray trace off
  106468. }
  106469. else if (value === "10") {
  106470. //Casts shadows onto invisible surfaces
  106471. }
  106472. }
  106473. else {
  106474. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  106475. }
  106476. }
  106477. //At the end of the file, add the last material
  106478. if (material) {
  106479. this.materials.push(material);
  106480. }
  106481. };
  106482. /**
  106483. * Gets the texture for the material.
  106484. *
  106485. * If the material is imported from input file,
  106486. * We sanitize the url to ensure it takes the textre from aside the material.
  106487. *
  106488. * @param rootUrl The root url to load from
  106489. * @param value The value stored in the mtl
  106490. * @return The Texture
  106491. */
  106492. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  106493. if (!value) {
  106494. return null;
  106495. }
  106496. var url = rootUrl;
  106497. // Load from input file.
  106498. if (rootUrl === "file:") {
  106499. var lastDelimiter = value.lastIndexOf("\\");
  106500. if (lastDelimiter === -1) {
  106501. lastDelimiter = value.lastIndexOf("/");
  106502. }
  106503. if (lastDelimiter > -1) {
  106504. url += value.substr(lastDelimiter + 1);
  106505. }
  106506. else {
  106507. url += value;
  106508. }
  106509. }
  106510. // Not from input file.
  106511. else {
  106512. url += value;
  106513. }
  106514. return new BABYLON.Texture(url, scene);
  106515. };
  106516. return MTLFileLoader;
  106517. }());
  106518. BABYLON.MTLFileLoader = MTLFileLoader;
  106519. var OBJFileLoader = /** @class */ (function () {
  106520. function OBJFileLoader() {
  106521. this.name = "obj";
  106522. this.extensions = ".obj";
  106523. this.obj = /^o/;
  106524. this.group = /^g/;
  106525. this.mtllib = /^mtllib /;
  106526. this.usemtl = /^usemtl /;
  106527. this.smooth = /^s /;
  106528. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106529. // vn float float float
  106530. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106531. // vt float float
  106532. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106533. // f vertex vertex vertex ...
  106534. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  106535. // f vertex/uvs vertex/uvs vertex/uvs ...
  106536. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  106537. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  106538. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  106539. // f vertex//normal vertex//normal vertex//normal ...
  106540. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  106541. }
  106542. /**
  106543. * Calls synchronously the MTL file attached to this obj.
  106544. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  106545. * Without this function materials are not displayed in the first frame (but displayed after).
  106546. * In consequence it is impossible to get material information in your HTML file
  106547. *
  106548. * @param url The URL of the MTL file
  106549. * @param rootUrl
  106550. * @param onSuccess Callback function to be called when the MTL file is loaded
  106551. * @private
  106552. */
  106553. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  106554. //The complete path to the mtl file
  106555. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  106556. // Loads through the babylon tools to allow fileInput search.
  106557. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  106558. };
  106559. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106560. //get the meshes from OBJ file
  106561. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  106562. return {
  106563. meshes: meshes,
  106564. particleSystems: [],
  106565. skeletons: [],
  106566. animationGroups: []
  106567. };
  106568. });
  106569. };
  106570. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106571. //Get the 3D model
  106572. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  106573. // return void
  106574. });
  106575. };
  106576. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  106577. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  106578. var container = new BABYLON.AssetContainer(scene);
  106579. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  106580. container.removeAllFromScene();
  106581. return container;
  106582. });
  106583. };
  106584. /**
  106585. * Read the OBJ file and create an Array of meshes.
  106586. * Each mesh contains all information given by the OBJ and the MTL file.
  106587. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  106588. *
  106589. * @param meshesNames
  106590. * @param scene BABYLON.Scene The scene where are displayed the data
  106591. * @param data String The content of the obj file
  106592. * @param rootUrl String The path to the folder
  106593. * @returns Array<AbstractMesh>
  106594. * @private
  106595. */
  106596. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  106597. var _this = this;
  106598. var positions = []; //values for the positions of vertices
  106599. var normals = []; //Values for the normals
  106600. var uvs = []; //Values for the textures
  106601. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  106602. var handledMesh; //The current mesh of meshes array
  106603. var indicesForBabylon = []; //The list of indices for VertexData
  106604. var wrappedPositionForBabylon = []; //The list of position in vectors
  106605. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  106606. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  106607. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  106608. var curPositionInIndices = 0;
  106609. var hasMeshes = false; //Meshes are defined in the file
  106610. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  106611. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  106612. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  106613. var triangles = []; //Indices from new triangles coming from polygons
  106614. var materialNameFromObj = ""; //The name of the current material
  106615. var fileToLoad = ""; //The name of the mtlFile to load
  106616. var materialsFromMTLFile = new MTLFileLoader();
  106617. var objMeshName = ""; //The name of the current obj mesh
  106618. var increment = 1; //Id for meshes created by the multimaterial
  106619. var isFirstMaterial = true;
  106620. /**
  106621. * Search for obj in the given array.
  106622. * This function is called to check if a couple of data already exists in an array.
  106623. *
  106624. * If found, returns the index of the founded tuple index. Returns -1 if not found
  106625. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  106626. * @param obj Array<number>
  106627. * @returns {boolean}
  106628. */
  106629. var isInArray = function (arr, obj) {
  106630. if (!arr[obj[0]])
  106631. arr[obj[0]] = { normals: [], idx: [] };
  106632. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106633. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  106634. };
  106635. var isInArrayUV = function (arr, obj) {
  106636. if (!arr[obj[0]])
  106637. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  106638. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106639. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  106640. return arr[obj[0]].idx[idx];
  106641. }
  106642. return -1;
  106643. };
  106644. /**
  106645. * This function set the data for each triangle.
  106646. * Data are position, normals and uvs
  106647. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  106648. * If the tuple already exist, add only their indice
  106649. *
  106650. * @param indicePositionFromObj Integer The index in positions array
  106651. * @param indiceUvsFromObj Integer The index in uvs array
  106652. * @param indiceNormalFromObj Integer The index in normals array
  106653. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  106654. * @param textureVectorFromOBJ Vector3 The value of uvs
  106655. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  106656. */
  106657. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  106658. //Check if this tuple already exists in the list of tuples
  106659. var _index;
  106660. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  106661. _index = isInArrayUV(tuplePosNorm, [
  106662. indicePositionFromObj,
  106663. indiceNormalFromObj,
  106664. indiceUvsFromObj
  106665. ]);
  106666. }
  106667. else {
  106668. _index = isInArray(tuplePosNorm, [
  106669. indicePositionFromObj,
  106670. indiceNormalFromObj
  106671. ]);
  106672. }
  106673. //If it not exists
  106674. if (_index == -1) {
  106675. //Add an new indice.
  106676. //The array of indices is only an array with his length equal to the number of triangles - 1.
  106677. //We add vertices data in this order
  106678. indicesForBabylon.push(wrappedPositionForBabylon.length);
  106679. //Push the position of vertice for Babylon
  106680. //Each element is a BABYLON.Vector3(x,y,z)
  106681. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  106682. //Push the uvs for Babylon
  106683. //Each element is a BABYLON.Vector3(u,v)
  106684. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  106685. //Push the normals for Babylon
  106686. //Each element is a BABYLON.Vector3(x,y,z)
  106687. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  106688. //Add the tuple in the comparison list
  106689. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  106690. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  106691. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  106692. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  106693. }
  106694. else {
  106695. //The tuple already exists
  106696. //Add the index of the already existing tuple
  106697. //At this index we can get the value of position, normal and uvs of vertex
  106698. indicesForBabylon.push(_index);
  106699. }
  106700. };
  106701. /**
  106702. * Transform BABYLON.Vector() object onto 3 digits in an array
  106703. */
  106704. var unwrapData = function () {
  106705. //Every array has the same length
  106706. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  106707. //Push the x, y, z values of each element in the unwrapped array
  106708. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  106709. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  106710. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  106711. }
  106712. // Reset arrays for the next new meshes
  106713. wrappedPositionForBabylon = [];
  106714. wrappedNormalsForBabylon = [];
  106715. wrappedUvsForBabylon = [];
  106716. tuplePosNorm = [];
  106717. curPositionInIndices = 0;
  106718. };
  106719. /**
  106720. * Create triangles from polygons by recursion
  106721. * The best to understand how it works is to draw it in the same time you get the recursion.
  106722. * It is important to notice that a triangle is a polygon
  106723. * We get 4 patterns of face defined in OBJ File :
  106724. * facePattern1 = ["1","2","3","4","5","6"]
  106725. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  106726. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  106727. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  106728. * Each pattern is divided by the same method
  106729. * @param face Array[String] The indices of elements
  106730. * @param v Integer The variable to increment
  106731. */
  106732. var getTriangles = function (face, v) {
  106733. //Work for each element of the array
  106734. if (v + 1 < face.length) {
  106735. //Add on the triangle variable the indexes to obtain triangles
  106736. triangles.push(face[0], face[v], face[v + 1]);
  106737. //Incrementation for recursion
  106738. v += 1;
  106739. //Recursion
  106740. getTriangles(face, v);
  106741. }
  106742. //Result obtained after 2 iterations:
  106743. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  106744. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  106745. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  106746. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  106747. };
  106748. /**
  106749. * Create triangles and push the data for each polygon for the pattern 1
  106750. * In this pattern we get vertice positions
  106751. * @param face
  106752. * @param v
  106753. */
  106754. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  106755. //Get the indices of triangles for each polygon
  106756. getTriangles(face, v);
  106757. //For each element in the triangles array.
  106758. //This var could contains 1 to an infinity of triangles
  106759. for (var k = 0; k < triangles.length; k++) {
  106760. // Set position indice
  106761. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  106762. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  106763. positions[indicePositionFromObj], //Get the vectors data
  106764. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  106765. );
  106766. }
  106767. //Reset variable for the next line
  106768. triangles = [];
  106769. };
  106770. /**
  106771. * Create triangles and push the data for each polygon for the pattern 2
  106772. * In this pattern we get vertice positions and uvsu
  106773. * @param face
  106774. * @param v
  106775. */
  106776. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  106777. //Get the indices of triangles for each polygon
  106778. getTriangles(face, v);
  106779. for (var k = 0; k < triangles.length; k++) {
  106780. //triangle[k] = "1/1"
  106781. //Split the data for getting position and uv
  106782. var point = triangles[k].split("/"); // ["1", "1"]
  106783. //Set position indice
  106784. var indicePositionFromObj = parseInt(point[0]) - 1;
  106785. //Set uv indice
  106786. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106787. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  106788. positions[indicePositionFromObj], //Get the values for each element
  106789. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  106790. );
  106791. }
  106792. //Reset variable for the next line
  106793. triangles = [];
  106794. };
  106795. /**
  106796. * Create triangles and push the data for each polygon for the pattern 3
  106797. * In this pattern we get vertice positions, uvs and normals
  106798. * @param face
  106799. * @param v
  106800. */
  106801. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  106802. //Get the indices of triangles for each polygon
  106803. getTriangles(face, v);
  106804. for (var k = 0; k < triangles.length; k++) {
  106805. //triangle[k] = "1/1/1"
  106806. //Split the data for getting position, uv, and normals
  106807. var point = triangles[k].split("/"); // ["1", "1", "1"]
  106808. // Set position indice
  106809. var indicePositionFromObj = parseInt(point[0]) - 1;
  106810. // Set uv indice
  106811. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106812. // Set normal indice
  106813. var indiceNormalFromObj = parseInt(point[2]) - 1;
  106814. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  106815. );
  106816. }
  106817. //Reset variable for the next line
  106818. triangles = [];
  106819. };
  106820. /**
  106821. * Create triangles and push the data for each polygon for the pattern 4
  106822. * In this pattern we get vertice positions and normals
  106823. * @param face
  106824. * @param v
  106825. */
  106826. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  106827. getTriangles(face, v);
  106828. for (var k = 0; k < triangles.length; k++) {
  106829. //triangle[k] = "1//1"
  106830. //Split the data for getting position and normals
  106831. var point = triangles[k].split("//"); // ["1", "1"]
  106832. // We check indices, and normals
  106833. var indicePositionFromObj = parseInt(point[0]) - 1;
  106834. var indiceNormalFromObj = parseInt(point[1]) - 1;
  106835. setData(indicePositionFromObj, 1, //Default value for uv
  106836. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  106837. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  106838. }
  106839. //Reset variable for the next line
  106840. triangles = [];
  106841. };
  106842. var addPreviousObjMesh = function () {
  106843. //Check if it is not the first mesh. Otherwise we don't have data.
  106844. if (meshesFromObj.length > 0) {
  106845. //Get the previous mesh for applying the data about the faces
  106846. //=> in obj file, faces definition append after the name of the mesh
  106847. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106848. //Set the data into Array for the mesh
  106849. unwrapData();
  106850. // Reverse tab. Otherwise face are displayed in the wrong sens
  106851. indicesForBabylon.reverse();
  106852. //Set the information for the mesh
  106853. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  106854. handledMesh.indices = indicesForBabylon.slice();
  106855. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  106856. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  106857. handledMesh.uvs = unwrappedUVForBabylon.slice();
  106858. //Reset the array for the next mesh
  106859. indicesForBabylon = [];
  106860. unwrappedPositionsForBabylon = [];
  106861. unwrappedNormalsForBabylon = [];
  106862. unwrappedUVForBabylon = [];
  106863. }
  106864. };
  106865. //Main function
  106866. //Split the file into lines
  106867. var lines = data.split('\n');
  106868. //Look at each line
  106869. for (var i = 0; i < lines.length; i++) {
  106870. var line = lines[i].trim();
  106871. var result;
  106872. //Comment or newLine
  106873. if (line.length === 0 || line.charAt(0) === '#') {
  106874. continue;
  106875. //Get information about one position possible for the vertices
  106876. }
  106877. else if ((result = this.vertexPattern.exec(line)) !== null) {
  106878. //Create a Vector3 with the position x, y, z
  106879. //Value of result:
  106880. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106881. //Add the Vector in the list of positions
  106882. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106883. }
  106884. else if ((result = this.normalPattern.exec(line)) !== null) {
  106885. //Create a Vector3 with the normals x, y, z
  106886. //Value of result
  106887. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106888. //Add the Vector in the list of normals
  106889. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106890. }
  106891. else if ((result = this.uvPattern.exec(line)) !== null) {
  106892. //Create a Vector2 with the normals u, v
  106893. //Value of result
  106894. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  106895. //Add the Vector in the list of uvs
  106896. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  106897. //Identify patterns of faces
  106898. //Face could be defined in different type of pattern
  106899. }
  106900. else if ((result = this.facePattern3.exec(line)) !== null) {
  106901. //Value of result:
  106902. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  106903. //Set the data for this face
  106904. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  106905. 1);
  106906. }
  106907. else if ((result = this.facePattern4.exec(line)) !== null) {
  106908. //Value of result:
  106909. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  106910. //Set the data for this face
  106911. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  106912. 1);
  106913. }
  106914. else if ((result = this.facePattern2.exec(line)) !== null) {
  106915. //Value of result:
  106916. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  106917. //Set the data for this face
  106918. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  106919. 1);
  106920. }
  106921. else if ((result = this.facePattern1.exec(line)) !== null) {
  106922. //Value of result
  106923. //["f 1 2 3", "1 2 3"...]
  106924. //Set the data for this face
  106925. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  106926. 1);
  106927. //Define a mesh or an object
  106928. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  106929. }
  106930. else if (this.group.test(line) || this.obj.test(line)) {
  106931. //Create a new mesh corresponding to the name of the group.
  106932. //Definition of the mesh
  106933. var objMesh =
  106934. //Set the name of the current obj mesh
  106935. {
  106936. name: line.substring(2).trim(),
  106937. indices: undefined,
  106938. positions: undefined,
  106939. normals: undefined,
  106940. uvs: undefined,
  106941. materialName: ""
  106942. };
  106943. addPreviousObjMesh();
  106944. //Push the last mesh created with only the name
  106945. meshesFromObj.push(objMesh);
  106946. //Set this variable to indicate that now meshesFromObj has objects defined inside
  106947. hasMeshes = true;
  106948. isFirstMaterial = true;
  106949. increment = 1;
  106950. //Keyword for applying a material
  106951. }
  106952. else if (this.usemtl.test(line)) {
  106953. //Get the name of the material
  106954. materialNameFromObj = line.substring(7).trim();
  106955. //If this new material is in the same mesh
  106956. if (!isFirstMaterial) {
  106957. //Set the data for the previous mesh
  106958. addPreviousObjMesh();
  106959. //Create a new mesh
  106960. var objMesh =
  106961. //Set the name of the current obj mesh
  106962. {
  106963. name: objMeshName + "_mm" + increment.toString(),
  106964. indices: undefined,
  106965. positions: undefined,
  106966. normals: undefined,
  106967. uvs: undefined,
  106968. materialName: materialNameFromObj
  106969. };
  106970. increment++;
  106971. //If meshes are already defined
  106972. meshesFromObj.push(objMesh);
  106973. }
  106974. //Set the material name if the previous line define a mesh
  106975. if (hasMeshes && isFirstMaterial) {
  106976. //Set the material name to the previous mesh (1 material per mesh)
  106977. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  106978. isFirstMaterial = false;
  106979. }
  106980. //Keyword for loading the mtl file
  106981. }
  106982. else if (this.mtllib.test(line)) {
  106983. //Get the name of mtl file
  106984. fileToLoad = line.substring(7).trim();
  106985. //Apply smoothing
  106986. }
  106987. else if (this.smooth.test(line)) {
  106988. // smooth shading => apply smoothing
  106989. //Toda y I don't know it work with babylon and with obj.
  106990. //With the obj file an integer is set
  106991. }
  106992. else {
  106993. //If there is another possibility
  106994. console.log("Unhandled expression at line : " + line);
  106995. }
  106996. }
  106997. //At the end of the file, add the last mesh into the meshesFromObj array
  106998. if (hasMeshes) {
  106999. //Set the data for the last mesh
  107000. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  107001. //Reverse indices for displaying faces in the good sens
  107002. indicesForBabylon.reverse();
  107003. //Get the good array
  107004. unwrapData();
  107005. //Set array
  107006. handledMesh.indices = indicesForBabylon;
  107007. handledMesh.positions = unwrappedPositionsForBabylon;
  107008. handledMesh.normals = unwrappedNormalsForBabylon;
  107009. handledMesh.uvs = unwrappedUVForBabylon;
  107010. }
  107011. //If any o or g keyword found, create a mesj with a random id
  107012. if (!hasMeshes) {
  107013. // reverse tab of indices
  107014. indicesForBabylon.reverse();
  107015. //Get positions normals uvs
  107016. unwrapData();
  107017. //Set data for one mesh
  107018. meshesFromObj.push({
  107019. name: BABYLON.Geometry.RandomId(),
  107020. indices: indicesForBabylon,
  107021. positions: unwrappedPositionsForBabylon,
  107022. normals: unwrappedNormalsForBabylon,
  107023. uvs: unwrappedUVForBabylon,
  107024. materialName: materialNameFromObj
  107025. });
  107026. }
  107027. //Create a BABYLON.Mesh list
  107028. var babylonMeshesArray = []; //The mesh for babylon
  107029. var materialToUse = new Array();
  107030. //Set data for each mesh
  107031. for (var j = 0; j < meshesFromObj.length; j++) {
  107032. //check meshesNames (stlFileLoader)
  107033. if (meshesNames && meshesFromObj[j].name) {
  107034. if (meshesNames instanceof Array) {
  107035. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  107036. continue;
  107037. }
  107038. }
  107039. else {
  107040. if (meshesFromObj[j].name !== meshesNames) {
  107041. continue;
  107042. }
  107043. }
  107044. }
  107045. //Get the current mesh
  107046. //Set the data with VertexBuffer for each mesh
  107047. handledMesh = meshesFromObj[j];
  107048. //Create a BABYLON.Mesh with the name of the obj mesh
  107049. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  107050. //Push the name of the material to an array
  107051. //This is indispensable for the importMesh function
  107052. materialToUse.push(meshesFromObj[j].materialName);
  107053. var vertexData = new BABYLON.VertexData(); //The container for the values
  107054. //Set the data for the babylonMesh
  107055. vertexData.positions = handledMesh.positions;
  107056. vertexData.normals = handledMesh.normals;
  107057. vertexData.uvs = handledMesh.uvs;
  107058. vertexData.indices = handledMesh.indices;
  107059. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  107060. vertexData.applyToMesh(babylonMesh);
  107061. if (OBJFileLoader.INVERT_Y) {
  107062. babylonMesh.scaling.y *= -1;
  107063. }
  107064. //Push the mesh into an array
  107065. babylonMeshesArray.push(babylonMesh);
  107066. }
  107067. var mtlPromises = [];
  107068. //load the materials
  107069. //Check if we have a file to load
  107070. if (fileToLoad !== "") {
  107071. //Load the file synchronously
  107072. mtlPromises.push(new Promise(function (resolve, reject) {
  107073. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  107074. try {
  107075. //Create materials thanks MTLLoader function
  107076. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  107077. //Look at each material loaded in the mtl file
  107078. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  107079. //Three variables to get all meshes with the same material
  107080. var startIndex = 0;
  107081. var _indices = [];
  107082. var _index;
  107083. //The material from MTL file is used in the meshes loaded
  107084. //Push the indice in an array
  107085. //Check if the material is not used for another mesh
  107086. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  107087. _indices.push(_index);
  107088. startIndex = _index + 1;
  107089. }
  107090. //If the material is not used dispose it
  107091. if (_index == -1 && _indices.length == 0) {
  107092. //If the material is not needed, remove it
  107093. materialsFromMTLFile.materials[n].dispose();
  107094. }
  107095. else {
  107096. for (var o = 0; o < _indices.length; o++) {
  107097. //Apply the material to the BABYLON.Mesh for each mesh with the material
  107098. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  107099. }
  107100. }
  107101. }
  107102. resolve();
  107103. }
  107104. catch (e) {
  107105. reject(e);
  107106. }
  107107. });
  107108. }));
  107109. }
  107110. //Return an array with all BABYLON.Mesh
  107111. return Promise.all(mtlPromises).then(function () {
  107112. return babylonMeshesArray;
  107113. });
  107114. };
  107115. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  107116. OBJFileLoader.INVERT_Y = false;
  107117. return OBJFileLoader;
  107118. }());
  107119. BABYLON.OBJFileLoader = OBJFileLoader;
  107120. if (BABYLON.SceneLoader) {
  107121. //Add this loader into the register plugin
  107122. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  107123. }
  107124. })(BABYLON || (BABYLON = {}));
  107125. //# sourceMappingURL=babylon.objFileLoader.js.map
  107126. var BABYLON;
  107127. (function (BABYLON) {
  107128. /**
  107129. * Mode that determines the coordinate system to use.
  107130. */
  107131. var GLTFLoaderCoordinateSystemMode;
  107132. (function (GLTFLoaderCoordinateSystemMode) {
  107133. /**
  107134. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  107135. */
  107136. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  107137. /**
  107138. * Sets the useRightHandedSystem flag on the scene.
  107139. */
  107140. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  107141. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  107142. /**
  107143. * Mode that determines what animations will start.
  107144. */
  107145. var GLTFLoaderAnimationStartMode;
  107146. (function (GLTFLoaderAnimationStartMode) {
  107147. /**
  107148. * No animation will start.
  107149. */
  107150. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  107151. /**
  107152. * The first animation will start.
  107153. */
  107154. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  107155. /**
  107156. * All animations will start.
  107157. */
  107158. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  107159. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  107160. /**
  107161. * Loader state.
  107162. */
  107163. var GLTFLoaderState;
  107164. (function (GLTFLoaderState) {
  107165. /**
  107166. * The asset is loading.
  107167. */
  107168. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  107169. /**
  107170. * The asset is ready for rendering.
  107171. */
  107172. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  107173. /**
  107174. * The asset is completely loaded.
  107175. */
  107176. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  107177. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  107178. /**
  107179. * File loader for loading glTF files into a scene.
  107180. */
  107181. var GLTFFileLoader = /** @class */ (function () {
  107182. function GLTFFileLoader() {
  107183. // #region Common options
  107184. /**
  107185. * Raised when the asset has been parsed
  107186. */
  107187. this.onParsedObservable = new BABYLON.Observable();
  107188. // #endregion
  107189. // #region V2 options
  107190. /**
  107191. * The coordinate system mode. Defaults to AUTO.
  107192. */
  107193. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  107194. /**
  107195. * The animation start mode. Defaults to FIRST.
  107196. */
  107197. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  107198. /**
  107199. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  107200. */
  107201. this.compileMaterials = false;
  107202. /**
  107203. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  107204. */
  107205. this.useClipPlane = false;
  107206. /**
  107207. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  107208. */
  107209. this.compileShadowGenerators = false;
  107210. /**
  107211. * Defines if the Alpha blended materials are only applied as coverage.
  107212. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  107213. * If true, no extra effects are applied to transparent pixels.
  107214. */
  107215. this.transparencyAsCoverage = false;
  107216. /** @hidden */
  107217. this._normalizeAnimationGroupsToBeginAtZero = true;
  107218. /**
  107219. * Function called before loading a url referenced by the asset.
  107220. */
  107221. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  107222. /**
  107223. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  107224. */
  107225. this.onMeshLoadedObservable = new BABYLON.Observable();
  107226. /**
  107227. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  107228. */
  107229. this.onTextureLoadedObservable = new BABYLON.Observable();
  107230. /**
  107231. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  107232. */
  107233. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107234. /**
  107235. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  107236. */
  107237. this.onCameraLoadedObservable = new BABYLON.Observable();
  107238. /**
  107239. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  107240. * For assets with LODs, raised when all of the LODs are complete.
  107241. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  107242. */
  107243. this.onCompleteObservable = new BABYLON.Observable();
  107244. /**
  107245. * Observable raised after the loader is disposed.
  107246. */
  107247. this.onDisposeObservable = new BABYLON.Observable();
  107248. /**
  107249. * Observable raised after a loader extension is created.
  107250. * Set additional options for a loader extension in this event.
  107251. */
  107252. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107253. // #endregion
  107254. this._loader = null;
  107255. /**
  107256. * Name of the loader ("gltf")
  107257. */
  107258. this.name = "gltf";
  107259. /**
  107260. * Supported file extensions of the loader (.gltf, .glb)
  107261. */
  107262. this.extensions = {
  107263. ".gltf": { isBinary: false },
  107264. ".glb": { isBinary: true }
  107265. };
  107266. this._logIndentLevel = 0;
  107267. this._loggingEnabled = false;
  107268. /** @hidden */
  107269. this._log = this._logDisabled;
  107270. this._capturePerformanceCounters = false;
  107271. /** @hidden */
  107272. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  107273. /** @hidden */
  107274. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  107275. }
  107276. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  107277. /**
  107278. * Raised when the asset has been parsed
  107279. */
  107280. set: function (callback) {
  107281. if (this._onParsedObserver) {
  107282. this.onParsedObservable.remove(this._onParsedObserver);
  107283. }
  107284. this._onParsedObserver = this.onParsedObservable.add(callback);
  107285. },
  107286. enumerable: true,
  107287. configurable: true
  107288. });
  107289. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  107290. /**
  107291. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  107292. */
  107293. set: function (callback) {
  107294. if (this._onMeshLoadedObserver) {
  107295. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  107296. }
  107297. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  107298. },
  107299. enumerable: true,
  107300. configurable: true
  107301. });
  107302. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  107303. /**
  107304. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  107305. */
  107306. set: function (callback) {
  107307. if (this._onTextureLoadedObserver) {
  107308. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  107309. }
  107310. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  107311. },
  107312. enumerable: true,
  107313. configurable: true
  107314. });
  107315. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  107316. /**
  107317. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  107318. */
  107319. set: function (callback) {
  107320. if (this._onMaterialLoadedObserver) {
  107321. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  107322. }
  107323. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  107324. },
  107325. enumerable: true,
  107326. configurable: true
  107327. });
  107328. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  107329. /**
  107330. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  107331. */
  107332. set: function (callback) {
  107333. if (this._onCameraLoadedObserver) {
  107334. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  107335. }
  107336. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  107337. },
  107338. enumerable: true,
  107339. configurable: true
  107340. });
  107341. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  107342. /**
  107343. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  107344. */
  107345. set: function (callback) {
  107346. if (this._onCompleteObserver) {
  107347. this.onCompleteObservable.remove(this._onCompleteObserver);
  107348. }
  107349. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  107350. },
  107351. enumerable: true,
  107352. configurable: true
  107353. });
  107354. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  107355. /**
  107356. * Callback raised after the loader is disposed.
  107357. */
  107358. set: function (callback) {
  107359. if (this._onDisposeObserver) {
  107360. this.onDisposeObservable.remove(this._onDisposeObserver);
  107361. }
  107362. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  107363. },
  107364. enumerable: true,
  107365. configurable: true
  107366. });
  107367. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  107368. /**
  107369. * Callback raised after a loader extension is created.
  107370. */
  107371. set: function (callback) {
  107372. if (this._onExtensionLoadedObserver) {
  107373. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  107374. }
  107375. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  107376. },
  107377. enumerable: true,
  107378. configurable: true
  107379. });
  107380. /**
  107381. * Returns a promise that resolves when the asset is completely loaded.
  107382. * @returns a promise that resolves when the asset is completely loaded.
  107383. */
  107384. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  107385. var _this = this;
  107386. return new Promise(function (resolve) {
  107387. _this.onCompleteObservable.addOnce(function () {
  107388. resolve();
  107389. });
  107390. });
  107391. };
  107392. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  107393. /**
  107394. * The loader state or null if the loader is not active.
  107395. */
  107396. get: function () {
  107397. return this._loader ? this._loader.state : null;
  107398. },
  107399. enumerable: true,
  107400. configurable: true
  107401. });
  107402. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  107403. /**
  107404. * Defines if the loader logging is enabled.
  107405. */
  107406. get: function () {
  107407. return this._loggingEnabled;
  107408. },
  107409. set: function (value) {
  107410. if (this._loggingEnabled === value) {
  107411. return;
  107412. }
  107413. this._loggingEnabled = value;
  107414. if (this._loggingEnabled) {
  107415. this._log = this._logEnabled;
  107416. }
  107417. else {
  107418. this._log = this._logDisabled;
  107419. }
  107420. },
  107421. enumerable: true,
  107422. configurable: true
  107423. });
  107424. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  107425. /**
  107426. * Defines if the loader should capture performance counters.
  107427. */
  107428. get: function () {
  107429. return this._capturePerformanceCounters;
  107430. },
  107431. set: function (value) {
  107432. if (this._capturePerformanceCounters === value) {
  107433. return;
  107434. }
  107435. this._capturePerformanceCounters = value;
  107436. if (this._capturePerformanceCounters) {
  107437. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  107438. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  107439. }
  107440. else {
  107441. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  107442. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  107443. }
  107444. },
  107445. enumerable: true,
  107446. configurable: true
  107447. });
  107448. /**
  107449. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  107450. */
  107451. GLTFFileLoader.prototype.dispose = function () {
  107452. if (this._loader) {
  107453. this._loader.dispose();
  107454. this._loader = null;
  107455. }
  107456. this._clear();
  107457. this.onDisposeObservable.notifyObservers(undefined);
  107458. this.onDisposeObservable.clear();
  107459. };
  107460. /** @hidden */
  107461. GLTFFileLoader.prototype._clear = function () {
  107462. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  107463. this.onMeshLoadedObservable.clear();
  107464. this.onTextureLoadedObservable.clear();
  107465. this.onMaterialLoadedObservable.clear();
  107466. this.onCameraLoadedObservable.clear();
  107467. this.onCompleteObservable.clear();
  107468. this.onExtensionLoadedObservable.clear();
  107469. };
  107470. /**
  107471. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  107472. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  107473. * @param scene the scene the meshes should be added to
  107474. * @param data the glTF data to load
  107475. * @param rootUrl root url to load from
  107476. * @param onProgress event that fires when loading progress has occured
  107477. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  107478. */
  107479. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107480. var _this = this;
  107481. return Promise.resolve().then(function () {
  107482. var loaderData = _this._parse(data);
  107483. _this._loader = _this._getLoader(loaderData);
  107484. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  107485. });
  107486. };
  107487. /**
  107488. * Imports all objects from the loaded glTF data and adds them to the scene
  107489. * @param scene the scene the objects should be added to
  107490. * @param data the glTF data to load
  107491. * @param rootUrl root url to load from
  107492. * @param onProgress event that fires when loading progress has occured
  107493. * @returns a promise which completes when objects have been loaded to the scene
  107494. */
  107495. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107496. var _this = this;
  107497. return Promise.resolve().then(function () {
  107498. var loaderData = _this._parse(data);
  107499. _this._loader = _this._getLoader(loaderData);
  107500. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  107501. });
  107502. };
  107503. /**
  107504. * Load into an asset container.
  107505. * @param scene The scene to load into
  107506. * @param data The data to import
  107507. * @param rootUrl The root url for scene and resources
  107508. * @param onProgress The callback when the load progresses
  107509. * @returns The loaded asset container
  107510. */
  107511. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  107512. var _this = this;
  107513. return Promise.resolve().then(function () {
  107514. var loaderData = _this._parse(data);
  107515. _this._loader = _this._getLoader(loaderData);
  107516. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  107517. var container = new BABYLON.AssetContainer(scene);
  107518. Array.prototype.push.apply(container.meshes, result.meshes);
  107519. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  107520. Array.prototype.push.apply(container.skeletons, result.skeletons);
  107521. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  107522. container.removeAllFromScene();
  107523. return container;
  107524. });
  107525. });
  107526. };
  107527. /**
  107528. * If the data string can be loaded directly.
  107529. * @param data string contianing the file data
  107530. * @returns if the data can be loaded directly
  107531. */
  107532. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  107533. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  107534. };
  107535. /**
  107536. * Instantiates a glTF file loader plugin.
  107537. * @returns the created plugin
  107538. */
  107539. GLTFFileLoader.prototype.createPlugin = function () {
  107540. return new GLTFFileLoader();
  107541. };
  107542. GLTFFileLoader.prototype._parse = function (data) {
  107543. this._startPerformanceCounter("Parse");
  107544. var parsedData;
  107545. if (data instanceof ArrayBuffer) {
  107546. this._log("Parsing binary");
  107547. parsedData = this._parseBinary(data);
  107548. }
  107549. else {
  107550. this._log("Parsing JSON");
  107551. this._log("JSON length: " + data.length);
  107552. parsedData = {
  107553. json: JSON.parse(data),
  107554. bin: null
  107555. };
  107556. }
  107557. this.onParsedObservable.notifyObservers(parsedData);
  107558. this.onParsedObservable.clear();
  107559. this._endPerformanceCounter("Parse");
  107560. return parsedData;
  107561. };
  107562. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  107563. var asset = loaderData.json.asset || {};
  107564. this._log("Asset version: " + asset.version);
  107565. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  107566. asset.generator && this._log("Asset generator: " + asset.generator);
  107567. var version = GLTFFileLoader._parseVersion(asset.version);
  107568. if (!version) {
  107569. throw new Error("Invalid version: " + asset.version);
  107570. }
  107571. if (asset.minVersion !== undefined) {
  107572. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  107573. if (!minVersion) {
  107574. throw new Error("Invalid minimum version: " + asset.minVersion);
  107575. }
  107576. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  107577. throw new Error("Incompatible minimum version: " + asset.minVersion);
  107578. }
  107579. }
  107580. var createLoaders = {
  107581. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  107582. 2: GLTFFileLoader._CreateGLTFLoaderV2
  107583. };
  107584. var createLoader = createLoaders[version.major];
  107585. if (!createLoader) {
  107586. throw new Error("Unsupported version: " + asset.version);
  107587. }
  107588. return createLoader(this);
  107589. };
  107590. GLTFFileLoader.prototype._parseBinary = function (data) {
  107591. var Binary = {
  107592. Magic: 0x46546C67
  107593. };
  107594. this._log("Binary length: " + data.byteLength);
  107595. var binaryReader = new BinaryReader(data);
  107596. var magic = binaryReader.readUint32();
  107597. if (magic !== Binary.Magic) {
  107598. throw new Error("Unexpected magic: " + magic);
  107599. }
  107600. var version = binaryReader.readUint32();
  107601. if (this.loggingEnabled) {
  107602. this._log("Binary version: " + version);
  107603. }
  107604. switch (version) {
  107605. case 1: return this._parseV1(binaryReader);
  107606. case 2: return this._parseV2(binaryReader);
  107607. }
  107608. throw new Error("Unsupported version: " + version);
  107609. };
  107610. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  107611. var ContentFormat = {
  107612. JSON: 0
  107613. };
  107614. var length = binaryReader.readUint32();
  107615. if (length != binaryReader.getLength()) {
  107616. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  107617. }
  107618. var contentLength = binaryReader.readUint32();
  107619. var contentFormat = binaryReader.readUint32();
  107620. var content;
  107621. switch (contentFormat) {
  107622. case ContentFormat.JSON: {
  107623. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  107624. break;
  107625. }
  107626. default: {
  107627. throw new Error("Unexpected content format: " + contentFormat);
  107628. }
  107629. }
  107630. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  107631. var body = binaryReader.readUint8Array(bytesRemaining);
  107632. return {
  107633. json: content,
  107634. bin: body
  107635. };
  107636. };
  107637. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  107638. var ChunkFormat = {
  107639. JSON: 0x4E4F534A,
  107640. BIN: 0x004E4942
  107641. };
  107642. var length = binaryReader.readUint32();
  107643. if (length !== binaryReader.getLength()) {
  107644. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  107645. }
  107646. // JSON chunk
  107647. var chunkLength = binaryReader.readUint32();
  107648. var chunkFormat = binaryReader.readUint32();
  107649. if (chunkFormat !== ChunkFormat.JSON) {
  107650. throw new Error("First chunk format is not JSON");
  107651. }
  107652. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  107653. // Look for BIN chunk
  107654. var bin = null;
  107655. while (binaryReader.getPosition() < binaryReader.getLength()) {
  107656. var chunkLength_1 = binaryReader.readUint32();
  107657. var chunkFormat_1 = binaryReader.readUint32();
  107658. switch (chunkFormat_1) {
  107659. case ChunkFormat.JSON: {
  107660. throw new Error("Unexpected JSON chunk");
  107661. }
  107662. case ChunkFormat.BIN: {
  107663. bin = binaryReader.readUint8Array(chunkLength_1);
  107664. break;
  107665. }
  107666. default: {
  107667. // ignore unrecognized chunkFormat
  107668. binaryReader.skipBytes(chunkLength_1);
  107669. break;
  107670. }
  107671. }
  107672. }
  107673. return {
  107674. json: json,
  107675. bin: bin
  107676. };
  107677. };
  107678. GLTFFileLoader._parseVersion = function (version) {
  107679. if (version === "1.0" || version === "1.0.1") {
  107680. return {
  107681. major: 1,
  107682. minor: 0
  107683. };
  107684. }
  107685. var match = (version + "").match(/^(\d+)\.(\d+)/);
  107686. if (!match) {
  107687. return null;
  107688. }
  107689. return {
  107690. major: parseInt(match[1]),
  107691. minor: parseInt(match[2])
  107692. };
  107693. };
  107694. GLTFFileLoader._compareVersion = function (a, b) {
  107695. if (a.major > b.major)
  107696. return 1;
  107697. if (a.major < b.major)
  107698. return -1;
  107699. if (a.minor > b.minor)
  107700. return 1;
  107701. if (a.minor < b.minor)
  107702. return -1;
  107703. return 0;
  107704. };
  107705. GLTFFileLoader._decodeBufferToText = function (buffer) {
  107706. var result = "";
  107707. var length = buffer.byteLength;
  107708. for (var i = 0; i < length; i++) {
  107709. result += String.fromCharCode(buffer[i]);
  107710. }
  107711. return result;
  107712. };
  107713. /** @hidden */
  107714. GLTFFileLoader.prototype._logOpen = function (message) {
  107715. this._log(message);
  107716. this._logIndentLevel++;
  107717. };
  107718. /** @hidden */
  107719. GLTFFileLoader.prototype._logClose = function () {
  107720. --this._logIndentLevel;
  107721. };
  107722. GLTFFileLoader.prototype._logEnabled = function (message) {
  107723. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  107724. BABYLON.Tools.Log("" + spaces + message);
  107725. };
  107726. GLTFFileLoader.prototype._logDisabled = function (message) {
  107727. };
  107728. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  107729. BABYLON.Tools.StartPerformanceCounter(counterName);
  107730. };
  107731. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  107732. };
  107733. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  107734. BABYLON.Tools.EndPerformanceCounter(counterName);
  107735. };
  107736. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  107737. };
  107738. // #endregion
  107739. // #region V1 options
  107740. /**
  107741. * 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.
  107742. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  107743. * Defaults to true.
  107744. * @hidden
  107745. */
  107746. GLTFFileLoader.IncrementalLoading = true;
  107747. /**
  107748. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  107749. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  107750. * @hidden
  107751. */
  107752. GLTFFileLoader.HomogeneousCoordinates = false;
  107753. GLTFFileLoader._logSpaces = " ";
  107754. return GLTFFileLoader;
  107755. }());
  107756. BABYLON.GLTFFileLoader = GLTFFileLoader;
  107757. var BinaryReader = /** @class */ (function () {
  107758. function BinaryReader(arrayBuffer) {
  107759. this._arrayBuffer = arrayBuffer;
  107760. this._dataView = new DataView(arrayBuffer);
  107761. this._byteOffset = 0;
  107762. }
  107763. BinaryReader.prototype.getPosition = function () {
  107764. return this._byteOffset;
  107765. };
  107766. BinaryReader.prototype.getLength = function () {
  107767. return this._arrayBuffer.byteLength;
  107768. };
  107769. BinaryReader.prototype.readUint32 = function () {
  107770. var value = this._dataView.getUint32(this._byteOffset, true);
  107771. this._byteOffset += 4;
  107772. return value;
  107773. };
  107774. BinaryReader.prototype.readUint8Array = function (length) {
  107775. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  107776. this._byteOffset += length;
  107777. return value;
  107778. };
  107779. BinaryReader.prototype.skipBytes = function (length) {
  107780. this._byteOffset += length;
  107781. };
  107782. return BinaryReader;
  107783. }());
  107784. if (BABYLON.SceneLoader) {
  107785. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  107786. }
  107787. })(BABYLON || (BABYLON = {}));
  107788. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  107789. var BABYLON;
  107790. (function (BABYLON) {
  107791. var GLTF1;
  107792. (function (GLTF1) {
  107793. /**
  107794. * Enums
  107795. */
  107796. var EComponentType;
  107797. (function (EComponentType) {
  107798. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  107799. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107800. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  107801. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107802. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  107803. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  107804. var EShaderType;
  107805. (function (EShaderType) {
  107806. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  107807. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  107808. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  107809. var EParameterType;
  107810. (function (EParameterType) {
  107811. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  107812. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107813. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  107814. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107815. EParameterType[EParameterType["INT"] = 5124] = "INT";
  107816. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  107817. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  107818. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  107819. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  107820. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  107821. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  107822. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  107823. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  107824. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  107825. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  107826. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  107827. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  107828. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  107829. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  107830. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  107831. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  107832. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  107833. var ETextureWrapMode;
  107834. (function (ETextureWrapMode) {
  107835. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  107836. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  107837. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  107838. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  107839. var ETextureFilterType;
  107840. (function (ETextureFilterType) {
  107841. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  107842. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  107843. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  107844. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  107845. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  107846. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  107847. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  107848. var ETextureFormat;
  107849. (function (ETextureFormat) {
  107850. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  107851. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  107852. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  107853. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  107854. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  107855. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  107856. var ECullingType;
  107857. (function (ECullingType) {
  107858. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  107859. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  107860. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  107861. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  107862. var EBlendingFunction;
  107863. (function (EBlendingFunction) {
  107864. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  107865. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  107866. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  107867. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  107868. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  107869. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  107870. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  107871. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  107872. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  107873. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  107874. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  107875. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  107876. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  107877. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  107878. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  107879. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  107880. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107881. })(BABYLON || (BABYLON = {}));
  107882. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  107883. var BABYLON;
  107884. (function (BABYLON) {
  107885. var GLTF1;
  107886. (function (GLTF1) {
  107887. /**
  107888. * Tokenizer. Used for shaders compatibility
  107889. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  107890. */
  107891. var ETokenType;
  107892. (function (ETokenType) {
  107893. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  107894. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  107895. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  107896. })(ETokenType || (ETokenType = {}));
  107897. var Tokenizer = /** @class */ (function () {
  107898. function Tokenizer(toParse) {
  107899. this._pos = 0;
  107900. this.currentToken = ETokenType.UNKNOWN;
  107901. this.currentIdentifier = "";
  107902. this.currentString = "";
  107903. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  107904. this._toParse = toParse;
  107905. this._maxPos = toParse.length;
  107906. }
  107907. Tokenizer.prototype.getNextToken = function () {
  107908. if (this.isEnd())
  107909. return ETokenType.END_OF_INPUT;
  107910. this.currentString = this.read();
  107911. this.currentToken = ETokenType.UNKNOWN;
  107912. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  107913. this.currentToken = ETokenType.IDENTIFIER;
  107914. this.currentIdentifier = this.currentString;
  107915. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  107916. this.currentIdentifier += this.currentString;
  107917. this.forward();
  107918. }
  107919. }
  107920. return this.currentToken;
  107921. };
  107922. Tokenizer.prototype.peek = function () {
  107923. return this._toParse[this._pos];
  107924. };
  107925. Tokenizer.prototype.read = function () {
  107926. return this._toParse[this._pos++];
  107927. };
  107928. Tokenizer.prototype.forward = function () {
  107929. this._pos++;
  107930. };
  107931. Tokenizer.prototype.isEnd = function () {
  107932. return this._pos >= this._maxPos;
  107933. };
  107934. return Tokenizer;
  107935. }());
  107936. /**
  107937. * Values
  107938. */
  107939. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  107940. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  107941. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  107942. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  107943. /**
  107944. * Parse
  107945. */
  107946. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  107947. for (var buf in parsedBuffers) {
  107948. var parsedBuffer = parsedBuffers[buf];
  107949. gltfRuntime.buffers[buf] = parsedBuffer;
  107950. gltfRuntime.buffersCount++;
  107951. }
  107952. };
  107953. var parseShaders = function (parsedShaders, gltfRuntime) {
  107954. for (var sha in parsedShaders) {
  107955. var parsedShader = parsedShaders[sha];
  107956. gltfRuntime.shaders[sha] = parsedShader;
  107957. gltfRuntime.shaderscount++;
  107958. }
  107959. };
  107960. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  107961. for (var object in parsedObjects) {
  107962. var parsedObject = parsedObjects[object];
  107963. gltfRuntime[runtimeProperty][object] = parsedObject;
  107964. }
  107965. };
  107966. /**
  107967. * Utils
  107968. */
  107969. var normalizeUVs = function (buffer) {
  107970. if (!buffer) {
  107971. return;
  107972. }
  107973. for (var i = 0; i < buffer.length / 2; i++) {
  107974. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  107975. }
  107976. };
  107977. var getAttribute = function (attributeParameter) {
  107978. if (attributeParameter.semantic === "NORMAL") {
  107979. return "normal";
  107980. }
  107981. else if (attributeParameter.semantic === "POSITION") {
  107982. return "position";
  107983. }
  107984. else if (attributeParameter.semantic === "JOINT") {
  107985. return "matricesIndices";
  107986. }
  107987. else if (attributeParameter.semantic === "WEIGHT") {
  107988. return "matricesWeights";
  107989. }
  107990. else if (attributeParameter.semantic === "COLOR") {
  107991. return "color";
  107992. }
  107993. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  107994. var channel = Number(attributeParameter.semantic.split("_")[1]);
  107995. return "uv" + (channel === 0 ? "" : channel + 1);
  107996. }
  107997. return null;
  107998. };
  107999. /**
  108000. * Loads and creates animations
  108001. */
  108002. var loadAnimations = function (gltfRuntime) {
  108003. for (var anim in gltfRuntime.animations) {
  108004. var animation = gltfRuntime.animations[anim];
  108005. if (!animation.channels || !animation.samplers) {
  108006. continue;
  108007. }
  108008. var lastAnimation = null;
  108009. for (var i = 0; i < animation.channels.length; i++) {
  108010. // Get parameters and load buffers
  108011. var channel = animation.channels[i];
  108012. var sampler = animation.samplers[channel.sampler];
  108013. if (!sampler) {
  108014. continue;
  108015. }
  108016. var inputData = null;
  108017. var outputData = null;
  108018. if (animation.parameters) {
  108019. inputData = animation.parameters[sampler.input];
  108020. outputData = animation.parameters[sampler.output];
  108021. }
  108022. else {
  108023. inputData = sampler.input;
  108024. outputData = sampler.output;
  108025. }
  108026. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  108027. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  108028. var targetID = channel.target.id;
  108029. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  108030. if (targetNode === null) {
  108031. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  108032. }
  108033. if (targetNode === null) {
  108034. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  108035. continue;
  108036. }
  108037. var isBone = targetNode instanceof BABYLON.Bone;
  108038. // Get target path (position, rotation or scaling)
  108039. var targetPath = channel.target.path;
  108040. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  108041. if (targetPathIndex !== -1) {
  108042. targetPath = babylonAnimationPaths[targetPathIndex];
  108043. }
  108044. // Determine animation type
  108045. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  108046. if (!isBone) {
  108047. if (targetPath === "rotationQuaternion") {
  108048. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  108049. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  108050. }
  108051. else {
  108052. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108053. }
  108054. }
  108055. // Create animation and key frames
  108056. var babylonAnimation = null;
  108057. var keys = [];
  108058. var arrayOffset = 0;
  108059. var modifyKey = false;
  108060. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  108061. babylonAnimation = lastAnimation;
  108062. modifyKey = true;
  108063. }
  108064. if (!modifyKey) {
  108065. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  108066. }
  108067. // For each frame
  108068. for (var j = 0; j < bufferInput.length; j++) {
  108069. var value = null;
  108070. if (targetPath === "rotationQuaternion") { // VEC4
  108071. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  108072. arrayOffset += 4;
  108073. }
  108074. else { // Position and scaling are VEC3
  108075. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  108076. arrayOffset += 3;
  108077. }
  108078. if (isBone) {
  108079. var bone = targetNode;
  108080. var translation = BABYLON.Vector3.Zero();
  108081. var rotationQuaternion = new BABYLON.Quaternion();
  108082. var scaling = BABYLON.Vector3.Zero();
  108083. // Warning on decompose
  108084. var mat = bone.getBaseMatrix();
  108085. if (modifyKey && lastAnimation) {
  108086. mat = lastAnimation.getKeys()[j].value;
  108087. }
  108088. mat.decompose(scaling, rotationQuaternion, translation);
  108089. if (targetPath === "position") {
  108090. translation = value;
  108091. }
  108092. else if (targetPath === "rotationQuaternion") {
  108093. rotationQuaternion = value;
  108094. }
  108095. else {
  108096. scaling = value;
  108097. }
  108098. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  108099. }
  108100. if (!modifyKey) {
  108101. keys.push({
  108102. frame: bufferInput[j],
  108103. value: value
  108104. });
  108105. }
  108106. else if (lastAnimation) {
  108107. lastAnimation.getKeys()[j].value = value;
  108108. }
  108109. }
  108110. // Finish
  108111. if (!modifyKey && babylonAnimation) {
  108112. babylonAnimation.setKeys(keys);
  108113. targetNode.animations.push(babylonAnimation);
  108114. }
  108115. lastAnimation = babylonAnimation;
  108116. gltfRuntime.scene.stopAnimation(targetNode);
  108117. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  108118. }
  108119. }
  108120. };
  108121. /**
  108122. * Returns the bones transformation matrix
  108123. */
  108124. var configureBoneTransformation = function (node) {
  108125. var mat = null;
  108126. if (node.translation || node.rotation || node.scale) {
  108127. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  108128. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  108129. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  108130. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  108131. }
  108132. else {
  108133. mat = BABYLON.Matrix.FromArray(node.matrix);
  108134. }
  108135. return mat;
  108136. };
  108137. /**
  108138. * Returns the parent bone
  108139. */
  108140. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  108141. // Try to find
  108142. for (var i = 0; i < newSkeleton.bones.length; i++) {
  108143. if (newSkeleton.bones[i].name === jointName) {
  108144. return newSkeleton.bones[i];
  108145. }
  108146. }
  108147. // Not found, search in gltf nodes
  108148. var nodes = gltfRuntime.nodes;
  108149. for (var nde in nodes) {
  108150. var node = nodes[nde];
  108151. if (!node.jointName) {
  108152. continue;
  108153. }
  108154. var children = node.children;
  108155. for (var i = 0; i < children.length; i++) {
  108156. var child = gltfRuntime.nodes[children[i]];
  108157. if (!child.jointName) {
  108158. continue;
  108159. }
  108160. if (child.jointName === jointName) {
  108161. var mat = configureBoneTransformation(node);
  108162. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  108163. bone.id = nde;
  108164. return bone;
  108165. }
  108166. }
  108167. }
  108168. return null;
  108169. };
  108170. /**
  108171. * Returns the appropriate root node
  108172. */
  108173. var getNodeToRoot = function (nodesToRoot, id) {
  108174. for (var i = 0; i < nodesToRoot.length; i++) {
  108175. var nodeToRoot = nodesToRoot[i];
  108176. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  108177. var child = nodeToRoot.node.children[j];
  108178. if (child === id) {
  108179. return nodeToRoot.bone;
  108180. }
  108181. }
  108182. }
  108183. return null;
  108184. };
  108185. /**
  108186. * Returns the node with the joint name
  108187. */
  108188. var getJointNode = function (gltfRuntime, jointName) {
  108189. var nodes = gltfRuntime.nodes;
  108190. var node = nodes[jointName];
  108191. if (node) {
  108192. return {
  108193. node: node,
  108194. id: jointName
  108195. };
  108196. }
  108197. for (var nde in nodes) {
  108198. node = nodes[nde];
  108199. if (node.jointName === jointName) {
  108200. return {
  108201. node: node,
  108202. id: nde
  108203. };
  108204. }
  108205. }
  108206. return null;
  108207. };
  108208. /**
  108209. * Checks if a nodes is in joints
  108210. */
  108211. var nodeIsInJoints = function (skins, id) {
  108212. for (var i = 0; i < skins.jointNames.length; i++) {
  108213. if (skins.jointNames[i] === id) {
  108214. return true;
  108215. }
  108216. }
  108217. return false;
  108218. };
  108219. /**
  108220. * Fills the nodes to root for bones and builds hierarchy
  108221. */
  108222. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  108223. // Creates nodes for root
  108224. for (var nde in gltfRuntime.nodes) {
  108225. var node = gltfRuntime.nodes[nde];
  108226. var id = nde;
  108227. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  108228. continue;
  108229. }
  108230. // Create node to root bone
  108231. var mat = configureBoneTransformation(node);
  108232. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  108233. bone.id = id;
  108234. nodesToRoot.push({ bone: bone, node: node, id: id });
  108235. }
  108236. // Parenting
  108237. for (var i = 0; i < nodesToRoot.length; i++) {
  108238. var nodeToRoot = nodesToRoot[i];
  108239. var children = nodeToRoot.node.children;
  108240. for (var j = 0; j < children.length; j++) {
  108241. var child = null;
  108242. for (var k = 0; k < nodesToRoot.length; k++) {
  108243. if (nodesToRoot[k].id === children[j]) {
  108244. child = nodesToRoot[k];
  108245. break;
  108246. }
  108247. }
  108248. if (child) {
  108249. child.bone._parent = nodeToRoot.bone;
  108250. nodeToRoot.bone.children.push(child.bone);
  108251. }
  108252. }
  108253. }
  108254. };
  108255. /**
  108256. * Imports a skeleton
  108257. */
  108258. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  108259. if (!newSkeleton) {
  108260. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  108261. }
  108262. if (!skins.babylonSkeleton) {
  108263. return newSkeleton;
  108264. }
  108265. // Find the root bones
  108266. var nodesToRoot = [];
  108267. var nodesToRootToAdd = [];
  108268. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  108269. newSkeleton.bones = [];
  108270. // Joints
  108271. for (var i = 0; i < skins.jointNames.length; i++) {
  108272. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  108273. if (!jointNode) {
  108274. continue;
  108275. }
  108276. var node = jointNode.node;
  108277. if (!node) {
  108278. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  108279. continue;
  108280. }
  108281. var id = jointNode.id;
  108282. // Optimize, if the bone already exists...
  108283. var existingBone = gltfRuntime.scene.getBoneByID(id);
  108284. if (existingBone) {
  108285. newSkeleton.bones.push(existingBone);
  108286. continue;
  108287. }
  108288. // Search for parent bone
  108289. var foundBone = false;
  108290. var parentBone = null;
  108291. for (var j = 0; j < i; j++) {
  108292. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  108293. if (!jointNode_1) {
  108294. continue;
  108295. }
  108296. var joint = jointNode_1.node;
  108297. if (!joint) {
  108298. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  108299. continue;
  108300. }
  108301. var children = joint.children;
  108302. if (!children) {
  108303. continue;
  108304. }
  108305. foundBone = false;
  108306. for (var k = 0; k < children.length; k++) {
  108307. if (children[k] === id) {
  108308. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  108309. foundBone = true;
  108310. break;
  108311. }
  108312. }
  108313. if (foundBone) {
  108314. break;
  108315. }
  108316. }
  108317. // Create bone
  108318. var mat = configureBoneTransformation(node);
  108319. if (!parentBone && nodesToRoot.length > 0) {
  108320. parentBone = getNodeToRoot(nodesToRoot, id);
  108321. if (parentBone) {
  108322. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  108323. nodesToRootToAdd.push(parentBone);
  108324. }
  108325. }
  108326. }
  108327. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  108328. bone.id = id;
  108329. }
  108330. // Polish
  108331. var bones = newSkeleton.bones;
  108332. newSkeleton.bones = [];
  108333. for (var i = 0; i < skins.jointNames.length; i++) {
  108334. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  108335. if (!jointNode) {
  108336. continue;
  108337. }
  108338. for (var j = 0; j < bones.length; j++) {
  108339. if (bones[j].id === jointNode.id) {
  108340. newSkeleton.bones.push(bones[j]);
  108341. break;
  108342. }
  108343. }
  108344. }
  108345. newSkeleton.prepare();
  108346. // Finish
  108347. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  108348. newSkeleton.bones.push(nodesToRootToAdd[i]);
  108349. }
  108350. return newSkeleton;
  108351. };
  108352. /**
  108353. * Imports a mesh and its geometries
  108354. */
  108355. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  108356. if (!newMesh) {
  108357. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  108358. newMesh.id = id;
  108359. }
  108360. if (!node.babylonNode) {
  108361. return newMesh;
  108362. }
  108363. var subMaterials = [];
  108364. var vertexData = null;
  108365. var verticesStarts = new Array();
  108366. var verticesCounts = new Array();
  108367. var indexStarts = new Array();
  108368. var indexCounts = new Array();
  108369. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  108370. var meshID = meshes[meshIndex];
  108371. var mesh = gltfRuntime.meshes[meshID];
  108372. if (!mesh) {
  108373. continue;
  108374. }
  108375. // Positions, normals and UVs
  108376. for (var i = 0; i < mesh.primitives.length; i++) {
  108377. // Temporary vertex data
  108378. var tempVertexData = new BABYLON.VertexData();
  108379. var primitive = mesh.primitives[i];
  108380. if (primitive.mode !== 4) {
  108381. // continue;
  108382. }
  108383. var attributes = primitive.attributes;
  108384. var accessor = null;
  108385. var buffer = null;
  108386. // Set positions, normal and uvs
  108387. for (var semantic in attributes) {
  108388. // Link accessor and buffer view
  108389. accessor = gltfRuntime.accessors[attributes[semantic]];
  108390. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  108391. if (semantic === "NORMAL") {
  108392. tempVertexData.normals = new Float32Array(buffer.length);
  108393. tempVertexData.normals.set(buffer);
  108394. }
  108395. else if (semantic === "POSITION") {
  108396. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  108397. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  108398. for (var j = 0; j < buffer.length; j += 4) {
  108399. tempVertexData.positions[j] = buffer[j];
  108400. tempVertexData.positions[j + 1] = buffer[j + 1];
  108401. tempVertexData.positions[j + 2] = buffer[j + 2];
  108402. }
  108403. }
  108404. else {
  108405. tempVertexData.positions = new Float32Array(buffer.length);
  108406. tempVertexData.positions.set(buffer);
  108407. }
  108408. verticesCounts.push(tempVertexData.positions.length);
  108409. }
  108410. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  108411. var channel = Number(semantic.split("_")[1]);
  108412. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  108413. var uvs = new Float32Array(buffer.length);
  108414. uvs.set(buffer);
  108415. normalizeUVs(uvs);
  108416. tempVertexData.set(uvs, uvKind);
  108417. }
  108418. else if (semantic === "JOINT") {
  108419. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  108420. tempVertexData.matricesIndices.set(buffer);
  108421. }
  108422. else if (semantic === "WEIGHT") {
  108423. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  108424. tempVertexData.matricesWeights.set(buffer);
  108425. }
  108426. else if (semantic === "COLOR") {
  108427. tempVertexData.colors = new Float32Array(buffer.length);
  108428. tempVertexData.colors.set(buffer);
  108429. }
  108430. }
  108431. // Indices
  108432. accessor = gltfRuntime.accessors[primitive.indices];
  108433. if (accessor) {
  108434. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  108435. tempVertexData.indices = new Int32Array(buffer.length);
  108436. tempVertexData.indices.set(buffer);
  108437. indexCounts.push(tempVertexData.indices.length);
  108438. }
  108439. else {
  108440. // Set indices on the fly
  108441. var indices = [];
  108442. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  108443. indices.push(j);
  108444. }
  108445. tempVertexData.indices = new Int32Array(indices);
  108446. indexCounts.push(tempVertexData.indices.length);
  108447. }
  108448. if (!vertexData) {
  108449. vertexData = tempVertexData;
  108450. }
  108451. else {
  108452. vertexData.merge(tempVertexData);
  108453. }
  108454. // Sub material
  108455. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  108456. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  108457. // Update vertices start and index start
  108458. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  108459. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  108460. }
  108461. }
  108462. var material;
  108463. if (subMaterials.length > 1) {
  108464. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  108465. material.subMaterials = subMaterials;
  108466. }
  108467. else {
  108468. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  108469. }
  108470. if (subMaterials.length === 1) {
  108471. material = subMaterials[0];
  108472. }
  108473. if (!newMesh.material) {
  108474. newMesh.material = material;
  108475. }
  108476. // Apply geometry
  108477. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  108478. newMesh.computeWorldMatrix(true);
  108479. // Apply submeshes
  108480. newMesh.subMeshes = [];
  108481. var index = 0;
  108482. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  108483. var meshID = meshes[meshIndex];
  108484. var mesh = gltfRuntime.meshes[meshID];
  108485. if (!mesh) {
  108486. continue;
  108487. }
  108488. for (var i = 0; i < mesh.primitives.length; i++) {
  108489. if (mesh.primitives[i].mode !== 4) {
  108490. //continue;
  108491. }
  108492. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  108493. index++;
  108494. }
  108495. }
  108496. // Finish
  108497. return newMesh;
  108498. };
  108499. /**
  108500. * Configure node transformation from position, rotation and scaling
  108501. */
  108502. var configureNode = function (newNode, position, rotation, scaling) {
  108503. if (newNode.position) {
  108504. newNode.position = position;
  108505. }
  108506. if (newNode.rotationQuaternion || newNode.rotation) {
  108507. newNode.rotationQuaternion = rotation;
  108508. }
  108509. if (newNode.scaling) {
  108510. newNode.scaling = scaling;
  108511. }
  108512. };
  108513. /**
  108514. * Configures node from transformation matrix
  108515. */
  108516. var configureNodeFromMatrix = function (newNode, node, parent) {
  108517. if (node.matrix) {
  108518. var position = new BABYLON.Vector3(0, 0, 0);
  108519. var rotation = new BABYLON.Quaternion();
  108520. var scaling = new BABYLON.Vector3(0, 0, 0);
  108521. var mat = BABYLON.Matrix.FromArray(node.matrix);
  108522. mat.decompose(scaling, rotation, position);
  108523. configureNode(newNode, position, rotation, scaling);
  108524. }
  108525. else if (node.translation && node.rotation && node.scale) {
  108526. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  108527. }
  108528. newNode.computeWorldMatrix(true);
  108529. };
  108530. /**
  108531. * Imports a node
  108532. */
  108533. var importNode = function (gltfRuntime, node, id, parent) {
  108534. var lastNode = null;
  108535. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  108536. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  108537. return null;
  108538. }
  108539. }
  108540. // Meshes
  108541. if (node.skin) {
  108542. if (node.meshes) {
  108543. var skin = gltfRuntime.skins[node.skin];
  108544. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  108545. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  108546. if (newMesh.skeleton === null) {
  108547. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  108548. if (!skin.babylonSkeleton) {
  108549. skin.babylonSkeleton = newMesh.skeleton;
  108550. }
  108551. }
  108552. lastNode = newMesh;
  108553. }
  108554. }
  108555. else if (node.meshes) {
  108556. /**
  108557. * Improve meshes property
  108558. */
  108559. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  108560. lastNode = newMesh;
  108561. }
  108562. // Lights
  108563. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  108564. var light = gltfRuntime.lights[node.light];
  108565. if (light) {
  108566. if (light.type === "ambient") {
  108567. var ambienLight = light[light.type];
  108568. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  108569. hemiLight.name = node.name || "";
  108570. if (ambienLight.color) {
  108571. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  108572. }
  108573. lastNode = hemiLight;
  108574. }
  108575. else if (light.type === "directional") {
  108576. var directionalLight = light[light.type];
  108577. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  108578. dirLight.name = node.name || "";
  108579. if (directionalLight.color) {
  108580. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  108581. }
  108582. lastNode = dirLight;
  108583. }
  108584. else if (light.type === "point") {
  108585. var pointLight = light[light.type];
  108586. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  108587. ptLight.name = node.name || "";
  108588. if (pointLight.color) {
  108589. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  108590. }
  108591. lastNode = ptLight;
  108592. }
  108593. else if (light.type === "spot") {
  108594. var spotLight = light[light.type];
  108595. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  108596. spLight.name = node.name || "";
  108597. if (spotLight.color) {
  108598. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  108599. }
  108600. if (spotLight.fallOfAngle) {
  108601. spLight.angle = spotLight.fallOfAngle;
  108602. }
  108603. if (spotLight.fallOffExponent) {
  108604. spLight.exponent = spotLight.fallOffExponent;
  108605. }
  108606. lastNode = spLight;
  108607. }
  108608. }
  108609. }
  108610. // Cameras
  108611. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  108612. var camera = gltfRuntime.cameras[node.camera];
  108613. if (camera) {
  108614. if (camera.type === "orthographic") {
  108615. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  108616. orthoCamera.name = node.name || "";
  108617. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  108618. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  108619. lastNode = orthoCamera;
  108620. }
  108621. else if (camera.type === "perspective") {
  108622. var perspectiveCamera = camera[camera.type];
  108623. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  108624. persCamera.name = node.name || "";
  108625. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  108626. if (!perspectiveCamera.aspectRatio) {
  108627. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  108628. }
  108629. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  108630. persCamera.maxZ = perspectiveCamera.zfar;
  108631. persCamera.minZ = perspectiveCamera.znear;
  108632. }
  108633. lastNode = persCamera;
  108634. }
  108635. }
  108636. }
  108637. // Empty node
  108638. if (!node.jointName) {
  108639. if (node.babylonNode) {
  108640. return node.babylonNode;
  108641. }
  108642. else if (lastNode === null) {
  108643. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  108644. node.babylonNode = dummy;
  108645. lastNode = dummy;
  108646. }
  108647. }
  108648. if (lastNode !== null) {
  108649. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  108650. configureNodeFromMatrix(lastNode, node, parent);
  108651. }
  108652. else {
  108653. var translation = node.translation || [0, 0, 0];
  108654. var rotation = node.rotation || [0, 0, 0, 1];
  108655. var scale = node.scale || [1, 1, 1];
  108656. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  108657. }
  108658. lastNode.updateCache(true);
  108659. node.babylonNode = lastNode;
  108660. }
  108661. return lastNode;
  108662. };
  108663. /**
  108664. * Traverses nodes and creates them
  108665. */
  108666. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  108667. if (meshIncluded === void 0) { meshIncluded = false; }
  108668. var node = gltfRuntime.nodes[id];
  108669. var newNode = null;
  108670. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  108671. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  108672. meshIncluded = true;
  108673. }
  108674. else {
  108675. meshIncluded = false;
  108676. }
  108677. }
  108678. else {
  108679. meshIncluded = true;
  108680. }
  108681. if (!node.jointName && meshIncluded) {
  108682. newNode = importNode(gltfRuntime, node, id, parent);
  108683. if (newNode !== null) {
  108684. newNode.id = id;
  108685. newNode.parent = parent;
  108686. }
  108687. }
  108688. if (node.children) {
  108689. for (var i = 0; i < node.children.length; i++) {
  108690. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  108691. }
  108692. }
  108693. };
  108694. /**
  108695. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  108696. */
  108697. var postLoad = function (gltfRuntime) {
  108698. // Nodes
  108699. var currentScene = gltfRuntime.currentScene;
  108700. if (currentScene) {
  108701. for (var i = 0; i < currentScene.nodes.length; i++) {
  108702. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108703. }
  108704. }
  108705. else {
  108706. for (var thing in gltfRuntime.scenes) {
  108707. currentScene = gltfRuntime.scenes[thing];
  108708. for (var i = 0; i < currentScene.nodes.length; i++) {
  108709. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108710. }
  108711. }
  108712. }
  108713. // Set animations
  108714. loadAnimations(gltfRuntime);
  108715. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  108716. var skeleton = gltfRuntime.scene.skeletons[i];
  108717. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  108718. }
  108719. };
  108720. /**
  108721. * onBind shaderrs callback to set uniforms and matrices
  108722. */
  108723. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  108724. var materialValues = material.values || technique.parameters;
  108725. for (var unif in unTreatedUniforms) {
  108726. var uniform = unTreatedUniforms[unif];
  108727. var type = uniform.type;
  108728. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  108729. if (uniform.semantic && !uniform.source && !uniform.node) {
  108730. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  108731. }
  108732. else if (uniform.semantic && (uniform.source || uniform.node)) {
  108733. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  108734. if (source === null) {
  108735. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  108736. }
  108737. if (source === null) {
  108738. continue;
  108739. }
  108740. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  108741. }
  108742. }
  108743. else {
  108744. var value = materialValues[technique.uniforms[unif]];
  108745. if (!value) {
  108746. continue;
  108747. }
  108748. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108749. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  108750. if (texture === null || texture === undefined) {
  108751. continue;
  108752. }
  108753. shaderMaterial.getEffect().setTexture(unif, texture);
  108754. }
  108755. else {
  108756. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  108757. }
  108758. }
  108759. }
  108760. onSuccess(shaderMaterial);
  108761. };
  108762. /**
  108763. * Prepare uniforms to send the only one time
  108764. * Loads the appropriate textures
  108765. */
  108766. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  108767. var materialValues = material.values || technique.parameters;
  108768. var techniqueUniforms = technique.uniforms;
  108769. /**
  108770. * Prepare values here (not matrices)
  108771. */
  108772. for (var unif in unTreatedUniforms) {
  108773. var uniform = unTreatedUniforms[unif];
  108774. var type = uniform.type;
  108775. var value = materialValues[techniqueUniforms[unif]];
  108776. if (value === undefined) {
  108777. // In case the value is the same for all materials
  108778. value = uniform.value;
  108779. }
  108780. if (!value) {
  108781. continue;
  108782. }
  108783. var onLoadTexture = function (uniformName) {
  108784. return function (texture) {
  108785. if (uniform.value && uniformName) {
  108786. // Static uniform
  108787. shaderMaterial.setTexture(uniformName, texture);
  108788. delete unTreatedUniforms[uniformName];
  108789. }
  108790. };
  108791. };
  108792. // Texture (sampler2D)
  108793. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108794. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  108795. }
  108796. // Others
  108797. else {
  108798. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  108799. // Static uniform
  108800. delete unTreatedUniforms[unif];
  108801. }
  108802. }
  108803. }
  108804. };
  108805. /**
  108806. * Shader compilation failed
  108807. */
  108808. var onShaderCompileError = function (program, shaderMaterial, onError) {
  108809. return function (effect, error) {
  108810. shaderMaterial.dispose(true);
  108811. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  108812. };
  108813. };
  108814. /**
  108815. * Shader compilation success
  108816. */
  108817. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  108818. return function (_) {
  108819. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  108820. shaderMaterial.onBind = function (mesh) {
  108821. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  108822. };
  108823. };
  108824. };
  108825. /**
  108826. * Returns the appropriate uniform if already handled by babylon
  108827. */
  108828. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  108829. for (var unif in technique.uniforms) {
  108830. var uniform = technique.uniforms[unif];
  108831. var uniformParameter = technique.parameters[uniform];
  108832. if (tokenizer.currentIdentifier === unif) {
  108833. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  108834. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108835. if (transformIndex !== -1) {
  108836. delete unTreatedUniforms[unif];
  108837. return babylonTransforms[transformIndex];
  108838. }
  108839. }
  108840. }
  108841. }
  108842. return tokenizer.currentIdentifier;
  108843. };
  108844. /**
  108845. * All shaders loaded. Create materials one by one
  108846. */
  108847. var importMaterials = function (gltfRuntime) {
  108848. // Create materials
  108849. for (var mat in gltfRuntime.materials) {
  108850. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  108851. }
  108852. };
  108853. /**
  108854. * Implementation of the base glTF spec
  108855. */
  108856. var GLTFLoaderBase = /** @class */ (function () {
  108857. function GLTFLoaderBase() {
  108858. }
  108859. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  108860. var gltfRuntime = {
  108861. extensions: {},
  108862. accessors: {},
  108863. buffers: {},
  108864. bufferViews: {},
  108865. meshes: {},
  108866. lights: {},
  108867. cameras: {},
  108868. nodes: {},
  108869. images: {},
  108870. textures: {},
  108871. shaders: {},
  108872. programs: {},
  108873. samplers: {},
  108874. techniques: {},
  108875. materials: {},
  108876. animations: {},
  108877. skins: {},
  108878. extensionsUsed: [],
  108879. scenes: {},
  108880. buffersCount: 0,
  108881. shaderscount: 0,
  108882. scene: scene,
  108883. rootUrl: rootUrl,
  108884. loadedBufferCount: 0,
  108885. loadedBufferViews: {},
  108886. loadedShaderCount: 0,
  108887. importOnlyMeshes: false,
  108888. dummyNodes: []
  108889. };
  108890. // Parse
  108891. if (parsedData.extensions) {
  108892. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  108893. }
  108894. if (parsedData.extensionsUsed) {
  108895. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  108896. }
  108897. if (parsedData.buffers) {
  108898. parseBuffers(parsedData.buffers, gltfRuntime);
  108899. }
  108900. if (parsedData.bufferViews) {
  108901. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  108902. }
  108903. if (parsedData.accessors) {
  108904. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  108905. }
  108906. if (parsedData.meshes) {
  108907. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  108908. }
  108909. if (parsedData.lights) {
  108910. parseObject(parsedData.lights, "lights", gltfRuntime);
  108911. }
  108912. if (parsedData.cameras) {
  108913. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  108914. }
  108915. if (parsedData.nodes) {
  108916. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  108917. }
  108918. if (parsedData.images) {
  108919. parseObject(parsedData.images, "images", gltfRuntime);
  108920. }
  108921. if (parsedData.textures) {
  108922. parseObject(parsedData.textures, "textures", gltfRuntime);
  108923. }
  108924. if (parsedData.shaders) {
  108925. parseShaders(parsedData.shaders, gltfRuntime);
  108926. }
  108927. if (parsedData.programs) {
  108928. parseObject(parsedData.programs, "programs", gltfRuntime);
  108929. }
  108930. if (parsedData.samplers) {
  108931. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  108932. }
  108933. if (parsedData.techniques) {
  108934. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  108935. }
  108936. if (parsedData.materials) {
  108937. parseObject(parsedData.materials, "materials", gltfRuntime);
  108938. }
  108939. if (parsedData.animations) {
  108940. parseObject(parsedData.animations, "animations", gltfRuntime);
  108941. }
  108942. if (parsedData.skins) {
  108943. parseObject(parsedData.skins, "skins", gltfRuntime);
  108944. }
  108945. if (parsedData.scenes) {
  108946. gltfRuntime.scenes = parsedData.scenes;
  108947. }
  108948. if (parsedData.scene && parsedData.scenes) {
  108949. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  108950. }
  108951. return gltfRuntime;
  108952. };
  108953. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108954. var buffer = gltfRuntime.buffers[id];
  108955. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  108956. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  108957. }
  108958. else {
  108959. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  108960. if (request) {
  108961. onError(request.status + " " + request.statusText);
  108962. }
  108963. });
  108964. }
  108965. };
  108966. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108967. var texture = gltfRuntime.textures[id];
  108968. if (!texture || !texture.source) {
  108969. onError("");
  108970. return;
  108971. }
  108972. if (texture.babylonTexture) {
  108973. onSuccess(null);
  108974. return;
  108975. }
  108976. var source = gltfRuntime.images[texture.source];
  108977. if (BABYLON.Tools.IsBase64(source.uri)) {
  108978. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  108979. }
  108980. else {
  108981. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  108982. if (request) {
  108983. onError(request.status + " " + request.statusText);
  108984. }
  108985. });
  108986. }
  108987. };
  108988. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108989. var texture = gltfRuntime.textures[id];
  108990. if (texture.babylonTexture) {
  108991. onSuccess(texture.babylonTexture);
  108992. return;
  108993. }
  108994. var sampler = gltfRuntime.samplers[texture.sampler];
  108995. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  108996. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  108997. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  108998. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  108999. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  109000. var blob = new Blob([buffer]);
  109001. var blobURL = URL.createObjectURL(blob);
  109002. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  109003. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  109004. if (sampler.wrapS !== undefined) {
  109005. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  109006. }
  109007. if (sampler.wrapT !== undefined) {
  109008. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  109009. }
  109010. newTexture.name = id;
  109011. texture.babylonTexture = newTexture;
  109012. onSuccess(newTexture);
  109013. };
  109014. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109015. var shader = gltfRuntime.shaders[id];
  109016. if (BABYLON.Tools.IsBase64(shader.uri)) {
  109017. var shaderString = atob(shader.uri.split(",")[1]);
  109018. if (onSuccess) {
  109019. onSuccess(shaderString);
  109020. }
  109021. }
  109022. else {
  109023. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  109024. if (request && onError) {
  109025. onError(request.status + " " + request.statusText);
  109026. }
  109027. });
  109028. }
  109029. };
  109030. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109031. var material = gltfRuntime.materials[id];
  109032. if (!material.technique) {
  109033. if (onError) {
  109034. onError("No technique found.");
  109035. }
  109036. return;
  109037. }
  109038. var technique = gltfRuntime.techniques[material.technique];
  109039. if (!technique) {
  109040. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  109041. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  109042. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109043. onSuccess(defaultMaterial);
  109044. return;
  109045. }
  109046. var program = gltfRuntime.programs[technique.program];
  109047. var states = technique.states;
  109048. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  109049. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  109050. var newVertexShader = "";
  109051. var newPixelShader = "";
  109052. var vertexTokenizer = new Tokenizer(vertexShader);
  109053. var pixelTokenizer = new Tokenizer(pixelShader);
  109054. var unTreatedUniforms = {};
  109055. var uniforms = [];
  109056. var attributes = [];
  109057. var samplers = [];
  109058. // Fill uniform, sampler2D and attributes
  109059. for (var unif in technique.uniforms) {
  109060. var uniform = technique.uniforms[unif];
  109061. var uniformParameter = technique.parameters[uniform];
  109062. unTreatedUniforms[unif] = uniformParameter;
  109063. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  109064. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  109065. if (transformIndex !== -1) {
  109066. uniforms.push(babylonTransforms[transformIndex]);
  109067. delete unTreatedUniforms[unif];
  109068. }
  109069. else {
  109070. uniforms.push(unif);
  109071. }
  109072. }
  109073. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  109074. samplers.push(unif);
  109075. }
  109076. else {
  109077. uniforms.push(unif);
  109078. }
  109079. }
  109080. for (var attr in technique.attributes) {
  109081. var attribute = technique.attributes[attr];
  109082. var attributeParameter = technique.parameters[attribute];
  109083. if (attributeParameter.semantic) {
  109084. attributes.push(getAttribute(attributeParameter));
  109085. }
  109086. }
  109087. // Configure vertex shader
  109088. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  109089. var tokenType = vertexTokenizer.currentToken;
  109090. if (tokenType !== ETokenType.IDENTIFIER) {
  109091. newVertexShader += vertexTokenizer.currentString;
  109092. continue;
  109093. }
  109094. var foundAttribute = false;
  109095. for (var attr in technique.attributes) {
  109096. var attribute = technique.attributes[attr];
  109097. var attributeParameter = technique.parameters[attribute];
  109098. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  109099. newVertexShader += getAttribute(attributeParameter);
  109100. foundAttribute = true;
  109101. break;
  109102. }
  109103. }
  109104. if (foundAttribute) {
  109105. continue;
  109106. }
  109107. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  109108. }
  109109. // Configure pixel shader
  109110. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  109111. var tokenType = pixelTokenizer.currentToken;
  109112. if (tokenType !== ETokenType.IDENTIFIER) {
  109113. newPixelShader += pixelTokenizer.currentString;
  109114. continue;
  109115. }
  109116. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  109117. }
  109118. // Create shader material
  109119. var shaderPath = {
  109120. vertex: program.vertexShader + id,
  109121. fragment: program.fragmentShader + id
  109122. };
  109123. var options = {
  109124. attributes: attributes,
  109125. uniforms: uniforms,
  109126. samplers: samplers,
  109127. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  109128. };
  109129. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  109130. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  109131. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  109132. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  109133. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  109134. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109135. if (states && states.functions) {
  109136. var functions = states.functions;
  109137. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  109138. shaderMaterial.backFaceCulling = false;
  109139. }
  109140. var blendFunc = functions.blendFuncSeparate;
  109141. if (blendFunc) {
  109142. 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) {
  109143. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  109144. }
  109145. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  109146. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  109147. }
  109148. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  109149. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  109150. }
  109151. 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) {
  109152. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  109153. }
  109154. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  109155. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  109156. }
  109157. 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) {
  109158. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  109159. }
  109160. }
  109161. }
  109162. };
  109163. return GLTFLoaderBase;
  109164. }());
  109165. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  109166. /**
  109167. * glTF V1 Loader
  109168. */
  109169. var GLTFLoader = /** @class */ (function () {
  109170. function GLTFLoader() {
  109171. this.state = null;
  109172. }
  109173. GLTFLoader.RegisterExtension = function (extension) {
  109174. if (GLTFLoader.Extensions[extension.name]) {
  109175. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  109176. return;
  109177. }
  109178. GLTFLoader.Extensions[extension.name] = extension;
  109179. };
  109180. GLTFLoader.prototype.dispose = function () {
  109181. // do nothing
  109182. };
  109183. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  109184. var _this = this;
  109185. scene.useRightHandedSystem = true;
  109186. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  109187. gltfRuntime.importOnlyMeshes = true;
  109188. if (meshesNames === "") {
  109189. gltfRuntime.importMeshesNames = [];
  109190. }
  109191. else if (typeof meshesNames === "string") {
  109192. gltfRuntime.importMeshesNames = [meshesNames];
  109193. }
  109194. else if (meshesNames && !(meshesNames instanceof Array)) {
  109195. gltfRuntime.importMeshesNames = [meshesNames];
  109196. }
  109197. else {
  109198. gltfRuntime.importMeshesNames = [];
  109199. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  109200. }
  109201. // Create nodes
  109202. _this._createNodes(gltfRuntime);
  109203. var meshes = new Array();
  109204. var skeletons = new Array();
  109205. // Fill arrays of meshes and skeletons
  109206. for (var nde in gltfRuntime.nodes) {
  109207. var node = gltfRuntime.nodes[nde];
  109208. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  109209. meshes.push(node.babylonNode);
  109210. }
  109211. }
  109212. for (var skl in gltfRuntime.skins) {
  109213. var skin = gltfRuntime.skins[skl];
  109214. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  109215. skeletons.push(skin.babylonSkeleton);
  109216. }
  109217. }
  109218. // Load buffers, shaders, materials, etc.
  109219. _this._loadBuffersAsync(gltfRuntime, function () {
  109220. _this._loadShadersAsync(gltfRuntime, function () {
  109221. importMaterials(gltfRuntime);
  109222. postLoad(gltfRuntime);
  109223. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  109224. onSuccess(meshes, skeletons);
  109225. }
  109226. });
  109227. }, onProgress);
  109228. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  109229. onSuccess(meshes, skeletons);
  109230. }
  109231. }, onError);
  109232. return true;
  109233. };
  109234. /**
  109235. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  109236. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  109237. * @param scene the scene the meshes should be added to
  109238. * @param data gltf data containing information of the meshes in a loaded file
  109239. * @param rootUrl root url to load from
  109240. * @param onProgress event that fires when loading progress has occured
  109241. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  109242. */
  109243. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  109244. var _this = this;
  109245. return new Promise(function (resolve, reject) {
  109246. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  109247. resolve({
  109248. meshes: meshes,
  109249. particleSystems: [],
  109250. skeletons: skeletons,
  109251. animationGroups: []
  109252. });
  109253. }, onProgress, function (message) {
  109254. reject(new Error(message));
  109255. });
  109256. });
  109257. };
  109258. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  109259. var _this = this;
  109260. scene.useRightHandedSystem = true;
  109261. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  109262. // Load runtime extensios
  109263. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  109264. // Create nodes
  109265. _this._createNodes(gltfRuntime);
  109266. // Load buffers, shaders, materials, etc.
  109267. _this._loadBuffersAsync(gltfRuntime, function () {
  109268. _this._loadShadersAsync(gltfRuntime, function () {
  109269. importMaterials(gltfRuntime);
  109270. postLoad(gltfRuntime);
  109271. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  109272. onSuccess();
  109273. }
  109274. });
  109275. });
  109276. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  109277. onSuccess();
  109278. }
  109279. }, onError);
  109280. }, onError);
  109281. };
  109282. /**
  109283. * Imports all objects from a loaded gltf file and adds them to the scene
  109284. * @param scene the scene the objects should be added to
  109285. * @param data gltf data containing information of the meshes in a loaded file
  109286. * @param rootUrl root url to load from
  109287. * @param onProgress event that fires when loading progress has occured
  109288. * @returns a promise which completes when objects have been loaded to the scene
  109289. */
  109290. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  109291. var _this = this;
  109292. return new Promise(function (resolve, reject) {
  109293. _this._loadAsync(scene, data, rootUrl, function () {
  109294. resolve();
  109295. }, onProgress, function (message) {
  109296. reject(new Error(message));
  109297. });
  109298. });
  109299. };
  109300. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  109301. var hasShaders = false;
  109302. var processShader = function (sha, shader) {
  109303. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  109304. if (shaderString instanceof ArrayBuffer) {
  109305. return;
  109306. }
  109307. gltfRuntime.loadedShaderCount++;
  109308. if (shaderString) {
  109309. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  109310. }
  109311. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  109312. onload();
  109313. }
  109314. }, function () {
  109315. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  109316. });
  109317. };
  109318. for (var sha in gltfRuntime.shaders) {
  109319. hasShaders = true;
  109320. var shader = gltfRuntime.shaders[sha];
  109321. if (shader) {
  109322. processShader.bind(this, sha, shader)();
  109323. }
  109324. else {
  109325. BABYLON.Tools.Error("No shader named: " + sha);
  109326. }
  109327. }
  109328. if (!hasShaders) {
  109329. onload();
  109330. }
  109331. };
  109332. ;
  109333. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  109334. var hasBuffers = false;
  109335. var processBuffer = function (buf, buffer) {
  109336. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  109337. gltfRuntime.loadedBufferCount++;
  109338. if (bufferView) {
  109339. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  109340. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  109341. }
  109342. gltfRuntime.loadedBufferViews[buf] = bufferView;
  109343. }
  109344. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  109345. onLoad();
  109346. }
  109347. }, function () {
  109348. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  109349. });
  109350. };
  109351. for (var buf in gltfRuntime.buffers) {
  109352. hasBuffers = true;
  109353. var buffer = gltfRuntime.buffers[buf];
  109354. if (buffer) {
  109355. processBuffer.bind(this, buf, buffer)();
  109356. }
  109357. else {
  109358. BABYLON.Tools.Error("No buffer named: " + buf);
  109359. }
  109360. }
  109361. if (!hasBuffers) {
  109362. onLoad();
  109363. }
  109364. };
  109365. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  109366. var currentScene = gltfRuntime.currentScene;
  109367. if (currentScene) {
  109368. // Only one scene even if multiple scenes are defined
  109369. for (var i = 0; i < currentScene.nodes.length; i++) {
  109370. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  109371. }
  109372. }
  109373. else {
  109374. // Load all scenes
  109375. for (var thing in gltfRuntime.scenes) {
  109376. currentScene = gltfRuntime.scenes[thing];
  109377. for (var i = 0; i < currentScene.nodes.length; i++) {
  109378. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  109379. }
  109380. }
  109381. }
  109382. };
  109383. GLTFLoader.Extensions = {};
  109384. return GLTFLoader;
  109385. }());
  109386. GLTF1.GLTFLoader = GLTFLoader;
  109387. ;
  109388. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  109389. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109390. })(BABYLON || (BABYLON = {}));
  109391. //# sourceMappingURL=babylon.glTFLoader.js.map
  109392. var BABYLON;
  109393. (function (BABYLON) {
  109394. var GLTF1;
  109395. (function (GLTF1) {
  109396. /**
  109397. * Utils functions for GLTF
  109398. */
  109399. var GLTFUtils = /** @class */ (function () {
  109400. function GLTFUtils() {
  109401. }
  109402. /**
  109403. * Sets the given "parameter" matrix
  109404. * @param scene: the {BABYLON.Scene} object
  109405. * @param source: the source node where to pick the matrix
  109406. * @param parameter: the GLTF technique parameter
  109407. * @param uniformName: the name of the shader's uniform
  109408. * @param shaderMaterial: the shader material
  109409. */
  109410. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  109411. var mat = null;
  109412. if (parameter.semantic === "MODEL") {
  109413. mat = source.getWorldMatrix();
  109414. }
  109415. else if (parameter.semantic === "PROJECTION") {
  109416. mat = scene.getProjectionMatrix();
  109417. }
  109418. else if (parameter.semantic === "VIEW") {
  109419. mat = scene.getViewMatrix();
  109420. }
  109421. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  109422. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  109423. }
  109424. else if (parameter.semantic === "MODELVIEW") {
  109425. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  109426. }
  109427. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  109428. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  109429. }
  109430. else if (parameter.semantic === "MODELINVERSE") {
  109431. mat = source.getWorldMatrix().invert();
  109432. }
  109433. else if (parameter.semantic === "VIEWINVERSE") {
  109434. mat = scene.getViewMatrix().invert();
  109435. }
  109436. else if (parameter.semantic === "PROJECTIONINVERSE") {
  109437. mat = scene.getProjectionMatrix().invert();
  109438. }
  109439. else if (parameter.semantic === "MODELVIEWINVERSE") {
  109440. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  109441. }
  109442. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  109443. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  109444. }
  109445. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  109446. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  109447. }
  109448. else {
  109449. debugger;
  109450. }
  109451. if (mat) {
  109452. switch (parameter.type) {
  109453. case GLTF1.EParameterType.FLOAT_MAT2:
  109454. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  109455. break;
  109456. case GLTF1.EParameterType.FLOAT_MAT3:
  109457. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  109458. break;
  109459. case GLTF1.EParameterType.FLOAT_MAT4:
  109460. shaderMaterial.setMatrix(uniformName, mat);
  109461. break;
  109462. default: break;
  109463. }
  109464. }
  109465. };
  109466. /**
  109467. * Sets the given "parameter" matrix
  109468. * @param shaderMaterial: the shader material
  109469. * @param uniform: the name of the shader's uniform
  109470. * @param value: the value of the uniform
  109471. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  109472. */
  109473. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  109474. switch (type) {
  109475. case GLTF1.EParameterType.FLOAT:
  109476. shaderMaterial.setFloat(uniform, value);
  109477. return true;
  109478. case GLTF1.EParameterType.FLOAT_VEC2:
  109479. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  109480. return true;
  109481. case GLTF1.EParameterType.FLOAT_VEC3:
  109482. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  109483. return true;
  109484. case GLTF1.EParameterType.FLOAT_VEC4:
  109485. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  109486. return true;
  109487. default: return false;
  109488. }
  109489. };
  109490. /**
  109491. * Returns the wrap mode of the texture
  109492. * @param mode: the mode value
  109493. */
  109494. GLTFUtils.GetWrapMode = function (mode) {
  109495. switch (mode) {
  109496. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109497. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109498. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109499. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109500. }
  109501. };
  109502. /**
  109503. * Returns the byte stride giving an accessor
  109504. * @param accessor: the GLTF accessor objet
  109505. */
  109506. GLTFUtils.GetByteStrideFromType = function (accessor) {
  109507. // Needs this function since "byteStride" isn't requiered in glTF format
  109508. var type = accessor.type;
  109509. switch (type) {
  109510. case "VEC2": return 2;
  109511. case "VEC3": return 3;
  109512. case "VEC4": return 4;
  109513. case "MAT2": return 4;
  109514. case "MAT3": return 9;
  109515. case "MAT4": return 16;
  109516. default: return 1;
  109517. }
  109518. };
  109519. /**
  109520. * Returns the texture filter mode giving a mode value
  109521. * @param mode: the filter mode value
  109522. */
  109523. GLTFUtils.GetTextureFilterMode = function (mode) {
  109524. switch (mode) {
  109525. case GLTF1.ETextureFilterType.LINEAR:
  109526. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  109527. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  109528. case GLTF1.ETextureFilterType.NEAREST:
  109529. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  109530. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  109531. }
  109532. };
  109533. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  109534. var byteOffset = bufferView.byteOffset + byteOffset;
  109535. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  109536. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  109537. throw new Error("Buffer access is out of range");
  109538. }
  109539. var buffer = loadedBufferView.buffer;
  109540. byteOffset += loadedBufferView.byteOffset;
  109541. switch (componentType) {
  109542. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  109543. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  109544. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  109545. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  109546. default: return new Float32Array(buffer, byteOffset, byteLength);
  109547. }
  109548. };
  109549. /**
  109550. * Returns a buffer from its accessor
  109551. * @param gltfRuntime: the GLTF runtime
  109552. * @param accessor: the GLTF accessor
  109553. */
  109554. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  109555. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  109556. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  109557. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  109558. };
  109559. /**
  109560. * Decodes a buffer view into a string
  109561. * @param view: the buffer view
  109562. */
  109563. GLTFUtils.DecodeBufferToText = function (view) {
  109564. var result = "";
  109565. var length = view.byteLength;
  109566. for (var i = 0; i < length; ++i) {
  109567. result += String.fromCharCode(view[i]);
  109568. }
  109569. return result;
  109570. };
  109571. /**
  109572. * Returns the default material of gltf. Related to
  109573. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  109574. * @param scene: the Babylon.js scene
  109575. */
  109576. GLTFUtils.GetDefaultMaterial = function (scene) {
  109577. if (!GLTFUtils._DefaultMaterial) {
  109578. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  109579. "precision highp float;",
  109580. "",
  109581. "uniform mat4 worldView;",
  109582. "uniform mat4 projection;",
  109583. "",
  109584. "attribute vec3 position;",
  109585. "",
  109586. "void main(void)",
  109587. "{",
  109588. " gl_Position = projection * worldView * vec4(position, 1.0);",
  109589. "}"
  109590. ].join("\n");
  109591. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  109592. "precision highp float;",
  109593. "",
  109594. "uniform vec4 u_emission;",
  109595. "",
  109596. "void main(void)",
  109597. "{",
  109598. " gl_FragColor = u_emission;",
  109599. "}"
  109600. ].join("\n");
  109601. var shaderPath = {
  109602. vertex: "GLTFDefaultMaterial",
  109603. fragment: "GLTFDefaultMaterial"
  109604. };
  109605. var options = {
  109606. attributes: ["position"],
  109607. uniforms: ["worldView", "projection", "u_emission"],
  109608. samplers: new Array(),
  109609. needAlphaBlending: false
  109610. };
  109611. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  109612. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  109613. }
  109614. return GLTFUtils._DefaultMaterial;
  109615. };
  109616. // The GLTF default material
  109617. GLTFUtils._DefaultMaterial = null;
  109618. return GLTFUtils;
  109619. }());
  109620. GLTF1.GLTFUtils = GLTFUtils;
  109621. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109622. })(BABYLON || (BABYLON = {}));
  109623. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  109624. var BABYLON;
  109625. (function (BABYLON) {
  109626. var GLTF1;
  109627. (function (GLTF1) {
  109628. var GLTFLoaderExtension = /** @class */ (function () {
  109629. function GLTFLoaderExtension(name) {
  109630. this._name = name;
  109631. }
  109632. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  109633. get: function () {
  109634. return this._name;
  109635. },
  109636. enumerable: true,
  109637. configurable: true
  109638. });
  109639. /**
  109640. * Defines an override for loading the runtime
  109641. * Return true to stop further extensions from loading the runtime
  109642. */
  109643. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109644. return false;
  109645. };
  109646. /**
  109647. * Defines an onverride for creating gltf runtime
  109648. * Return true to stop further extensions from creating the runtime
  109649. */
  109650. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109651. return false;
  109652. };
  109653. /**
  109654. * Defines an override for loading buffers
  109655. * Return true to stop further extensions from loading this buffer
  109656. */
  109657. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109658. return false;
  109659. };
  109660. /**
  109661. * Defines an override for loading texture buffers
  109662. * Return true to stop further extensions from loading this texture data
  109663. */
  109664. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109665. return false;
  109666. };
  109667. /**
  109668. * Defines an override for creating textures
  109669. * Return true to stop further extensions from loading this texture
  109670. */
  109671. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109672. return false;
  109673. };
  109674. /**
  109675. * Defines an override for loading shader strings
  109676. * Return true to stop further extensions from loading this shader data
  109677. */
  109678. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109679. return false;
  109680. };
  109681. /**
  109682. * Defines an override for loading materials
  109683. * Return true to stop further extensions from loading this material
  109684. */
  109685. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109686. return false;
  109687. };
  109688. // ---------
  109689. // Utilities
  109690. // ---------
  109691. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109692. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109693. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  109694. }, function () {
  109695. setTimeout(function () {
  109696. if (!onSuccess) {
  109697. return;
  109698. }
  109699. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109700. });
  109701. });
  109702. };
  109703. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109704. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109705. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  109706. }, function () {
  109707. setTimeout(function () {
  109708. onSuccess();
  109709. });
  109710. });
  109711. };
  109712. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109713. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109714. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109715. }, function () {
  109716. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109717. });
  109718. };
  109719. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  109720. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  109721. if (buffer) {
  109722. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109723. }
  109724. }, onError);
  109725. };
  109726. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109727. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109728. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109729. }, function () {
  109730. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109731. });
  109732. };
  109733. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109734. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109735. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109736. }, function () {
  109737. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109738. });
  109739. };
  109740. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109741. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109742. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109743. }, function () {
  109744. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109745. });
  109746. };
  109747. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109748. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109749. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109750. }, function () {
  109751. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109752. });
  109753. };
  109754. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  109755. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  109756. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  109757. if (func(loaderExtension)) {
  109758. return;
  109759. }
  109760. }
  109761. defaultFunc();
  109762. };
  109763. return GLTFLoaderExtension;
  109764. }());
  109765. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  109766. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109767. })(BABYLON || (BABYLON = {}));
  109768. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109769. var BABYLON;
  109770. (function (BABYLON) {
  109771. var GLTF1;
  109772. (function (GLTF1) {
  109773. var BinaryExtensionBufferName = "binary_glTF";
  109774. ;
  109775. ;
  109776. var GLTFBinaryExtension = /** @class */ (function (_super) {
  109777. __extends(GLTFBinaryExtension, _super);
  109778. function GLTFBinaryExtension() {
  109779. return _super.call(this, "KHR_binary_glTF") || this;
  109780. }
  109781. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109782. var extensionsUsed = data.json.extensionsUsed;
  109783. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  109784. return false;
  109785. }
  109786. this._bin = data.bin;
  109787. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109788. return true;
  109789. };
  109790. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109791. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  109792. return false;
  109793. }
  109794. if (id !== BinaryExtensionBufferName) {
  109795. return false;
  109796. }
  109797. onSuccess(this._bin);
  109798. return true;
  109799. };
  109800. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109801. var texture = gltfRuntime.textures[id];
  109802. var source = gltfRuntime.images[texture.source];
  109803. if (!source.extensions || !(this.name in source.extensions)) {
  109804. return false;
  109805. }
  109806. var sourceExt = source.extensions[this.name];
  109807. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  109808. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109809. onSuccess(buffer);
  109810. return true;
  109811. };
  109812. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109813. var shader = gltfRuntime.shaders[id];
  109814. if (!shader.extensions || !(this.name in shader.extensions)) {
  109815. return false;
  109816. }
  109817. var binaryExtensionShader = shader.extensions[this.name];
  109818. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  109819. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109820. setTimeout(function () {
  109821. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  109822. onSuccess(shaderString);
  109823. });
  109824. return true;
  109825. };
  109826. return GLTFBinaryExtension;
  109827. }(GLTF1.GLTFLoaderExtension));
  109828. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  109829. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  109830. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109831. })(BABYLON || (BABYLON = {}));
  109832. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  109833. var BABYLON;
  109834. (function (BABYLON) {
  109835. var GLTF1;
  109836. (function (GLTF1) {
  109837. ;
  109838. ;
  109839. ;
  109840. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  109841. __extends(GLTFMaterialsCommonExtension, _super);
  109842. function GLTFMaterialsCommonExtension() {
  109843. return _super.call(this, "KHR_materials_common") || this;
  109844. }
  109845. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109846. if (!gltfRuntime.extensions)
  109847. return false;
  109848. var extension = gltfRuntime.extensions[this.name];
  109849. if (!extension)
  109850. return false;
  109851. // Create lights
  109852. var lights = extension.lights;
  109853. if (lights) {
  109854. for (var thing in lights) {
  109855. var light = lights[thing];
  109856. switch (light.type) {
  109857. case "ambient":
  109858. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  109859. var ambient = light.ambient;
  109860. if (ambient) {
  109861. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  109862. }
  109863. break;
  109864. case "point":
  109865. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  109866. var point = light.point;
  109867. if (point) {
  109868. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  109869. }
  109870. break;
  109871. case "directional":
  109872. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  109873. var directional = light.directional;
  109874. if (directional) {
  109875. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  109876. }
  109877. break;
  109878. case "spot":
  109879. var spot = light.spot;
  109880. if (spot) {
  109881. 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);
  109882. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  109883. }
  109884. break;
  109885. default:
  109886. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  109887. break;
  109888. }
  109889. }
  109890. }
  109891. return false;
  109892. };
  109893. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109894. var material = gltfRuntime.materials[id];
  109895. if (!material || !material.extensions)
  109896. return false;
  109897. var extension = material.extensions[this.name];
  109898. if (!extension)
  109899. return false;
  109900. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  109901. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109902. if (extension.technique === "CONSTANT") {
  109903. standardMaterial.disableLighting = true;
  109904. }
  109905. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  109906. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  109907. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  109908. // Ambient
  109909. if (typeof extension.values.ambient === "string") {
  109910. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  109911. }
  109912. else {
  109913. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  109914. }
  109915. // Diffuse
  109916. if (typeof extension.values.diffuse === "string") {
  109917. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  109918. }
  109919. else {
  109920. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  109921. }
  109922. // Emission
  109923. if (typeof extension.values.emission === "string") {
  109924. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  109925. }
  109926. else {
  109927. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  109928. }
  109929. // Specular
  109930. if (typeof extension.values.specular === "string") {
  109931. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  109932. }
  109933. else {
  109934. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  109935. }
  109936. return true;
  109937. };
  109938. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  109939. // Create buffer from texture url
  109940. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  109941. // Create texture from buffer
  109942. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  109943. }, onError);
  109944. };
  109945. return GLTFMaterialsCommonExtension;
  109946. }(GLTF1.GLTFLoaderExtension));
  109947. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  109948. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  109949. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109950. })(BABYLON || (BABYLON = {}));
  109951. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  109952. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  109953. /**
  109954. * Defines the module used to import/export glTF 2.0 assets
  109955. */
  109956. var BABYLON;
  109957. (function (BABYLON) {
  109958. var GLTF2;
  109959. (function (GLTF2) {
  109960. /** @hidden */
  109961. var _ArrayItem = /** @class */ (function () {
  109962. function _ArrayItem() {
  109963. }
  109964. _ArrayItem.Assign = function (values) {
  109965. if (values) {
  109966. for (var index = 0; index < values.length; index++) {
  109967. values[index]._index = index;
  109968. }
  109969. }
  109970. };
  109971. return _ArrayItem;
  109972. }());
  109973. GLTF2._ArrayItem = _ArrayItem;
  109974. /** @hidden */
  109975. var GLTFLoader = /** @class */ (function () {
  109976. function GLTFLoader(parent) {
  109977. this._completePromises = new Array();
  109978. this._disposed = false;
  109979. this._state = null;
  109980. this._extensions = {};
  109981. this._defaultSampler = {};
  109982. this._defaultBabylonMaterials = {};
  109983. this._requests = new Array();
  109984. this._parent = parent;
  109985. }
  109986. GLTFLoader._Register = function (name, factory) {
  109987. if (GLTFLoader._ExtensionFactories[name]) {
  109988. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  109989. return;
  109990. }
  109991. GLTFLoader._ExtensionFactories[name] = factory;
  109992. // Keep the order of registration so that extensions registered first are called first.
  109993. GLTFLoader._ExtensionNames.push(name);
  109994. };
  109995. Object.defineProperty(GLTFLoader.prototype, "state", {
  109996. /**
  109997. * Loader state or null if the loader is not active.
  109998. */
  109999. get: function () {
  110000. return this._state;
  110001. },
  110002. enumerable: true,
  110003. configurable: true
  110004. });
  110005. GLTFLoader.prototype.dispose = function () {
  110006. if (this._disposed) {
  110007. return;
  110008. }
  110009. this._disposed = true;
  110010. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110011. var request = _a[_i];
  110012. request.abort();
  110013. }
  110014. this._requests.length = 0;
  110015. delete this._gltf;
  110016. delete this._babylonScene;
  110017. delete this._readyPromise;
  110018. this._completePromises.length = 0;
  110019. for (var name_1 in this._extensions) {
  110020. this._extensions[name_1].dispose();
  110021. }
  110022. this._extensions = {};
  110023. delete this._rootBabylonMesh;
  110024. delete this._progressCallback;
  110025. this._parent._clear();
  110026. };
  110027. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  110028. var _this = this;
  110029. return Promise.resolve().then(function () {
  110030. _this._babylonScene = scene;
  110031. _this._rootUrl = rootUrl;
  110032. _this._progressCallback = onProgress;
  110033. _this._loadData(data);
  110034. var nodes = null;
  110035. if (meshesNames) {
  110036. var nodeMap_1 = {};
  110037. if (_this._gltf.nodes) {
  110038. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  110039. var node = _a[_i];
  110040. if (node.name) {
  110041. nodeMap_1[node.name] = node._index;
  110042. }
  110043. }
  110044. }
  110045. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  110046. nodes = names.map(function (name) {
  110047. var node = nodeMap_1[name];
  110048. if (node === undefined) {
  110049. throw new Error("Failed to find node '" + name + "'");
  110050. }
  110051. return node;
  110052. });
  110053. }
  110054. return _this._loadAsync(nodes).then(function () {
  110055. return {
  110056. meshes: _this._getMeshes(),
  110057. particleSystems: [],
  110058. skeletons: _this._getSkeletons(),
  110059. animationGroups: _this._getAnimationGroups()
  110060. };
  110061. });
  110062. });
  110063. };
  110064. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  110065. var _this = this;
  110066. return Promise.resolve().then(function () {
  110067. _this._babylonScene = scene;
  110068. _this._rootUrl = rootUrl;
  110069. _this._progressCallback = onProgress;
  110070. _this._loadData(data);
  110071. return _this._loadAsync(null);
  110072. });
  110073. };
  110074. GLTFLoader.prototype._loadAsync = function (nodes) {
  110075. var _this = this;
  110076. return Promise.resolve().then(function () {
  110077. _this._parent._startPerformanceCounter("Loading => Ready");
  110078. _this._parent._startPerformanceCounter("Loading => Complete");
  110079. _this._state = BABYLON.GLTFLoaderState.LOADING;
  110080. _this._parent._log("Loading");
  110081. var readyDeferred = new BABYLON.Deferred();
  110082. _this._readyPromise = readyDeferred.promise;
  110083. _this._loadExtensions();
  110084. _this._checkExtensions();
  110085. var promises = new Array();
  110086. if (nodes) {
  110087. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  110088. }
  110089. else {
  110090. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  110091. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  110092. }
  110093. if (_this._parent.compileMaterials) {
  110094. promises.push(_this._compileMaterialsAsync());
  110095. }
  110096. if (_this._parent.compileShadowGenerators) {
  110097. promises.push(_this._compileShadowGeneratorsAsync());
  110098. }
  110099. var resultPromise = Promise.all(promises).then(function () {
  110100. _this._state = BABYLON.GLTFLoaderState.READY;
  110101. _this._parent._log("Ready");
  110102. readyDeferred.resolve();
  110103. _this._startAnimations();
  110104. });
  110105. resultPromise.then(function () {
  110106. _this._parent._endPerformanceCounter("Loading => Ready");
  110107. BABYLON.Tools.SetImmediate(function () {
  110108. if (!_this._disposed) {
  110109. Promise.all(_this._completePromises).then(function () {
  110110. _this._parent._endPerformanceCounter("Loading => Complete");
  110111. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  110112. _this._parent._log("Complete");
  110113. _this._parent.onCompleteObservable.notifyObservers(undefined);
  110114. _this._parent.onCompleteObservable.clear();
  110115. _this.dispose();
  110116. }).catch(function (error) {
  110117. BABYLON.Tools.Error("glTF Loader: " + error.message);
  110118. _this.dispose();
  110119. });
  110120. }
  110121. });
  110122. });
  110123. return resultPromise;
  110124. }).catch(function (error) {
  110125. if (!_this._disposed) {
  110126. BABYLON.Tools.Error("glTF Loader: " + error.message);
  110127. _this.dispose();
  110128. throw error;
  110129. }
  110130. });
  110131. };
  110132. GLTFLoader.prototype._loadData = function (data) {
  110133. this._gltf = data.json;
  110134. this._setupData();
  110135. if (data.bin) {
  110136. var buffers = this._gltf.buffers;
  110137. if (buffers && buffers[0] && !buffers[0].uri) {
  110138. var binaryBuffer = buffers[0];
  110139. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  110140. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  110141. }
  110142. binaryBuffer._data = Promise.resolve(data.bin);
  110143. }
  110144. else {
  110145. BABYLON.Tools.Warn("Unexpected BIN chunk");
  110146. }
  110147. }
  110148. };
  110149. GLTFLoader.prototype._setupData = function () {
  110150. _ArrayItem.Assign(this._gltf.accessors);
  110151. _ArrayItem.Assign(this._gltf.animations);
  110152. _ArrayItem.Assign(this._gltf.buffers);
  110153. _ArrayItem.Assign(this._gltf.bufferViews);
  110154. _ArrayItem.Assign(this._gltf.cameras);
  110155. _ArrayItem.Assign(this._gltf.images);
  110156. _ArrayItem.Assign(this._gltf.materials);
  110157. _ArrayItem.Assign(this._gltf.meshes);
  110158. _ArrayItem.Assign(this._gltf.nodes);
  110159. _ArrayItem.Assign(this._gltf.samplers);
  110160. _ArrayItem.Assign(this._gltf.scenes);
  110161. _ArrayItem.Assign(this._gltf.skins);
  110162. _ArrayItem.Assign(this._gltf.textures);
  110163. if (this._gltf.nodes) {
  110164. var nodeParents = {};
  110165. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  110166. var node = _a[_i];
  110167. if (node.children) {
  110168. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  110169. var index = _c[_b];
  110170. nodeParents[index] = node._index;
  110171. }
  110172. }
  110173. }
  110174. var rootNode = this._createRootNode();
  110175. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  110176. var node = _e[_d];
  110177. var parentIndex = nodeParents[node._index];
  110178. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  110179. }
  110180. }
  110181. };
  110182. GLTFLoader.prototype._loadExtensions = function () {
  110183. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  110184. var name_2 = _a[_i];
  110185. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  110186. this._extensions[name_2] = extension;
  110187. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  110188. }
  110189. this._parent.onExtensionLoadedObservable.clear();
  110190. };
  110191. GLTFLoader.prototype._checkExtensions = function () {
  110192. if (this._gltf.extensionsRequired) {
  110193. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  110194. var name_3 = _a[_i];
  110195. var extension = this._extensions[name_3];
  110196. if (!extension || !extension.enabled) {
  110197. throw new Error("Require extension " + name_3 + " is not available");
  110198. }
  110199. }
  110200. }
  110201. };
  110202. GLTFLoader.prototype._createRootNode = function () {
  110203. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  110204. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  110205. switch (this._parent.coordinateSystemMode) {
  110206. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  110207. if (!this._babylonScene.useRightHandedSystem) {
  110208. rootNode.rotation = [0, 1, 0, 0];
  110209. rootNode.scale = [1, 1, -1];
  110210. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  110211. }
  110212. break;
  110213. }
  110214. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  110215. this._babylonScene.useRightHandedSystem = true;
  110216. break;
  110217. }
  110218. default: {
  110219. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  110220. }
  110221. }
  110222. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  110223. return rootNode;
  110224. };
  110225. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  110226. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  110227. if (extensionPromise) {
  110228. return extensionPromise;
  110229. }
  110230. var promises = new Array();
  110231. this._parent._logOpen(context + " " + (scene.name || ""));
  110232. if (scene.nodes) {
  110233. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  110234. var index = _a[_i];
  110235. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  110236. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  110237. }
  110238. }
  110239. promises.push(this._loadAnimationsAsync());
  110240. this._parent._logClose();
  110241. return Promise.all(promises).then(function () { });
  110242. };
  110243. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  110244. if (node._primitiveBabylonMeshes) {
  110245. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  110246. var babylonMesh = _a[_i];
  110247. callback(babylonMesh);
  110248. }
  110249. }
  110250. else {
  110251. callback(node._babylonMesh);
  110252. }
  110253. };
  110254. GLTFLoader.prototype._getMeshes = function () {
  110255. var meshes = new Array();
  110256. // Root mesh is always first.
  110257. meshes.push(this._rootBabylonMesh);
  110258. var nodes = this._gltf.nodes;
  110259. if (nodes) {
  110260. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  110261. var node = nodes_1[_i];
  110262. if (node._babylonMesh) {
  110263. meshes.push(node._babylonMesh);
  110264. }
  110265. if (node._primitiveBabylonMeshes) {
  110266. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  110267. var babylonMesh = _b[_a];
  110268. meshes.push(babylonMesh);
  110269. }
  110270. }
  110271. }
  110272. }
  110273. return meshes;
  110274. };
  110275. GLTFLoader.prototype._getSkeletons = function () {
  110276. var skeletons = new Array();
  110277. var skins = this._gltf.skins;
  110278. if (skins) {
  110279. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  110280. var skin = skins_1[_i];
  110281. if (skin._babylonSkeleton) {
  110282. skeletons.push(skin._babylonSkeleton);
  110283. }
  110284. }
  110285. }
  110286. return skeletons;
  110287. };
  110288. GLTFLoader.prototype._getAnimationGroups = function () {
  110289. var animationGroups = new Array();
  110290. var animations = this._gltf.animations;
  110291. if (animations) {
  110292. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  110293. var animation = animations_1[_i];
  110294. if (animation._babylonAnimationGroup) {
  110295. animationGroups.push(animation._babylonAnimationGroup);
  110296. }
  110297. }
  110298. }
  110299. return animationGroups;
  110300. };
  110301. GLTFLoader.prototype._startAnimations = function () {
  110302. switch (this._parent.animationStartMode) {
  110303. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  110304. // do nothing
  110305. break;
  110306. }
  110307. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  110308. var babylonAnimationGroups = this._getAnimationGroups();
  110309. if (babylonAnimationGroups.length !== 0) {
  110310. babylonAnimationGroups[0].start(true);
  110311. }
  110312. break;
  110313. }
  110314. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  110315. var babylonAnimationGroups = this._getAnimationGroups();
  110316. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  110317. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  110318. babylonAnimationGroup.start(true);
  110319. }
  110320. break;
  110321. }
  110322. default: {
  110323. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  110324. return;
  110325. }
  110326. }
  110327. };
  110328. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  110329. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  110330. if (extensionPromise) {
  110331. return extensionPromise;
  110332. }
  110333. if (node._babylonMesh) {
  110334. throw new Error(context + ": Invalid recursive node hierarchy");
  110335. }
  110336. var promises = new Array();
  110337. this._parent._logOpen(context + " " + (node.name || ""));
  110338. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  110339. node._babylonMesh = babylonMesh;
  110340. babylonMesh.setEnabled(false);
  110341. GLTFLoader._LoadTransform(node, babylonMesh);
  110342. if (node.mesh != undefined) {
  110343. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  110344. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  110345. }
  110346. if (node.camera != undefined) {
  110347. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  110348. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  110349. }
  110350. if (node.children) {
  110351. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  110352. var index = _a[_i];
  110353. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  110354. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  110355. }
  110356. }
  110357. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  110358. this._parent._logClose();
  110359. return Promise.all(promises).then(function () {
  110360. babylonMesh.setEnabled(true);
  110361. });
  110362. };
  110363. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  110364. var _this = this;
  110365. var promises = new Array();
  110366. this._parent._logOpen(context + " " + (mesh.name || ""));
  110367. var primitives = mesh.primitives;
  110368. if (!primitives || primitives.length === 0) {
  110369. throw new Error(context + ": Primitives are missing");
  110370. }
  110371. _ArrayItem.Assign(primitives);
  110372. if (primitives.length === 1) {
  110373. var primitive = primitives[0];
  110374. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  110375. }
  110376. else {
  110377. node._primitiveBabylonMeshes = [];
  110378. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  110379. var primitive = primitives_1[_i];
  110380. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  110381. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  110382. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  110383. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  110384. }
  110385. }
  110386. if (node.skin != undefined) {
  110387. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  110388. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  110389. }
  110390. this._parent._logClose();
  110391. return Promise.all(promises).then(function () {
  110392. _this._forEachPrimitive(node, function (babylonMesh) {
  110393. babylonMesh._refreshBoundingInfo(true);
  110394. });
  110395. });
  110396. };
  110397. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  110398. var _this = this;
  110399. var promises = new Array();
  110400. this._parent._logOpen("" + context);
  110401. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  110402. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  110403. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  110404. babylonGeometry.applyToMesh(babylonMesh);
  110405. });
  110406. }));
  110407. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  110408. if (primitive.material == undefined) {
  110409. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  110410. }
  110411. else {
  110412. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  110413. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  110414. babylonMesh.material = babylonMaterial;
  110415. }));
  110416. }
  110417. this._parent._logClose();
  110418. return Promise.all(promises).then(function () { });
  110419. };
  110420. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  110421. var _this = this;
  110422. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  110423. if (extensionPromise) {
  110424. return extensionPromise;
  110425. }
  110426. var attributes = primitive.attributes;
  110427. if (!attributes) {
  110428. throw new Error(context + ": Attributes are missing");
  110429. }
  110430. var promises = new Array();
  110431. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  110432. if (primitive.indices == undefined) {
  110433. babylonMesh.isUnIndexed = true;
  110434. }
  110435. else {
  110436. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  110437. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  110438. babylonGeometry.setIndices(data);
  110439. }));
  110440. }
  110441. var loadAttribute = function (attribute, kind, callback) {
  110442. if (attributes[attribute] == undefined) {
  110443. return;
  110444. }
  110445. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  110446. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  110447. babylonMesh._delayInfo.push(kind);
  110448. }
  110449. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  110450. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  110451. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  110452. }));
  110453. if (callback) {
  110454. callback(accessor);
  110455. }
  110456. };
  110457. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  110458. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  110459. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  110460. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  110461. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  110462. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  110463. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  110464. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  110465. if (accessor.type === "VEC4" /* VEC4 */) {
  110466. babylonMesh.hasVertexAlpha = true;
  110467. }
  110468. });
  110469. return Promise.all(promises).then(function () {
  110470. return babylonGeometry;
  110471. });
  110472. };
  110473. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  110474. if (!primitive.targets) {
  110475. return;
  110476. }
  110477. if (node._numMorphTargets == undefined) {
  110478. node._numMorphTargets = primitive.targets.length;
  110479. }
  110480. else if (primitive.targets.length !== node._numMorphTargets) {
  110481. throw new Error(context + ": Primitives do not have the same number of targets");
  110482. }
  110483. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  110484. for (var index = 0; index < primitive.targets.length; index++) {
  110485. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  110486. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  110487. // TODO: tell the target whether it has positions, normals, tangents
  110488. }
  110489. };
  110490. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  110491. if (!primitive.targets) {
  110492. return Promise.resolve();
  110493. }
  110494. var promises = new Array();
  110495. var morphTargetManager = babylonMesh.morphTargetManager;
  110496. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  110497. var babylonMorphTarget = morphTargetManager.getTarget(index);
  110498. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  110499. }
  110500. return Promise.all(promises).then(function () { });
  110501. };
  110502. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  110503. var _this = this;
  110504. var promises = new Array();
  110505. var loadAttribute = function (attribute, kind, setData) {
  110506. if (attributes[attribute] == undefined) {
  110507. return;
  110508. }
  110509. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  110510. if (!babylonVertexBuffer) {
  110511. return;
  110512. }
  110513. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  110514. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  110515. setData(babylonVertexBuffer, data);
  110516. }));
  110517. };
  110518. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  110519. babylonVertexBuffer.forEach(data.length, function (value, index) {
  110520. data[index] += value;
  110521. });
  110522. babylonMorphTarget.setPositions(data);
  110523. });
  110524. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  110525. babylonVertexBuffer.forEach(data.length, function (value, index) {
  110526. data[index] += value;
  110527. });
  110528. babylonMorphTarget.setNormals(data);
  110529. });
  110530. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  110531. var dataIndex = 0;
  110532. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  110533. // Tangent data for morph targets is stored as xyz delta.
  110534. // The vertexData.tangent is stored as xyzw.
  110535. // So we need to skip every fourth vertexData.tangent.
  110536. if (((index + 1) % 4) !== 0) {
  110537. data[dataIndex++] += value;
  110538. }
  110539. });
  110540. babylonMorphTarget.setTangents(data);
  110541. });
  110542. return Promise.all(promises).then(function () { });
  110543. };
  110544. GLTFLoader._LoadTransform = function (node, babylonNode) {
  110545. var position = BABYLON.Vector3.Zero();
  110546. var rotation = BABYLON.Quaternion.Identity();
  110547. var scaling = BABYLON.Vector3.One();
  110548. if (node.matrix) {
  110549. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  110550. matrix.decompose(scaling, rotation, position);
  110551. }
  110552. else {
  110553. if (node.translation)
  110554. position = BABYLON.Vector3.FromArray(node.translation);
  110555. if (node.rotation)
  110556. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  110557. if (node.scale)
  110558. scaling = BABYLON.Vector3.FromArray(node.scale);
  110559. }
  110560. babylonNode.position = position;
  110561. babylonNode.rotationQuaternion = rotation;
  110562. babylonNode.scaling = scaling;
  110563. };
  110564. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  110565. var _this = this;
  110566. var assignSkeleton = function (skeleton) {
  110567. _this._forEachPrimitive(node, function (babylonMesh) {
  110568. babylonMesh.skeleton = skeleton;
  110569. });
  110570. // Ignore the TRS of skinned nodes.
  110571. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  110572. node._babylonMesh.parent = _this._rootBabylonMesh;
  110573. node._babylonMesh.position = BABYLON.Vector3.Zero();
  110574. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  110575. node._babylonMesh.scaling = BABYLON.Vector3.One();
  110576. };
  110577. if (skin._loaded) {
  110578. return skin._loaded.then(function () {
  110579. assignSkeleton(skin._babylonSkeleton);
  110580. });
  110581. }
  110582. var skeletonId = "skeleton" + skin._index;
  110583. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  110584. skin._babylonSkeleton = babylonSkeleton;
  110585. this._loadBones(context, skin);
  110586. assignSkeleton(babylonSkeleton);
  110587. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  110588. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  110589. }));
  110590. };
  110591. GLTFLoader.prototype._loadBones = function (context, skin) {
  110592. var babylonBones = {};
  110593. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  110594. var index = _a[_i];
  110595. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  110596. this._loadBone(node, skin, babylonBones);
  110597. }
  110598. };
  110599. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  110600. var babylonBone = babylonBones[node._index];
  110601. if (babylonBone) {
  110602. return babylonBone;
  110603. }
  110604. var babylonParentBone = null;
  110605. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  110606. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  110607. }
  110608. var boneIndex = skin.joints.indexOf(node._index);
  110609. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  110610. babylonBones[node._index] = babylonBone;
  110611. node._babylonBones = node._babylonBones || [];
  110612. node._babylonBones.push(babylonBone);
  110613. return babylonBone;
  110614. };
  110615. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  110616. if (skin.inverseBindMatrices == undefined) {
  110617. return Promise.resolve(null);
  110618. }
  110619. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  110620. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  110621. };
  110622. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  110623. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  110624. var babylonBone = _a[_i];
  110625. var baseMatrix = BABYLON.Matrix.Identity();
  110626. var boneIndex = babylonBone._index;
  110627. if (inverseBindMatricesData && boneIndex !== -1) {
  110628. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  110629. baseMatrix.invertToRef(baseMatrix);
  110630. }
  110631. var babylonParentBone = babylonBone.getParent();
  110632. if (babylonParentBone) {
  110633. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  110634. }
  110635. babylonBone.updateMatrix(baseMatrix, false, false);
  110636. babylonBone._updateDifferenceMatrix(undefined, false);
  110637. }
  110638. };
  110639. GLTFLoader.prototype._getNodeMatrix = function (node) {
  110640. return node.matrix ?
  110641. BABYLON.Matrix.FromArray(node.matrix) :
  110642. 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());
  110643. };
  110644. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  110645. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  110646. babylonCamera.parent = babylonMesh;
  110647. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  110648. switch (camera.type) {
  110649. case "perspective" /* PERSPECTIVE */: {
  110650. var perspective = camera.perspective;
  110651. if (!perspective) {
  110652. throw new Error(context + ": Camera perspective properties are missing");
  110653. }
  110654. babylonCamera.fov = perspective.yfov;
  110655. babylonCamera.minZ = perspective.znear;
  110656. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  110657. break;
  110658. }
  110659. case "orthographic" /* ORTHOGRAPHIC */: {
  110660. if (!camera.orthographic) {
  110661. throw new Error(context + ": Camera orthographic properties are missing");
  110662. }
  110663. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  110664. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  110665. babylonCamera.orthoRight = camera.orthographic.xmag;
  110666. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  110667. babylonCamera.orthoTop = camera.orthographic.ymag;
  110668. babylonCamera.minZ = camera.orthographic.znear;
  110669. babylonCamera.maxZ = camera.orthographic.zfar;
  110670. break;
  110671. }
  110672. default: {
  110673. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  110674. }
  110675. }
  110676. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  110677. };
  110678. GLTFLoader.prototype._loadAnimationsAsync = function () {
  110679. var animations = this._gltf.animations;
  110680. if (!animations) {
  110681. return Promise.resolve();
  110682. }
  110683. var promises = new Array();
  110684. for (var index = 0; index < animations.length; index++) {
  110685. var animation = animations[index];
  110686. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  110687. }
  110688. return Promise.all(promises).then(function () { });
  110689. };
  110690. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  110691. var _this = this;
  110692. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  110693. animation._babylonAnimationGroup = babylonAnimationGroup;
  110694. var promises = new Array();
  110695. _ArrayItem.Assign(animation.channels);
  110696. _ArrayItem.Assign(animation.samplers);
  110697. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  110698. var channel = _a[_i];
  110699. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  110700. }
  110701. return Promise.all(promises).then(function () {
  110702. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  110703. });
  110704. };
  110705. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  110706. var _this = this;
  110707. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  110708. // Ignore animations that have no animation targets.
  110709. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  110710. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  110711. return Promise.resolve();
  110712. }
  110713. // Ignore animations targeting TRS of skinned nodes.
  110714. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  110715. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  110716. return Promise.resolve();
  110717. }
  110718. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  110719. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  110720. var targetPath;
  110721. var animationType;
  110722. switch (channel.target.path) {
  110723. case "translation" /* TRANSLATION */: {
  110724. targetPath = "position";
  110725. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110726. break;
  110727. }
  110728. case "rotation" /* ROTATION */: {
  110729. targetPath = "rotationQuaternion";
  110730. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  110731. break;
  110732. }
  110733. case "scale" /* SCALE */: {
  110734. targetPath = "scaling";
  110735. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110736. break;
  110737. }
  110738. case "weights" /* WEIGHTS */: {
  110739. targetPath = "influence";
  110740. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  110741. break;
  110742. }
  110743. default: {
  110744. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  110745. }
  110746. }
  110747. var outputBufferOffset = 0;
  110748. var getNextOutputValue;
  110749. switch (targetPath) {
  110750. case "position": {
  110751. getNextOutputValue = function () {
  110752. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110753. outputBufferOffset += 3;
  110754. return value;
  110755. };
  110756. break;
  110757. }
  110758. case "rotationQuaternion": {
  110759. getNextOutputValue = function () {
  110760. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  110761. outputBufferOffset += 4;
  110762. return value;
  110763. };
  110764. break;
  110765. }
  110766. case "scaling": {
  110767. getNextOutputValue = function () {
  110768. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110769. outputBufferOffset += 3;
  110770. return value;
  110771. };
  110772. break;
  110773. }
  110774. case "influence": {
  110775. getNextOutputValue = function () {
  110776. var value = new Array(targetNode._numMorphTargets);
  110777. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  110778. value[i] = data.output[outputBufferOffset++];
  110779. }
  110780. return value;
  110781. };
  110782. break;
  110783. }
  110784. }
  110785. var getNextKey;
  110786. switch (data.interpolation) {
  110787. case "STEP" /* STEP */: {
  110788. getNextKey = function (frameIndex) { return ({
  110789. frame: data.input[frameIndex],
  110790. value: getNextOutputValue(),
  110791. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  110792. }); };
  110793. break;
  110794. }
  110795. case "LINEAR" /* LINEAR */: {
  110796. getNextKey = function (frameIndex) { return ({
  110797. frame: data.input[frameIndex],
  110798. value: getNextOutputValue()
  110799. }); };
  110800. break;
  110801. }
  110802. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110803. getNextKey = function (frameIndex) { return ({
  110804. frame: data.input[frameIndex],
  110805. inTangent: getNextOutputValue(),
  110806. value: getNextOutputValue(),
  110807. outTangent: getNextOutputValue()
  110808. }); };
  110809. break;
  110810. }
  110811. }
  110812. var keys = new Array(data.input.length);
  110813. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  110814. keys[frameIndex] = getNextKey(frameIndex);
  110815. }
  110816. if (targetPath === "influence") {
  110817. var _loop_1 = function (targetIndex) {
  110818. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110819. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110820. babylonAnimation.setKeys(keys.map(function (key) { return ({
  110821. frame: key.frame,
  110822. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  110823. value: key.value[targetIndex],
  110824. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  110825. }); }));
  110826. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  110827. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  110828. var babylonAnimationClone = babylonAnimation.clone();
  110829. morphTarget.animations.push(babylonAnimationClone);
  110830. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  110831. });
  110832. };
  110833. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  110834. _loop_1(targetIndex);
  110835. }
  110836. }
  110837. else {
  110838. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110839. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110840. babylonAnimation.setKeys(keys);
  110841. if (targetNode._babylonBones) {
  110842. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  110843. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  110844. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  110845. babylonAnimationTarget.animations.push(babylonAnimation);
  110846. }
  110847. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  110848. }
  110849. else {
  110850. targetNode._babylonMesh.animations.push(babylonAnimation);
  110851. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  110852. }
  110853. }
  110854. });
  110855. };
  110856. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  110857. if (sampler._data) {
  110858. return sampler._data;
  110859. }
  110860. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  110861. switch (interpolation) {
  110862. case "STEP" /* STEP */:
  110863. case "LINEAR" /* LINEAR */:
  110864. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110865. break;
  110866. }
  110867. default: {
  110868. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  110869. }
  110870. }
  110871. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  110872. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  110873. sampler._data = Promise.all([
  110874. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  110875. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  110876. ]).then(function (_a) {
  110877. var inputData = _a[0], outputData = _a[1];
  110878. return {
  110879. input: inputData,
  110880. interpolation: interpolation,
  110881. output: outputData,
  110882. };
  110883. });
  110884. return sampler._data;
  110885. };
  110886. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  110887. if (buffer._data) {
  110888. return buffer._data;
  110889. }
  110890. if (!buffer.uri) {
  110891. throw new Error(context + ": Uri is missing");
  110892. }
  110893. buffer._data = this._loadUriAsync(context, buffer.uri);
  110894. return buffer._data;
  110895. };
  110896. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  110897. if (bufferView._data) {
  110898. return bufferView._data;
  110899. }
  110900. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  110901. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  110902. try {
  110903. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  110904. }
  110905. catch (e) {
  110906. throw new Error(context + ": " + e.message);
  110907. }
  110908. });
  110909. return bufferView._data;
  110910. };
  110911. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  110912. if (accessor.type !== "SCALAR" /* SCALAR */) {
  110913. throw new Error(context + ": Invalid type " + accessor.type);
  110914. }
  110915. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  110916. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  110917. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  110918. throw new Error(context + ": Invalid component type " + accessor.componentType);
  110919. }
  110920. if (accessor._data) {
  110921. return accessor._data;
  110922. }
  110923. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110924. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110925. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  110926. });
  110927. return accessor._data;
  110928. };
  110929. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  110930. // TODO: support normalized and stride
  110931. var _this = this;
  110932. if (accessor.componentType !== 5126 /* FLOAT */) {
  110933. throw new Error("Invalid component type " + accessor.componentType);
  110934. }
  110935. if (accessor._data) {
  110936. return accessor._data;
  110937. }
  110938. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  110939. var length = numComponents * accessor.count;
  110940. if (accessor.bufferView == undefined) {
  110941. accessor._data = Promise.resolve(new Float32Array(length));
  110942. }
  110943. else {
  110944. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110945. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110946. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  110947. });
  110948. }
  110949. if (accessor.sparse) {
  110950. var sparse_1 = accessor.sparse;
  110951. accessor._data = accessor._data.then(function (data) {
  110952. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  110953. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  110954. return Promise.all([
  110955. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  110956. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  110957. ]).then(function (_a) {
  110958. var indicesData = _a[0], valuesData = _a[1];
  110959. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  110960. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  110961. var valuesIndex = 0;
  110962. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  110963. var dataIndex = indices[indicesIndex] * numComponents;
  110964. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  110965. data[dataIndex++] = values[valuesIndex++];
  110966. }
  110967. }
  110968. return data;
  110969. });
  110970. });
  110971. }
  110972. return accessor._data;
  110973. };
  110974. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  110975. var _this = this;
  110976. if (bufferView._babylonBuffer) {
  110977. return bufferView._babylonBuffer;
  110978. }
  110979. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  110980. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  110981. });
  110982. return bufferView._babylonBuffer;
  110983. };
  110984. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  110985. var _this = this;
  110986. if (accessor._babylonVertexBuffer) {
  110987. return accessor._babylonVertexBuffer;
  110988. }
  110989. if (accessor.sparse) {
  110990. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  110991. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  110992. });
  110993. }
  110994. else {
  110995. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110996. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  110997. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  110998. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  110999. });
  111000. }
  111001. return accessor._babylonVertexBuffer;
  111002. };
  111003. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  111004. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  111005. if (!babylonMaterial) {
  111006. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  111007. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  111008. babylonMaterial.metallic = 1;
  111009. babylonMaterial.roughness = 1;
  111010. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  111011. }
  111012. return babylonMaterial;
  111013. };
  111014. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  111015. var promises = new Array();
  111016. // Ensure metallic workflow
  111017. babylonMaterial.metallic = 1;
  111018. babylonMaterial.roughness = 1;
  111019. var properties = material.pbrMetallicRoughness;
  111020. if (properties) {
  111021. if (properties.baseColorFactor) {
  111022. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  111023. babylonMaterial.alpha = properties.baseColorFactor[3];
  111024. }
  111025. else {
  111026. babylonMaterial.albedoColor = BABYLON.Color3.White();
  111027. }
  111028. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  111029. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  111030. if (properties.baseColorTexture) {
  111031. promises.push(this._loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  111032. babylonMaterial.albedoTexture = texture;
  111033. }));
  111034. }
  111035. if (properties.metallicRoughnessTexture) {
  111036. promises.push(this._loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  111037. babylonMaterial.metallicTexture = texture;
  111038. }));
  111039. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  111040. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  111041. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  111042. }
  111043. }
  111044. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  111045. return Promise.all(promises).then(function () { });
  111046. };
  111047. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111048. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  111049. if (extensionPromise) {
  111050. return extensionPromise;
  111051. }
  111052. material._babylonData = material._babylonData || {};
  111053. var babylonData = material._babylonData[babylonDrawMode];
  111054. if (!babylonData) {
  111055. this._parent._logOpen(context + " " + (material.name || ""));
  111056. var name_4 = material.name || "material" + material._index;
  111057. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  111058. babylonData = {
  111059. material: babylonMaterial,
  111060. meshes: [],
  111061. loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)
  111062. };
  111063. material._babylonData[babylonDrawMode] = babylonData;
  111064. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  111065. this._parent._logClose();
  111066. }
  111067. babylonData.meshes.push(babylonMesh);
  111068. babylonMesh.onDisposeObservable.addOnce(function () {
  111069. var index = babylonData.meshes.indexOf(babylonMesh);
  111070. if (index !== -1) {
  111071. babylonData.meshes.splice(index, 1);
  111072. }
  111073. });
  111074. assign(babylonData.material);
  111075. return babylonData.loaded;
  111076. };
  111077. GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  111078. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);
  111079. if (extensionPromise) {
  111080. return extensionPromise;
  111081. }
  111082. var promises = new Array();
  111083. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  111084. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  111085. return Promise.all(promises).then(function () { });
  111086. };
  111087. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  111088. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  111089. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  111090. babylonMaterial.fillMode = drawMode;
  111091. babylonMaterial.enableSpecularAntiAliasing = true;
  111092. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  111093. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  111094. return babylonMaterial;
  111095. };
  111096. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  111097. var promises = new Array();
  111098. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  111099. if (material.doubleSided) {
  111100. babylonMaterial.backFaceCulling = false;
  111101. babylonMaterial.twoSidedLighting = true;
  111102. }
  111103. if (material.normalTexture) {
  111104. promises.push(this._loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  111105. babylonMaterial.bumpTexture = texture;
  111106. }));
  111107. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  111108. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  111109. if (material.normalTexture.scale != undefined) {
  111110. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  111111. }
  111112. }
  111113. if (material.occlusionTexture) {
  111114. promises.push(this._loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  111115. babylonMaterial.ambientTexture = texture;
  111116. }));
  111117. babylonMaterial.useAmbientInGrayScale = true;
  111118. if (material.occlusionTexture.strength != undefined) {
  111119. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  111120. }
  111121. }
  111122. if (material.emissiveTexture) {
  111123. promises.push(this._loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  111124. babylonMaterial.emissiveTexture = texture;
  111125. }));
  111126. }
  111127. return Promise.all(promises).then(function () { });
  111128. };
  111129. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  111130. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  111131. switch (alphaMode) {
  111132. case "OPAQUE" /* OPAQUE */: {
  111133. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  111134. break;
  111135. }
  111136. case "MASK" /* MASK */: {
  111137. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  111138. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  111139. if (babylonMaterial.albedoTexture) {
  111140. babylonMaterial.albedoTexture.hasAlpha = true;
  111141. }
  111142. break;
  111143. }
  111144. case "BLEND" /* BLEND */: {
  111145. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  111146. if (babylonMaterial.albedoTexture) {
  111147. babylonMaterial.albedoTexture.hasAlpha = true;
  111148. babylonMaterial.useAlphaFromAlbedoTexture = true;
  111149. }
  111150. break;
  111151. }
  111152. default: {
  111153. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  111154. }
  111155. }
  111156. };
  111157. GLTFLoader.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {
  111158. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureInfoAsync(this, context, textureInfo, assign);
  111159. if (extensionPromise) {
  111160. return extensionPromise;
  111161. }
  111162. this._parent._logOpen("" + context);
  111163. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  111164. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  111165. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  111166. assign(babylonTexture);
  111167. });
  111168. this._parent._logClose();
  111169. return promise;
  111170. };
  111171. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  111172. var _this = this;
  111173. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, texture, assign);
  111174. if (extensionPromise) {
  111175. return extensionPromise;
  111176. }
  111177. var promises = new Array();
  111178. this._parent._logOpen(context + " " + (texture.name || ""));
  111179. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  111180. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  111181. var deferred = new BABYLON.Deferred();
  111182. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  111183. if (!_this._disposed) {
  111184. deferred.resolve();
  111185. }
  111186. }, function (message, exception) {
  111187. if (!_this._disposed) {
  111188. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  111189. }
  111190. });
  111191. promises.push(deferred.promise);
  111192. babylonTexture.name = texture.name || "texture" + texture._index;
  111193. babylonTexture.wrapU = samplerData.wrapU;
  111194. babylonTexture.wrapV = samplerData.wrapV;
  111195. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  111196. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (data) {
  111197. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  111198. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  111199. }));
  111200. assign(babylonTexture);
  111201. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  111202. this._parent._logClose();
  111203. return Promise.all(promises).then(function () { });
  111204. };
  111205. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  111206. if (!sampler._data) {
  111207. sampler._data = {
  111208. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  111209. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  111210. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  111211. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  111212. };
  111213. }
  111214. ;
  111215. return sampler._data;
  111216. };
  111217. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  111218. if (!image._data) {
  111219. this._parent._logOpen(context + " " + (image.name || ""));
  111220. if (image.uri) {
  111221. image._data = this._loadUriAsync(context, image.uri);
  111222. }
  111223. else {
  111224. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  111225. image._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  111226. }
  111227. this._parent._logClose();
  111228. }
  111229. return image._data;
  111230. };
  111231. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  111232. var _this = this;
  111233. var extensionPromise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  111234. if (extensionPromise) {
  111235. return extensionPromise;
  111236. }
  111237. if (!GLTFLoader._ValidateUri(uri)) {
  111238. throw new Error(context + ": Uri '" + uri + "' is invalid");
  111239. }
  111240. if (BABYLON.Tools.IsBase64(uri)) {
  111241. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  111242. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  111243. return Promise.resolve(data);
  111244. }
  111245. this._parent._log("Loading " + uri);
  111246. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  111247. return new Promise(function (resolve, reject) {
  111248. if (!_this._disposed) {
  111249. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  111250. if (!_this._disposed) {
  111251. var data = new Uint8Array(fileData);
  111252. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  111253. resolve(data);
  111254. }
  111255. }, function (event) {
  111256. if (!_this._disposed) {
  111257. if (request_1) {
  111258. request_1._lengthComputable = event.lengthComputable;
  111259. request_1._loaded = event.loaded;
  111260. request_1._total = event.total;
  111261. }
  111262. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  111263. try {
  111264. _this._onProgress();
  111265. }
  111266. catch (e) {
  111267. reject(e);
  111268. }
  111269. }
  111270. }
  111271. }, _this._babylonScene.database, true, function (request, exception) {
  111272. if (!_this._disposed) {
  111273. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  111274. }
  111275. });
  111276. _this._requests.push(request_1);
  111277. }
  111278. });
  111279. });
  111280. };
  111281. GLTFLoader.prototype._onProgress = function () {
  111282. if (!this._progressCallback) {
  111283. return;
  111284. }
  111285. var lengthComputable = true;
  111286. var loaded = 0;
  111287. var total = 0;
  111288. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  111289. var request = _a[_i];
  111290. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  111291. return;
  111292. }
  111293. lengthComputable = lengthComputable && request._lengthComputable;
  111294. loaded += request._loaded;
  111295. total += request._total;
  111296. }
  111297. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  111298. };
  111299. GLTFLoader._GetProperty = function (context, array, index) {
  111300. if (!array || index == undefined || !array[index]) {
  111301. throw new Error(context + ": Failed to find index (" + index + ")");
  111302. }
  111303. return array[index];
  111304. };
  111305. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  111306. // Set defaults if undefined
  111307. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  111308. switch (mode) {
  111309. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  111310. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  111311. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  111312. default:
  111313. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  111314. return BABYLON.Texture.WRAP_ADDRESSMODE;
  111315. }
  111316. };
  111317. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  111318. // Set defaults if undefined
  111319. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  111320. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  111321. if (magFilter === 9729 /* LINEAR */) {
  111322. switch (minFilter) {
  111323. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  111324. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  111325. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  111326. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  111327. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  111328. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  111329. default:
  111330. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  111331. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  111332. }
  111333. }
  111334. else {
  111335. if (magFilter !== 9728 /* NEAREST */) {
  111336. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  111337. }
  111338. switch (minFilter) {
  111339. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  111340. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  111341. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  111342. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  111343. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  111344. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  111345. default:
  111346. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  111347. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  111348. }
  111349. }
  111350. };
  111351. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  111352. var buffer = bufferView.buffer;
  111353. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  111354. try {
  111355. switch (componentType) {
  111356. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  111357. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  111358. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  111359. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  111360. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  111361. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  111362. default: throw new Error("Invalid component type " + componentType);
  111363. }
  111364. }
  111365. catch (e) {
  111366. throw new Error(context + ": " + e);
  111367. }
  111368. };
  111369. GLTFLoader._GetNumComponents = function (context, type) {
  111370. switch (type) {
  111371. case "SCALAR": return 1;
  111372. case "VEC2": return 2;
  111373. case "VEC3": return 3;
  111374. case "VEC4": return 4;
  111375. case "MAT2": return 4;
  111376. case "MAT3": return 9;
  111377. case "MAT4": return 16;
  111378. }
  111379. throw new Error(context + ": Invalid type (" + type + ")");
  111380. };
  111381. GLTFLoader._ValidateUri = function (uri) {
  111382. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  111383. };
  111384. GLTFLoader._GetDrawMode = function (context, mode) {
  111385. if (mode == undefined) {
  111386. mode = 4 /* TRIANGLES */;
  111387. }
  111388. switch (mode) {
  111389. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  111390. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  111391. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  111392. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  111393. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  111394. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  111395. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  111396. }
  111397. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  111398. };
  111399. GLTFLoader.prototype._compileMaterialsAsync = function () {
  111400. var _this = this;
  111401. this._parent._startPerformanceCounter("Compile materials");
  111402. var promises = new Array();
  111403. if (this._gltf.materials) {
  111404. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  111405. var material = _a[_i];
  111406. if (material._babylonData) {
  111407. for (var babylonDrawMode in material._babylonData) {
  111408. var babylonData = material._babylonData[babylonDrawMode];
  111409. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  111410. var babylonMesh = _c[_b];
  111411. // Ensure nonUniformScaling is set if necessary.
  111412. babylonMesh.computeWorldMatrix(true);
  111413. var babylonMaterial = babylonData.material;
  111414. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  111415. if (this._parent.useClipPlane) {
  111416. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  111417. }
  111418. }
  111419. }
  111420. }
  111421. }
  111422. }
  111423. return Promise.all(promises).then(function () {
  111424. _this._parent._endPerformanceCounter("Compile materials");
  111425. });
  111426. };
  111427. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  111428. var _this = this;
  111429. this._parent._startPerformanceCounter("Compile shadow generators");
  111430. var promises = new Array();
  111431. var lights = this._babylonScene.lights;
  111432. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  111433. var light = lights_1[_i];
  111434. var generator = light.getShadowGenerator();
  111435. if (generator) {
  111436. promises.push(generator.forceCompilationAsync());
  111437. }
  111438. }
  111439. return Promise.all(promises).then(function () {
  111440. _this._parent._endPerformanceCounter("Compile shadow generators");
  111441. });
  111442. };
  111443. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  111444. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  111445. var name_5 = _a[_i];
  111446. var extension = this._extensions[name_5];
  111447. if (extension.enabled) {
  111448. var promise = actionAsync(extension);
  111449. if (promise) {
  111450. return promise;
  111451. }
  111452. }
  111453. }
  111454. return null;
  111455. };
  111456. GLTFLoader._ExtensionNames = new Array();
  111457. GLTFLoader._ExtensionFactories = {};
  111458. return GLTFLoader;
  111459. }());
  111460. GLTF2.GLTFLoader = GLTFLoader;
  111461. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  111462. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111463. })(BABYLON || (BABYLON = {}));
  111464. //# sourceMappingURL=babylon.glTFLoader.js.map
  111465. var BABYLON;
  111466. (function (BABYLON) {
  111467. var GLTF2;
  111468. (function (GLTF2) {
  111469. /**
  111470. * Abstract class that can be implemented to extend existing glTF loader behavior.
  111471. */
  111472. var GLTFLoaderExtension = /** @class */ (function () {
  111473. /**
  111474. * Creates new GLTFLoaderExtension
  111475. * @param loader defines the GLTFLoader to use
  111476. */
  111477. function GLTFLoaderExtension(loader) {
  111478. /**
  111479. * Gets or sets a boolean indicating if the extension is enabled
  111480. */
  111481. this.enabled = true;
  111482. this._loader = loader;
  111483. }
  111484. /**
  111485. * Release all resources
  111486. */
  111487. GLTFLoaderExtension.prototype.dispose = function () {
  111488. delete this._loader;
  111489. };
  111490. // #region Overridable Methods
  111491. /**
  111492. * Override this method to modify the default behavior for loading scenes.
  111493. * @hidden
  111494. */
  111495. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  111496. /**
  111497. * Override this method to modify the default behavior for loading nodes.
  111498. * @hidden
  111499. */
  111500. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  111501. /**
  111502. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  111503. * @hidden
  111504. */
  111505. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  111506. /**
  111507. * Override this method to modify the default behavior for loading materials.
  111508. * @hidden
  111509. */
  111510. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  111511. /**
  111512. * Override this method to modify the default behavior for loading material properties.
  111513. * @hidden
  111514. */
  111515. GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };
  111516. /**
  111517. * Override this method to modify the default behavior for loading texture infos.
  111518. * @hidden
  111519. */
  111520. GLTFLoaderExtension.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) { return null; };
  111521. /**
  111522. * Override this method to modify the default behavior for loading textures.
  111523. * @hidden
  111524. */
  111525. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, texture, assign) { return null; };
  111526. /**
  111527. * Override this method to modify the default behavior for loading uris.
  111528. * @hidden
  111529. */
  111530. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  111531. // #endregion
  111532. /**
  111533. * Helper method called by a loader extension to load an glTF extension.
  111534. * @hidden
  111535. */
  111536. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  111537. if (!property.extensions) {
  111538. return null;
  111539. }
  111540. var extensions = property.extensions;
  111541. var extension = extensions[this.name];
  111542. if (!extension) {
  111543. return null;
  111544. }
  111545. // Clear out the extension before executing the action to avoid infinite recursion.
  111546. delete extensions[this.name];
  111547. try {
  111548. return actionAsync(context + "/extensions/" + this.name, extension);
  111549. }
  111550. finally {
  111551. // Restore the extension after executing the action.
  111552. extensions[this.name] = extension;
  111553. }
  111554. };
  111555. /**
  111556. * Helper method called by the loader to allow extensions to override loading scenes.
  111557. * @hidden
  111558. */
  111559. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  111560. if (!property.extras) {
  111561. return null;
  111562. }
  111563. var extras = property.extras;
  111564. var value = extras[this.name];
  111565. if (value === undefined) {
  111566. return null;
  111567. }
  111568. // Clear out the extras value before executing the action to avoid infinite recursion.
  111569. delete extras[this.name];
  111570. try {
  111571. return actionAsync(context + "/extras/" + this.name, value);
  111572. }
  111573. finally {
  111574. // Restore the extras value after executing the action.
  111575. extras[this.name] = value;
  111576. }
  111577. };
  111578. /**
  111579. * Helper method called by the loader to allow extensions to override loading scenes.
  111580. * @hidden
  111581. */
  111582. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  111583. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  111584. };
  111585. /**
  111586. * Helper method called by the loader to allow extensions to override loading nodes.
  111587. * @hidden
  111588. */
  111589. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  111590. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  111591. };
  111592. /**
  111593. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  111594. * @hidden
  111595. */
  111596. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  111597. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  111598. };
  111599. /**
  111600. * Helper method called by the loader to allow extensions to override loading materials.
  111601. * @hidden
  111602. */
  111603. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111604. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  111605. };
  111606. /**
  111607. * Helper method called by the loader to allow extensions to override loading material properties.
  111608. * @hidden
  111609. */
  111610. GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {
  111611. return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  111612. };
  111613. /**
  111614. * Helper method called by the loader to allow extensions to override loading texture infos.
  111615. * @hidden
  111616. */
  111617. GLTFLoaderExtension._LoadTextureInfoAsync = function (loader, context, textureInfo, assign) {
  111618. return loader._applyExtensions(function (extension) { return extension._loadTextureInfoAsync(context, textureInfo, assign); });
  111619. };
  111620. /**
  111621. * Helper method called by the loader to allow extensions to override loading textures.
  111622. * @hidden
  111623. */
  111624. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, texture, assign) {
  111625. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, texture, assign); });
  111626. };
  111627. /**
  111628. * Helper method called by the loader to allow extensions to override loading uris.
  111629. * @hidden
  111630. */
  111631. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  111632. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  111633. };
  111634. return GLTFLoaderExtension;
  111635. }());
  111636. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  111637. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111638. })(BABYLON || (BABYLON = {}));
  111639. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  111640. var BABYLON;
  111641. (function (BABYLON) {
  111642. var GLTF2;
  111643. (function (GLTF2) {
  111644. var Extensions;
  111645. (function (Extensions) {
  111646. var NAME = "MSFT_lod";
  111647. /**
  111648. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  111649. */
  111650. var MSFT_lod = /** @class */ (function (_super) {
  111651. __extends(MSFT_lod, _super);
  111652. function MSFT_lod(loader) {
  111653. var _this = _super.call(this, loader) || this;
  111654. _this.name = NAME;
  111655. /**
  111656. * Maximum number of LODs to load, starting from the lowest LOD.
  111657. */
  111658. _this.maxLODsToLoad = Number.MAX_VALUE;
  111659. /**
  111660. * Observable raised when all node LODs of one level are loaded.
  111661. * The event data is the index of the loaded LOD starting from zero.
  111662. * Dispose the loader to cancel the loading of the next level of LODs.
  111663. */
  111664. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  111665. /**
  111666. * Observable raised when all material LODs of one level are loaded.
  111667. * The event data is the index of the loaded LOD starting from zero.
  111668. * Dispose the loader to cancel the loading of the next level of LODs.
  111669. */
  111670. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  111671. _this._nodeIndexLOD = null;
  111672. _this._nodeSignalLODs = new Array();
  111673. _this._nodePromiseLODs = new Array();
  111674. _this._materialIndexLOD = null;
  111675. _this._materialSignalLODs = new Array();
  111676. _this._materialPromiseLODs = new Array();
  111677. _this._loader._readyPromise.then(function () {
  111678. var _loop_1 = function (indexLOD) {
  111679. var promise = Promise.all(_this._nodePromiseLODs[indexLOD]).then(function () {
  111680. if (indexLOD !== 0) {
  111681. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  111682. }
  111683. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  111684. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  111685. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  111686. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  111687. _this._nodeSignalLODs[indexLOD].resolve();
  111688. }
  111689. });
  111690. _this._loader._completePromises.push(promise);
  111691. };
  111692. for (var indexLOD = 0; indexLOD < _this._nodePromiseLODs.length; indexLOD++) {
  111693. _loop_1(indexLOD);
  111694. }
  111695. var _loop_2 = function (indexLOD) {
  111696. var promise = Promise.all(_this._materialPromiseLODs[indexLOD]).then(function () {
  111697. if (indexLOD !== 0) {
  111698. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  111699. }
  111700. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  111701. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  111702. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  111703. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  111704. _this._materialSignalLODs[indexLOD].resolve();
  111705. }
  111706. });
  111707. _this._loader._completePromises.push(promise);
  111708. };
  111709. for (var indexLOD = 0; indexLOD < _this._materialPromiseLODs.length; indexLOD++) {
  111710. _loop_2(indexLOD);
  111711. }
  111712. });
  111713. return _this;
  111714. }
  111715. MSFT_lod.prototype.dispose = function () {
  111716. _super.prototype.dispose.call(this);
  111717. this._nodeIndexLOD = null;
  111718. this._nodeSignalLODs.length = 0;
  111719. this._nodePromiseLODs.length = 0;
  111720. this._materialIndexLOD = null;
  111721. this._materialSignalLODs.length = 0;
  111722. this._materialPromiseLODs.length = 0;
  111723. this.onMaterialLODsLoadedObservable.clear();
  111724. this.onNodeLODsLoadedObservable.clear();
  111725. };
  111726. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  111727. var _this = this;
  111728. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  111729. var firstPromise;
  111730. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  111731. _this._loader._parent._logOpen("" + extensionContext);
  111732. var _loop_3 = function (indexLOD) {
  111733. var nodeLOD = nodeLODs[indexLOD];
  111734. if (indexLOD !== 0) {
  111735. _this._nodeIndexLOD = indexLOD;
  111736. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  111737. }
  111738. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  111739. if (indexLOD !== 0) {
  111740. var previousNodeLOD = nodeLODs[indexLOD - 1];
  111741. if (previousNodeLOD._babylonMesh) {
  111742. previousNodeLOD._babylonMesh.dispose();
  111743. delete previousNodeLOD._babylonMesh;
  111744. _this._disposeUnusedMaterials();
  111745. }
  111746. }
  111747. });
  111748. if (indexLOD === 0) {
  111749. firstPromise = promise;
  111750. }
  111751. else {
  111752. _this._nodeIndexLOD = null;
  111753. }
  111754. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  111755. _this._nodePromiseLODs[indexLOD].push(promise);
  111756. };
  111757. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  111758. _loop_3(indexLOD);
  111759. }
  111760. _this._loader._parent._logClose();
  111761. return firstPromise;
  111762. });
  111763. };
  111764. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111765. var _this = this;
  111766. // Don't load material LODs if already loading a node LOD.
  111767. if (this._nodeIndexLOD) {
  111768. return null;
  111769. }
  111770. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  111771. var firstPromise;
  111772. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  111773. _this._loader._parent._logOpen("" + extensionContext);
  111774. var _loop_4 = function (indexLOD) {
  111775. var materialLOD = materialLODs[indexLOD];
  111776. if (indexLOD !== 0) {
  111777. _this._materialIndexLOD = indexLOD;
  111778. }
  111779. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  111780. if (indexLOD !== 0) {
  111781. var babylonDataLOD = materialLOD._babylonData;
  111782. assign(babylonDataLOD[babylonDrawMode].material);
  111783. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  111784. if (previousBabylonDataLOD[babylonDrawMode]) {
  111785. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  111786. delete previousBabylonDataLOD[babylonDrawMode];
  111787. }
  111788. }
  111789. });
  111790. if (indexLOD === 0) {
  111791. firstPromise = promise;
  111792. }
  111793. else {
  111794. _this._materialIndexLOD = null;
  111795. }
  111796. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  111797. _this._materialPromiseLODs[indexLOD].push(promise);
  111798. };
  111799. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  111800. _loop_4(indexLOD);
  111801. }
  111802. _this._loader._parent._logClose();
  111803. return firstPromise;
  111804. });
  111805. };
  111806. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  111807. var _this = this;
  111808. // Defer the loading of uris if loading a material or node LOD.
  111809. if (this._materialIndexLOD !== null) {
  111810. this._loader._parent._log("deferred");
  111811. var previousIndexLOD = this._materialIndexLOD - 1;
  111812. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  111813. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  111814. return _this._loader._loadUriAsync(context, uri);
  111815. });
  111816. }
  111817. else if (this._nodeIndexLOD !== null) {
  111818. this._loader._parent._log("deferred");
  111819. var previousIndexLOD = this._nodeIndexLOD - 1;
  111820. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  111821. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  111822. return _this._loader._loadUriAsync(context, uri);
  111823. });
  111824. }
  111825. return null;
  111826. };
  111827. /**
  111828. * Gets an array of LOD properties from lowest to highest.
  111829. */
  111830. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  111831. if (this.maxLODsToLoad <= 0) {
  111832. throw new Error("maxLODsToLoad must be greater than zero");
  111833. }
  111834. var properties = new Array();
  111835. for (var i = ids.length - 1; i >= 0; i--) {
  111836. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  111837. if (properties.length === this.maxLODsToLoad) {
  111838. return properties;
  111839. }
  111840. }
  111841. properties.push(property);
  111842. return properties;
  111843. };
  111844. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  111845. var materials = this._loader._gltf.materials;
  111846. if (materials) {
  111847. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  111848. var material = materials_1[_i];
  111849. if (material._babylonData) {
  111850. for (var drawMode in material._babylonData) {
  111851. var babylonData = material._babylonData[drawMode];
  111852. if (babylonData.meshes.length === 0) {
  111853. babylonData.material.dispose(false, true);
  111854. delete material._babylonData[drawMode];
  111855. }
  111856. }
  111857. }
  111858. }
  111859. }
  111860. };
  111861. return MSFT_lod;
  111862. }(GLTF2.GLTFLoaderExtension));
  111863. Extensions.MSFT_lod = MSFT_lod;
  111864. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  111865. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111866. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111867. })(BABYLON || (BABYLON = {}));
  111868. //# sourceMappingURL=MSFT_lod.js.map
  111869. var BABYLON;
  111870. (function (BABYLON) {
  111871. var GLTF2;
  111872. (function (GLTF2) {
  111873. var Extensions;
  111874. (function (Extensions) {
  111875. var NAME = "MSFT_minecraftMesh";
  111876. /** @hidden */
  111877. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  111878. __extends(MSFT_minecraftMesh, _super);
  111879. function MSFT_minecraftMesh() {
  111880. var _this = _super !== null && _super.apply(this, arguments) || this;
  111881. _this.name = NAME;
  111882. return _this;
  111883. }
  111884. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111885. var _this = this;
  111886. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  111887. if (value) {
  111888. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  111889. if (babylonMaterial.needAlphaBlending()) {
  111890. babylonMaterial.forceDepthWrite = true;
  111891. babylonMaterial.separateCullingPass = true;
  111892. }
  111893. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  111894. babylonMaterial.twoSidedLighting = true;
  111895. assign(babylonMaterial);
  111896. });
  111897. }
  111898. return null;
  111899. });
  111900. };
  111901. return MSFT_minecraftMesh;
  111902. }(GLTF2.GLTFLoaderExtension));
  111903. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  111904. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  111905. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111906. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111907. })(BABYLON || (BABYLON = {}));
  111908. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  111909. var BABYLON;
  111910. (function (BABYLON) {
  111911. var GLTF2;
  111912. (function (GLTF2) {
  111913. var Extensions;
  111914. (function (Extensions) {
  111915. var NAME = "MSFT_sRGBFactors";
  111916. /** @hidden */
  111917. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  111918. __extends(MSFT_sRGBFactors, _super);
  111919. function MSFT_sRGBFactors() {
  111920. var _this = _super !== null && _super.apply(this, arguments) || this;
  111921. _this.name = NAME;
  111922. return _this;
  111923. }
  111924. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111925. var _this = this;
  111926. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  111927. if (value) {
  111928. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  111929. if (!babylonMaterial.albedoTexture) {
  111930. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  111931. }
  111932. if (!babylonMaterial.reflectivityTexture) {
  111933. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  111934. }
  111935. assign(babylonMaterial);
  111936. });
  111937. }
  111938. return null;
  111939. });
  111940. };
  111941. return MSFT_sRGBFactors;
  111942. }(GLTF2.GLTFLoaderExtension));
  111943. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  111944. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  111945. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111946. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111947. })(BABYLON || (BABYLON = {}));
  111948. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  111949. var BABYLON;
  111950. (function (BABYLON) {
  111951. var GLTF2;
  111952. (function (GLTF2) {
  111953. var Extensions;
  111954. (function (Extensions) {
  111955. var NAME = "KHR_draco_mesh_compression";
  111956. /**
  111957. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  111958. */
  111959. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  111960. __extends(KHR_draco_mesh_compression, _super);
  111961. function KHR_draco_mesh_compression(loader) {
  111962. var _this = _super.call(this, loader) || this;
  111963. _this.name = NAME;
  111964. _this._dracoCompression = null;
  111965. // Disable extension if decoder is not available.
  111966. if (!BABYLON.DracoCompression.DecoderAvailable) {
  111967. _this.enabled = false;
  111968. }
  111969. return _this;
  111970. }
  111971. KHR_draco_mesh_compression.prototype.dispose = function () {
  111972. if (this._dracoCompression) {
  111973. this._dracoCompression.dispose();
  111974. }
  111975. _super.prototype.dispose.call(this);
  111976. };
  111977. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  111978. var _this = this;
  111979. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  111980. if (primitive.mode != undefined) {
  111981. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  111982. primitive.mode !== 4 /* TRIANGLES */) {
  111983. throw new Error(context + ": Unsupported mode " + primitive.mode);
  111984. }
  111985. // TODO: handle triangle strips
  111986. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  111987. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  111988. }
  111989. }
  111990. var attributes = {};
  111991. var loadAttribute = function (name, kind) {
  111992. var uniqueId = extension.attributes[name];
  111993. if (uniqueId == undefined) {
  111994. return;
  111995. }
  111996. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  111997. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  111998. babylonMesh._delayInfo.push(kind);
  111999. }
  112000. attributes[kind] = uniqueId;
  112001. };
  112002. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  112003. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  112004. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  112005. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  112006. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  112007. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  112008. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  112009. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  112010. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  112011. if (!bufferView._dracoBabylonGeometry) {
  112012. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  112013. if (!_this._dracoCompression) {
  112014. _this._dracoCompression = new BABYLON.DracoCompression();
  112015. }
  112016. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  112017. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  112018. babylonVertexData.applyToGeometry(babylonGeometry);
  112019. return babylonGeometry;
  112020. }).catch(function (error) {
  112021. throw new Error(context + ": " + error.message);
  112022. });
  112023. });
  112024. }
  112025. return bufferView._dracoBabylonGeometry;
  112026. });
  112027. };
  112028. return KHR_draco_mesh_compression;
  112029. }(GLTF2.GLTFLoaderExtension));
  112030. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  112031. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  112032. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112033. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112034. })(BABYLON || (BABYLON = {}));
  112035. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  112036. var BABYLON;
  112037. (function (BABYLON) {
  112038. var GLTF2;
  112039. (function (GLTF2) {
  112040. var Extensions;
  112041. (function (Extensions) {
  112042. var NAME = "KHR_materials_pbrSpecularGlossiness";
  112043. /**
  112044. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  112045. */
  112046. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  112047. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  112048. function KHR_materials_pbrSpecularGlossiness() {
  112049. var _this = _super !== null && _super.apply(this, arguments) || this;
  112050. _this.name = NAME;
  112051. return _this;
  112052. }
  112053. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  112054. var _this = this;
  112055. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  112056. var promises = new Array();
  112057. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  112058. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  112059. return Promise.all(promises).then(function () { });
  112060. });
  112061. };
  112062. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  112063. var promises = new Array();
  112064. if (properties.diffuseFactor) {
  112065. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  112066. babylonMaterial.alpha = properties.diffuseFactor[3];
  112067. }
  112068. else {
  112069. babylonMaterial.albedoColor = BABYLON.Color3.White();
  112070. }
  112071. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  112072. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  112073. if (properties.diffuseTexture) {
  112074. promises.push(this._loader._loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  112075. babylonMaterial.albedoTexture = texture;
  112076. }));
  112077. }
  112078. if (properties.specularGlossinessTexture) {
  112079. promises.push(this._loader._loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  112080. babylonMaterial.reflectivityTexture = texture;
  112081. }));
  112082. babylonMaterial.reflectivityTexture.hasAlpha = true;
  112083. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  112084. }
  112085. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  112086. return Promise.all(promises).then(function () { });
  112087. };
  112088. return KHR_materials_pbrSpecularGlossiness;
  112089. }(GLTF2.GLTFLoaderExtension));
  112090. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  112091. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  112092. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112093. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112094. })(BABYLON || (BABYLON = {}));
  112095. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  112096. var BABYLON;
  112097. (function (BABYLON) {
  112098. var GLTF2;
  112099. (function (GLTF2) {
  112100. var Extensions;
  112101. (function (Extensions) {
  112102. var NAME = "KHR_materials_unlit";
  112103. /**
  112104. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  112105. */
  112106. var KHR_materials_unlit = /** @class */ (function (_super) {
  112107. __extends(KHR_materials_unlit, _super);
  112108. function KHR_materials_unlit() {
  112109. var _this = _super !== null && _super.apply(this, arguments) || this;
  112110. _this.name = NAME;
  112111. return _this;
  112112. }
  112113. KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  112114. var _this = this;
  112115. return this._loadExtensionAsync(context, material, function () {
  112116. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  112117. });
  112118. };
  112119. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  112120. var promises = new Array();
  112121. babylonMaterial.unlit = true;
  112122. // Ensure metallic workflow
  112123. babylonMaterial.metallic = 1;
  112124. babylonMaterial.roughness = 1;
  112125. var properties = material.pbrMetallicRoughness;
  112126. if (properties) {
  112127. if (properties.baseColorFactor) {
  112128. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  112129. babylonMaterial.alpha = properties.baseColorFactor[3];
  112130. }
  112131. else {
  112132. babylonMaterial.albedoColor = BABYLON.Color3.White();
  112133. }
  112134. if (properties.baseColorTexture) {
  112135. promises.push(this._loader._loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  112136. babylonMaterial.albedoTexture = texture;
  112137. }));
  112138. }
  112139. }
  112140. if (material.doubleSided) {
  112141. babylonMaterial.backFaceCulling = false;
  112142. babylonMaterial.twoSidedLighting = true;
  112143. }
  112144. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  112145. return Promise.all(promises).then(function () { });
  112146. };
  112147. return KHR_materials_unlit;
  112148. }(GLTF2.GLTFLoaderExtension));
  112149. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  112150. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  112151. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112152. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112153. })(BABYLON || (BABYLON = {}));
  112154. //# sourceMappingURL=KHR_materials_unlit.js.map
  112155. var BABYLON;
  112156. (function (BABYLON) {
  112157. var GLTF2;
  112158. (function (GLTF2) {
  112159. var Extensions;
  112160. (function (Extensions) {
  112161. var NAME = "KHR_lights";
  112162. var LightType;
  112163. (function (LightType) {
  112164. LightType["AMBIENT"] = "ambient";
  112165. LightType["DIRECTIONAL"] = "directional";
  112166. LightType["POINT"] = "point";
  112167. LightType["SPOT"] = "spot";
  112168. })(LightType || (LightType = {}));
  112169. /**
  112170. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  112171. */
  112172. var KHR_lights = /** @class */ (function (_super) {
  112173. __extends(KHR_lights, _super);
  112174. function KHR_lights() {
  112175. var _this = _super !== null && _super.apply(this, arguments) || this;
  112176. _this.name = NAME;
  112177. return _this;
  112178. }
  112179. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  112180. var _this = this;
  112181. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  112182. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  112183. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  112184. if (light.type !== LightType.AMBIENT) {
  112185. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  112186. }
  112187. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  112188. return promise;
  112189. });
  112190. };
  112191. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  112192. var _this = this;
  112193. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  112194. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  112195. var babylonLight;
  112196. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  112197. var name = node._babylonMesh.name;
  112198. switch (light.type) {
  112199. case LightType.AMBIENT: {
  112200. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  112201. }
  112202. case LightType.DIRECTIONAL: {
  112203. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  112204. break;
  112205. }
  112206. case LightType.POINT: {
  112207. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  112208. break;
  112209. }
  112210. case LightType.SPOT: {
  112211. // TODO: support inner and outer cone angles
  112212. //const innerConeAngle = spotLight.innerConeAngle || 0;
  112213. var outerConeAngle = light.spot && light.spot.outerConeAngle || Math.PI / 4;
  112214. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  112215. break;
  112216. }
  112217. default: {
  112218. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  112219. }
  112220. }
  112221. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  112222. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  112223. babylonLight.parent = node._babylonMesh;
  112224. return promise;
  112225. });
  112226. };
  112227. Object.defineProperty(KHR_lights.prototype, "_lights", {
  112228. get: function () {
  112229. var extensions = this._loader._gltf.extensions;
  112230. if (!extensions || !extensions[this.name]) {
  112231. throw new Error("#/extensions: '" + this.name + "' not found");
  112232. }
  112233. var extension = extensions[this.name];
  112234. return extension.lights;
  112235. },
  112236. enumerable: true,
  112237. configurable: true
  112238. });
  112239. return KHR_lights;
  112240. }(GLTF2.GLTFLoaderExtension));
  112241. Extensions.KHR_lights = KHR_lights;
  112242. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  112243. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112244. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112245. })(BABYLON || (BABYLON = {}));
  112246. var BABYLON;
  112247. (function (BABYLON) {
  112248. var GLTF2;
  112249. (function (GLTF2) {
  112250. var Extensions;
  112251. (function (Extensions) {
  112252. var NAME = "KHR_texture_transform";
  112253. /**
  112254. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  112255. */
  112256. var KHR_texture_transform = /** @class */ (function (_super) {
  112257. __extends(KHR_texture_transform, _super);
  112258. function KHR_texture_transform() {
  112259. var _this = _super !== null && _super.apply(this, arguments) || this;
  112260. _this.name = NAME;
  112261. return _this;
  112262. }
  112263. KHR_texture_transform.prototype._loadTextureInfoAsync = function (context, textureInfo, assign) {
  112264. var _this = this;
  112265. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  112266. return _this._loader._loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  112267. if (extension.offset) {
  112268. babylonTexture.uOffset = extension.offset[0];
  112269. babylonTexture.vOffset = extension.offset[1];
  112270. }
  112271. // Always rotate around the origin.
  112272. babylonTexture.uRotationCenter = 0;
  112273. babylonTexture.vRotationCenter = 0;
  112274. if (extension.rotation) {
  112275. babylonTexture.wAng = -extension.rotation;
  112276. }
  112277. if (extension.scale) {
  112278. babylonTexture.uScale = extension.scale[0];
  112279. babylonTexture.vScale = extension.scale[1];
  112280. }
  112281. if (extension.texCoord != undefined) {
  112282. babylonTexture.coordinatesIndex = extension.texCoord;
  112283. }
  112284. assign(babylonTexture);
  112285. });
  112286. });
  112287. };
  112288. return KHR_texture_transform;
  112289. }(GLTF2.GLTFLoaderExtension));
  112290. Extensions.KHR_texture_transform = KHR_texture_transform;
  112291. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  112292. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112293. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112294. })(BABYLON || (BABYLON = {}));
  112295. var BABYLON;
  112296. (function (BABYLON) {
  112297. var GLTF2;
  112298. (function (GLTF2) {
  112299. var Extensions;
  112300. (function (Extensions) {
  112301. var NAME = "EXT_lights_imageBased";
  112302. /**
  112303. * [Specification](TODO) (Experimental)
  112304. */
  112305. var EXT_lights_imageBased = /** @class */ (function (_super) {
  112306. __extends(EXT_lights_imageBased, _super);
  112307. function EXT_lights_imageBased() {
  112308. var _this = _super !== null && _super.apply(this, arguments) || this;
  112309. _this.name = NAME;
  112310. return _this;
  112311. }
  112312. EXT_lights_imageBased.prototype._loadSceneAsync = function (context, scene) {
  112313. var _this = this;
  112314. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  112315. var promises = new Array();
  112316. promises.push(_this._loader._loadSceneAsync(context, scene));
  112317. _this._loader._parent._logOpen("" + extensionContext);
  112318. var light = GLTF2.GLTFLoader._GetProperty(extensionContext + "/light", _this._lights, extension.light);
  112319. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  112320. _this._loader._babylonScene.environmentTexture = texture;
  112321. }));
  112322. _this._loader._parent._logClose();
  112323. return Promise.all(promises).then(function () { });
  112324. });
  112325. };
  112326. EXT_lights_imageBased.prototype._loadLightAsync = function (context, light) {
  112327. var _this = this;
  112328. if (!light._loaded) {
  112329. var promises = new Array();
  112330. this._loader._parent._logOpen("" + context);
  112331. var imageData_1 = new Array(light.specularImages.length);
  112332. var _loop_1 = function (mipmap) {
  112333. var faces = light.specularImages[mipmap];
  112334. imageData_1[mipmap] = new Array(faces.length);
  112335. var _loop_2 = function (face) {
  112336. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  112337. this_1._loader._parent._logOpen("" + specularImageContext);
  112338. var index = faces[face];
  112339. var image = GLTF2.GLTFLoader._GetProperty(specularImageContext, this_1._loader._gltf.images, index);
  112340. promises.push(this_1._loader._loadImageAsync("#/images/" + index, image).then(function (data) {
  112341. imageData_1[mipmap][face] = data;
  112342. }));
  112343. this_1._loader._parent._logClose();
  112344. };
  112345. for (var face = 0; face < faces.length; face++) {
  112346. _loop_2(face);
  112347. }
  112348. };
  112349. var this_1 = this;
  112350. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  112351. _loop_1(mipmap);
  112352. }
  112353. this._loader._parent._logClose();
  112354. light._loaded = Promise.all(promises).then(function () {
  112355. var size = Math.pow(2, imageData_1.length - 1);
  112356. var babylonTexture = new BABYLON.RawCubeTexture(_this._loader._babylonScene, null, size);
  112357. light._babylonTexture = babylonTexture;
  112358. if (light.intensity != undefined) {
  112359. babylonTexture.level = light.intensity;
  112360. }
  112361. if (light.rotation) {
  112362. var rotation = BABYLON.Quaternion.FromArray(light.rotation);
  112363. // Invert the rotation so that positive rotation is counter-clockwise.
  112364. if (!_this._loader._babylonScene.useRightHandedSystem) {
  112365. rotation = BABYLON.Quaternion.Inverse(rotation);
  112366. }
  112367. BABYLON.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  112368. }
  112369. var sphericalHarmonics = BABYLON.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  112370. sphericalHarmonics.scale(light.intensity);
  112371. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  112372. var sphericalPolynomial = BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  112373. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial);
  112374. });
  112375. }
  112376. return light._loaded.then(function () {
  112377. return light._babylonTexture;
  112378. });
  112379. };
  112380. Object.defineProperty(EXT_lights_imageBased.prototype, "_lights", {
  112381. get: function () {
  112382. var extensions = this._loader._gltf.extensions;
  112383. if (!extensions || !extensions[this.name]) {
  112384. throw new Error("#/extensions: '" + this.name + "' not found");
  112385. }
  112386. var extension = extensions[this.name];
  112387. return extension.lights;
  112388. },
  112389. enumerable: true,
  112390. configurable: true
  112391. });
  112392. return EXT_lights_imageBased;
  112393. }(GLTF2.GLTFLoaderExtension));
  112394. Extensions.EXT_lights_imageBased = EXT_lights_imageBased;
  112395. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new EXT_lights_imageBased(loader); });
  112396. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112397. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112398. })(BABYLON || (BABYLON = {}));
  112399. return BABYLON;
  112400. });
  112401. /***/ }),
  112402. /* 14 */
  112403. /***/ (function(module, exports, __webpack_require__) {
  112404. "use strict";
  112405. function __export(m) {
  112406. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  112407. }
  112408. Object.defineProperty(exports, "__esModule", { value: true });
  112409. __export(__webpack_require__(11));
  112410. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  112411. /***/ }),
  112412. /* 15 */
  112413. /***/ (function(module, exports, __webpack_require__) {
  112414. "use strict";
  112415. Object.defineProperty(exports, "__esModule", { value: true });
  112416. var babylonjs_1 = __webpack_require__(0);
  112417. /**
  112418. * A minimal WebGL cubemap descriptor
  112419. */
  112420. var TextureCube = /** @class */ (function () {
  112421. /**
  112422. * constructor
  112423. * @param internalFormat WebGL pixel format for the texture on the GPU
  112424. * @param type WebGL pixel type of the supplied data and texture on the GPU
  112425. * @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
  112426. */
  112427. function TextureCube(internalFormat, type, source) {
  112428. if (source === void 0) { source = []; }
  112429. this.internalFormat = internalFormat;
  112430. this.type = type;
  112431. this.source = source;
  112432. }
  112433. Object.defineProperty(TextureCube.prototype, "Width", {
  112434. /**
  112435. * Returns the width of a face of the texture or 0 if not available
  112436. */
  112437. get: function () {
  112438. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  112439. },
  112440. enumerable: true,
  112441. configurable: true
  112442. });
  112443. Object.defineProperty(TextureCube.prototype, "Height", {
  112444. /**
  112445. * Returns the height of a face of the texture or 0 if not available
  112446. */
  112447. get: function () {
  112448. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  112449. },
  112450. enumerable: true,
  112451. configurable: true
  112452. });
  112453. return TextureCube;
  112454. }());
  112455. exports.TextureCube = TextureCube;
  112456. /**
  112457. * A static class providing methods to aid working with Bablyon textures.
  112458. */
  112459. var TextureUtils = /** @class */ (function () {
  112460. function TextureUtils() {
  112461. }
  112462. /**
  112463. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  112464. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  112465. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  112466. * @param scene A Babylon Scene instance
  112467. * @param textureCube A Spectre TextureCube object
  112468. * @param parameters WebGL texture sampling parameters
  112469. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  112470. * @param environment Specifies that the texture will be used as an environment
  112471. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  112472. * @return Babylon cube texture
  112473. */
  112474. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  112475. if (environment === void 0) { environment = false; }
  112476. if (singleLod === void 0) { singleLod = false; }
  112477. if (!textureCube)
  112478. throw new Error("no texture cube provided");
  112479. var parameters;
  112480. if (environment) {
  112481. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  112482. }
  112483. else {
  112484. parameters = {
  112485. magFilter: 9728 /* NEAREST */,
  112486. minFilter: 9728 /* NEAREST */,
  112487. wrapS: 33071 /* CLAMP_TO_EDGE */,
  112488. wrapT: 33071 /* CLAMP_TO_EDGE */
  112489. };
  112490. }
  112491. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  112492. var babylonTexture = textureCube[key];
  112493. if (!babylonTexture) {
  112494. //initialize babylon texture
  112495. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  112496. if (environment) {
  112497. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  112498. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  112499. }
  112500. babylonTexture.gammaSpace = false;
  112501. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  112502. var glTexture_1 = internalTexture_1._webGLTexture;
  112503. //babylon properties
  112504. internalTexture_1.isCube = true;
  112505. internalTexture_1.generateMipMaps = false;
  112506. babylonTexture._texture = internalTexture_1;
  112507. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  112508. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  112509. var texturesUploaded_1 = 0;
  112510. var textureComplete = function () {
  112511. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  112512. };
  112513. var uploadFace = function (i, level, face) {
  112514. if (!glTexture_1)
  112515. return;
  112516. if (i === 0 && level === 0) {
  112517. internalTexture_1.width = face.width;
  112518. internalTexture_1.height = face.height;
  112519. }
  112520. var gl = (scene.getEngine())._gl;
  112521. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  112522. scene.getEngine()._unpackFlipY(false);
  112523. if (face instanceof HTMLElement || face instanceof ImageData) {
  112524. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  112525. }
  112526. else {
  112527. var textureData = face;
  112528. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  112529. }
  112530. texturesUploaded_1++;
  112531. if (textureComplete()) {
  112532. //generate mipmaps
  112533. if (automaticMipmaps) {
  112534. var w = face.width;
  112535. var h = face.height;
  112536. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  112537. if (isPot) {
  112538. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  112539. }
  112540. }
  112541. // Upload Separate lods in case there is no support for texture lod.
  112542. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  112543. var mipSlices = 3;
  112544. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  112545. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  112546. var lod = textureCube[lodKey];
  112547. //initialize lod texture if it doesn't already exist
  112548. if (lod == null && textureCube.Width) {
  112549. //compute LOD from even spacing in smoothness (matching shader calculation)
  112550. var smoothness = i_1 / (mipSlices - 1);
  112551. var roughness = 1 - smoothness;
  112552. var kMinimumVariance = 0.0005;
  112553. var alphaG = roughness * roughness + kMinimumVariance;
  112554. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  112555. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  112556. var maxLODIndex = textureCube.source.length - 1;
  112557. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  112558. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  112559. if (i_1 === 0) {
  112560. internalTexture_1._lodTextureLow = lod;
  112561. }
  112562. else if (i_1 === 1) {
  112563. internalTexture_1._lodTextureMid = lod;
  112564. }
  112565. else {
  112566. internalTexture_1._lodTextureHigh = lod;
  112567. }
  112568. textureCube[lodKey] = lod;
  112569. }
  112570. }
  112571. }
  112572. internalTexture_1.isReady = true;
  112573. }
  112574. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  112575. scene.getEngine().resetTextureCache();
  112576. };
  112577. var _loop_1 = function (i) {
  112578. var faces = textureCube.source[i];
  112579. var _loop_2 = function (j) {
  112580. var face = faces[j];
  112581. if (face instanceof HTMLImageElement && !face.complete) {
  112582. face.addEventListener('load', function () {
  112583. uploadFace(j, i, face);
  112584. }, false);
  112585. }
  112586. else {
  112587. uploadFace(j, i, face);
  112588. }
  112589. };
  112590. for (var j = 0; j < faces.length; j++) {
  112591. _loop_2(j);
  112592. }
  112593. };
  112594. for (var i = 0; i <= maxMipLevel_1; i++) {
  112595. _loop_1(i);
  112596. }
  112597. scene.getEngine().resetTextureCache();
  112598. babylonTexture.isReady = function () {
  112599. return textureComplete();
  112600. };
  112601. textureCube[key] = babylonTexture;
  112602. }
  112603. return babylonTexture;
  112604. };
  112605. /**
  112606. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  112607. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  112608. * @param parameters Spectre SamplingParameters to apply
  112609. */
  112610. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  112611. var scene = babylonTexture.getScene();
  112612. if (!scene)
  112613. return;
  112614. var gl = (scene.getEngine())._gl;
  112615. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  112616. var internalTexture = babylonTexture._texture;
  112617. if (!internalTexture)
  112618. return;
  112619. var glTexture = internalTexture._webGLTexture;
  112620. gl.bindTexture(target, glTexture);
  112621. if (parameters.magFilter != null)
  112622. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  112623. if (parameters.minFilter != null)
  112624. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  112625. if (parameters.wrapS != null)
  112626. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  112627. if (parameters.wrapT != null)
  112628. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  112629. //set babylon wrap modes from sampling parameter
  112630. switch (parameters.wrapS) {
  112631. case 10497 /* REPEAT */:
  112632. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  112633. break;
  112634. case 33071 /* CLAMP_TO_EDGE */:
  112635. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  112636. break;
  112637. case 33648 /* MIRRORED_REPEAT */:
  112638. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  112639. break;
  112640. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  112641. }
  112642. switch (parameters.wrapT) {
  112643. case 10497 /* REPEAT */:
  112644. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  112645. break;
  112646. case 33071 /* CLAMP_TO_EDGE */:
  112647. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  112648. break;
  112649. case 33648 /* MIRRORED_REPEAT */:
  112650. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  112651. break;
  112652. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  112653. }
  112654. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  112655. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  112656. if (anisotropicExt) {
  112657. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  112658. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  112659. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  112660. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  112661. }
  112662. }
  112663. gl.bindTexture(target, null);
  112664. scene.getEngine().resetTextureCache();
  112665. };
  112666. /**
  112667. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  112668. */
  112669. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  112670. /**
  112671. * Controls anisotropic filtering for deserialized textures.
  112672. */
  112673. TextureUtils.MaxAnisotropy = 4;
  112674. TextureUtils._EnvironmentSampling = {
  112675. magFilter: 9729 /* LINEAR */,
  112676. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  112677. wrapS: 33071 /* CLAMP_TO_EDGE */,
  112678. wrapT: 33071 /* CLAMP_TO_EDGE */,
  112679. maxAnisotropy: 1
  112680. };
  112681. TextureUtils._EnvironmentSingleMipSampling = {
  112682. magFilter: 9729 /* LINEAR */,
  112683. minFilter: 9729 /* LINEAR */,
  112684. wrapS: 33071 /* CLAMP_TO_EDGE */,
  112685. wrapT: 33071 /* CLAMP_TO_EDGE */,
  112686. maxAnisotropy: 1
  112687. };
  112688. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  112689. /**
  112690. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  112691. */
  112692. TextureUtils.EnvironmentLODScale = 0.8;
  112693. /**
  112694. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  112695. */
  112696. TextureUtils.EnvironmentLODOffset = 1.0;
  112697. return TextureUtils;
  112698. }());
  112699. exports.TextureUtils = TextureUtils;
  112700. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGV4dHVyZS5qcyIsInN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BMFBDO0FBMVBZLG9DQUFZIn0=
  112701. /***/ }),
  112702. /* 16 */
  112703. /***/ (function(module, exports, __webpack_require__) {
  112704. "use strict";
  112705. Object.defineProperty(exports, "__esModule", { value: true });
  112706. var extended_1 = __webpack_require__(62);
  112707. var cache = {};
  112708. /**
  112709. *
  112710. * @param name the name of the custom optimizer configuration
  112711. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  112712. */
  112713. function getCustomOptimizerByName(name, upgrade) {
  112714. if (!cache[name]) {
  112715. switch (name) {
  112716. case 'extended':
  112717. if (upgrade) {
  112718. return extended_1.extendedUpgrade;
  112719. }
  112720. else {
  112721. return extended_1.extendedDegrade;
  112722. }
  112723. }
  112724. }
  112725. return cache[name];
  112726. }
  112727. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  112728. function registerCustomOptimizer(name, optimizer) {
  112729. cache[name] = optimizer;
  112730. }
  112731. exports.registerCustomOptimizer = registerCustomOptimizer;
  112732. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDO0FBRUQsaUNBQXdDLElBQVksRUFBRSxTQUFrRDtJQUNwRyxLQUFLLENBQUMsSUFBSSxDQUFDLEdBQUcsU0FBUyxDQUFDO0FBQzVCLENBQUM7QUFGRCwwREFFQyJ9
  112733. /***/ }),
  112734. /* 17 */
  112735. /***/ (function(module, exports, __webpack_require__) {
  112736. /**!
  112737. @license
  112738. handlebars v4.0.11
  112739. Copyright (C) 2011-2017 by Yehuda Katz
  112740. Permission is hereby granted, free of charge, to any person obtaining a copy
  112741. of this software and associated documentation files (the "Software"), to deal
  112742. in the Software without restriction, including without limitation the rights
  112743. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  112744. copies of the Software, and to permit persons to whom the Software is
  112745. furnished to do so, subject to the following conditions:
  112746. The above copyright notice and this permission notice shall be included in
  112747. all copies or substantial portions of the Software.
  112748. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  112749. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  112750. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  112751. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  112752. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  112753. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  112754. THE SOFTWARE.
  112755. */
  112756. (function webpackUniversalModuleDefinition(root, factory) {
  112757. if(true)
  112758. module.exports = factory();
  112759. else if(typeof define === 'function' && define.amd)
  112760. define([], factory);
  112761. else if(typeof exports === 'object')
  112762. exports["Handlebars"] = factory();
  112763. else
  112764. root["Handlebars"] = factory();
  112765. })(this, function() {
  112766. return /******/ (function(modules) { // webpackBootstrap
  112767. /******/ // The module cache
  112768. /******/ var installedModules = {};
  112769. /******/ // The require function
  112770. /******/ function __webpack_require__(moduleId) {
  112771. /******/ // Check if module is in cache
  112772. /******/ if(installedModules[moduleId])
  112773. /******/ return installedModules[moduleId].exports;
  112774. /******/ // Create a new module (and put it into the cache)
  112775. /******/ var module = installedModules[moduleId] = {
  112776. /******/ exports: {},
  112777. /******/ id: moduleId,
  112778. /******/ loaded: false
  112779. /******/ };
  112780. /******/ // Execute the module function
  112781. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  112782. /******/ // Flag the module as loaded
  112783. /******/ module.loaded = true;
  112784. /******/ // Return the exports of the module
  112785. /******/ return module.exports;
  112786. /******/ }
  112787. /******/ // expose the modules object (__webpack_modules__)
  112788. /******/ __webpack_require__.m = modules;
  112789. /******/ // expose the module cache
  112790. /******/ __webpack_require__.c = installedModules;
  112791. /******/ // __webpack_public_path__
  112792. /******/ __webpack_require__.p = "";
  112793. /******/ // Load entry module and return exports
  112794. /******/ return __webpack_require__(0);
  112795. /******/ })
  112796. /************************************************************************/
  112797. /******/ ([
  112798. /* 0 */
  112799. /***/ (function(module, exports, __webpack_require__) {
  112800. 'use strict';
  112801. var _interopRequireDefault = __webpack_require__(1)['default'];
  112802. exports.__esModule = true;
  112803. var _handlebarsRuntime = __webpack_require__(2);
  112804. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  112805. // Compiler imports
  112806. var _handlebarsCompilerAst = __webpack_require__(35);
  112807. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  112808. var _handlebarsCompilerBase = __webpack_require__(36);
  112809. var _handlebarsCompilerCompiler = __webpack_require__(41);
  112810. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  112811. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  112812. var _handlebarsCompilerVisitor = __webpack_require__(39);
  112813. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  112814. var _handlebarsNoConflict = __webpack_require__(34);
  112815. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  112816. var _create = _handlebarsRuntime2['default'].create;
  112817. function create() {
  112818. var hb = _create();
  112819. hb.compile = function (input, options) {
  112820. return _handlebarsCompilerCompiler.compile(input, options, hb);
  112821. };
  112822. hb.precompile = function (input, options) {
  112823. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  112824. };
  112825. hb.AST = _handlebarsCompilerAst2['default'];
  112826. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  112827. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  112828. hb.Parser = _handlebarsCompilerBase.parser;
  112829. hb.parse = _handlebarsCompilerBase.parse;
  112830. return hb;
  112831. }
  112832. var inst = create();
  112833. inst.create = create;
  112834. _handlebarsNoConflict2['default'](inst);
  112835. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  112836. inst['default'] = inst;
  112837. exports['default'] = inst;
  112838. module.exports = exports['default'];
  112839. /***/ }),
  112840. /* 1 */
  112841. /***/ (function(module, exports) {
  112842. "use strict";
  112843. exports["default"] = function (obj) {
  112844. return obj && obj.__esModule ? obj : {
  112845. "default": obj
  112846. };
  112847. };
  112848. exports.__esModule = true;
  112849. /***/ }),
  112850. /* 2 */
  112851. /***/ (function(module, exports, __webpack_require__) {
  112852. 'use strict';
  112853. var _interopRequireWildcard = __webpack_require__(3)['default'];
  112854. var _interopRequireDefault = __webpack_require__(1)['default'];
  112855. exports.__esModule = true;
  112856. var _handlebarsBase = __webpack_require__(4);
  112857. var base = _interopRequireWildcard(_handlebarsBase);
  112858. // Each of these augment the Handlebars object. No need to setup here.
  112859. // (This is done to easily share code between commonjs and browse envs)
  112860. var _handlebarsSafeString = __webpack_require__(21);
  112861. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  112862. var _handlebarsException = __webpack_require__(6);
  112863. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  112864. var _handlebarsUtils = __webpack_require__(5);
  112865. var Utils = _interopRequireWildcard(_handlebarsUtils);
  112866. var _handlebarsRuntime = __webpack_require__(22);
  112867. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  112868. var _handlebarsNoConflict = __webpack_require__(34);
  112869. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  112870. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  112871. function create() {
  112872. var hb = new base.HandlebarsEnvironment();
  112873. Utils.extend(hb, base);
  112874. hb.SafeString = _handlebarsSafeString2['default'];
  112875. hb.Exception = _handlebarsException2['default'];
  112876. hb.Utils = Utils;
  112877. hb.escapeExpression = Utils.escapeExpression;
  112878. hb.VM = runtime;
  112879. hb.template = function (spec) {
  112880. return runtime.template(spec, hb);
  112881. };
  112882. return hb;
  112883. }
  112884. var inst = create();
  112885. inst.create = create;
  112886. _handlebarsNoConflict2['default'](inst);
  112887. inst['default'] = inst;
  112888. exports['default'] = inst;
  112889. module.exports = exports['default'];
  112890. /***/ }),
  112891. /* 3 */
  112892. /***/ (function(module, exports) {
  112893. "use strict";
  112894. exports["default"] = function (obj) {
  112895. if (obj && obj.__esModule) {
  112896. return obj;
  112897. } else {
  112898. var newObj = {};
  112899. if (obj != null) {
  112900. for (var key in obj) {
  112901. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  112902. }
  112903. }
  112904. newObj["default"] = obj;
  112905. return newObj;
  112906. }
  112907. };
  112908. exports.__esModule = true;
  112909. /***/ }),
  112910. /* 4 */
  112911. /***/ (function(module, exports, __webpack_require__) {
  112912. 'use strict';
  112913. var _interopRequireDefault = __webpack_require__(1)['default'];
  112914. exports.__esModule = true;
  112915. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  112916. var _utils = __webpack_require__(5);
  112917. var _exception = __webpack_require__(6);
  112918. var _exception2 = _interopRequireDefault(_exception);
  112919. var _helpers = __webpack_require__(10);
  112920. var _decorators = __webpack_require__(18);
  112921. var _logger = __webpack_require__(20);
  112922. var _logger2 = _interopRequireDefault(_logger);
  112923. var VERSION = '4.0.11';
  112924. exports.VERSION = VERSION;
  112925. var COMPILER_REVISION = 7;
  112926. exports.COMPILER_REVISION = COMPILER_REVISION;
  112927. var REVISION_CHANGES = {
  112928. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  112929. 2: '== 1.0.0-rc.3',
  112930. 3: '== 1.0.0-rc.4',
  112931. 4: '== 1.x.x',
  112932. 5: '== 2.0.0-alpha.x',
  112933. 6: '>= 2.0.0-beta.1',
  112934. 7: '>= 4.0.0'
  112935. };
  112936. exports.REVISION_CHANGES = REVISION_CHANGES;
  112937. var objectType = '[object Object]';
  112938. function HandlebarsEnvironment(helpers, partials, decorators) {
  112939. this.helpers = helpers || {};
  112940. this.partials = partials || {};
  112941. this.decorators = decorators || {};
  112942. _helpers.registerDefaultHelpers(this);
  112943. _decorators.registerDefaultDecorators(this);
  112944. }
  112945. HandlebarsEnvironment.prototype = {
  112946. constructor: HandlebarsEnvironment,
  112947. logger: _logger2['default'],
  112948. log: _logger2['default'].log,
  112949. registerHelper: function registerHelper(name, fn) {
  112950. if (_utils.toString.call(name) === objectType) {
  112951. if (fn) {
  112952. throw new _exception2['default']('Arg not supported with multiple helpers');
  112953. }
  112954. _utils.extend(this.helpers, name);
  112955. } else {
  112956. this.helpers[name] = fn;
  112957. }
  112958. },
  112959. unregisterHelper: function unregisterHelper(name) {
  112960. delete this.helpers[name];
  112961. },
  112962. registerPartial: function registerPartial(name, partial) {
  112963. if (_utils.toString.call(name) === objectType) {
  112964. _utils.extend(this.partials, name);
  112965. } else {
  112966. if (typeof partial === 'undefined') {
  112967. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  112968. }
  112969. this.partials[name] = partial;
  112970. }
  112971. },
  112972. unregisterPartial: function unregisterPartial(name) {
  112973. delete this.partials[name];
  112974. },
  112975. registerDecorator: function registerDecorator(name, fn) {
  112976. if (_utils.toString.call(name) === objectType) {
  112977. if (fn) {
  112978. throw new _exception2['default']('Arg not supported with multiple decorators');
  112979. }
  112980. _utils.extend(this.decorators, name);
  112981. } else {
  112982. this.decorators[name] = fn;
  112983. }
  112984. },
  112985. unregisterDecorator: function unregisterDecorator(name) {
  112986. delete this.decorators[name];
  112987. }
  112988. };
  112989. var log = _logger2['default'].log;
  112990. exports.log = log;
  112991. exports.createFrame = _utils.createFrame;
  112992. exports.logger = _logger2['default'];
  112993. /***/ }),
  112994. /* 5 */
  112995. /***/ (function(module, exports) {
  112996. 'use strict';
  112997. exports.__esModule = true;
  112998. exports.extend = extend;
  112999. exports.indexOf = indexOf;
  113000. exports.escapeExpression = escapeExpression;
  113001. exports.isEmpty = isEmpty;
  113002. exports.createFrame = createFrame;
  113003. exports.blockParams = blockParams;
  113004. exports.appendContextPath = appendContextPath;
  113005. var escape = {
  113006. '&': '&amp;',
  113007. '<': '&lt;',
  113008. '>': '&gt;',
  113009. '"': '&quot;',
  113010. "'": '&#x27;',
  113011. '`': '&#x60;',
  113012. '=': '&#x3D;'
  113013. };
  113014. var badChars = /[&<>"'`=]/g,
  113015. possible = /[&<>"'`=]/;
  113016. function escapeChar(chr) {
  113017. return escape[chr];
  113018. }
  113019. function extend(obj /* , ...source */) {
  113020. for (var i = 1; i < arguments.length; i++) {
  113021. for (var key in arguments[i]) {
  113022. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  113023. obj[key] = arguments[i][key];
  113024. }
  113025. }
  113026. }
  113027. return obj;
  113028. }
  113029. var toString = Object.prototype.toString;
  113030. exports.toString = toString;
  113031. // Sourced from lodash
  113032. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  113033. /* eslint-disable func-style */
  113034. var isFunction = function isFunction(value) {
  113035. return typeof value === 'function';
  113036. };
  113037. // fallback for older versions of Chrome and Safari
  113038. /* istanbul ignore next */
  113039. if (isFunction(/x/)) {
  113040. exports.isFunction = isFunction = function (value) {
  113041. return typeof value === 'function' && toString.call(value) === '[object Function]';
  113042. };
  113043. }
  113044. exports.isFunction = isFunction;
  113045. /* eslint-enable func-style */
  113046. /* istanbul ignore next */
  113047. var isArray = Array.isArray || function (value) {
  113048. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  113049. };
  113050. exports.isArray = isArray;
  113051. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  113052. function indexOf(array, value) {
  113053. for (var i = 0, len = array.length; i < len; i++) {
  113054. if (array[i] === value) {
  113055. return i;
  113056. }
  113057. }
  113058. return -1;
  113059. }
  113060. function escapeExpression(string) {
  113061. if (typeof string !== 'string') {
  113062. // don't escape SafeStrings, since they're already safe
  113063. if (string && string.toHTML) {
  113064. return string.toHTML();
  113065. } else if (string == null) {
  113066. return '';
  113067. } else if (!string) {
  113068. return string + '';
  113069. }
  113070. // Force a string conversion as this will be done by the append regardless and
  113071. // the regex test will do this transparently behind the scenes, causing issues if
  113072. // an object's to string has escaped characters in it.
  113073. string = '' + string;
  113074. }
  113075. if (!possible.test(string)) {
  113076. return string;
  113077. }
  113078. return string.replace(badChars, escapeChar);
  113079. }
  113080. function isEmpty(value) {
  113081. if (!value && value !== 0) {
  113082. return true;
  113083. } else if (isArray(value) && value.length === 0) {
  113084. return true;
  113085. } else {
  113086. return false;
  113087. }
  113088. }
  113089. function createFrame(object) {
  113090. var frame = extend({}, object);
  113091. frame._parent = object;
  113092. return frame;
  113093. }
  113094. function blockParams(params, ids) {
  113095. params.path = ids;
  113096. return params;
  113097. }
  113098. function appendContextPath(contextPath, id) {
  113099. return (contextPath ? contextPath + '.' : '') + id;
  113100. }
  113101. /***/ }),
  113102. /* 6 */
  113103. /***/ (function(module, exports, __webpack_require__) {
  113104. 'use strict';
  113105. var _Object$defineProperty = __webpack_require__(7)['default'];
  113106. exports.__esModule = true;
  113107. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  113108. function Exception(message, node) {
  113109. var loc = node && node.loc,
  113110. line = undefined,
  113111. column = undefined;
  113112. if (loc) {
  113113. line = loc.start.line;
  113114. column = loc.start.column;
  113115. message += ' - ' + line + ':' + column;
  113116. }
  113117. var tmp = Error.prototype.constructor.call(this, message);
  113118. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  113119. for (var idx = 0; idx < errorProps.length; idx++) {
  113120. this[errorProps[idx]] = tmp[errorProps[idx]];
  113121. }
  113122. /* istanbul ignore else */
  113123. if (Error.captureStackTrace) {
  113124. Error.captureStackTrace(this, Exception);
  113125. }
  113126. try {
  113127. if (loc) {
  113128. this.lineNumber = line;
  113129. // Work around issue under safari where we can't directly set the column value
  113130. /* istanbul ignore next */
  113131. if (_Object$defineProperty) {
  113132. Object.defineProperty(this, 'column', {
  113133. value: column,
  113134. enumerable: true
  113135. });
  113136. } else {
  113137. this.column = column;
  113138. }
  113139. }
  113140. } catch (nop) {
  113141. /* Ignore if the browser is very particular */
  113142. }
  113143. }
  113144. Exception.prototype = new Error();
  113145. exports['default'] = Exception;
  113146. module.exports = exports['default'];
  113147. /***/ }),
  113148. /* 7 */
  113149. /***/ (function(module, exports, __webpack_require__) {
  113150. module.exports = { "default": __webpack_require__(8), __esModule: true };
  113151. /***/ }),
  113152. /* 8 */
  113153. /***/ (function(module, exports, __webpack_require__) {
  113154. var $ = __webpack_require__(9);
  113155. module.exports = function defineProperty(it, key, desc){
  113156. return $.setDesc(it, key, desc);
  113157. };
  113158. /***/ }),
  113159. /* 9 */
  113160. /***/ (function(module, exports) {
  113161. var $Object = Object;
  113162. module.exports = {
  113163. create: $Object.create,
  113164. getProto: $Object.getPrototypeOf,
  113165. isEnum: {}.propertyIsEnumerable,
  113166. getDesc: $Object.getOwnPropertyDescriptor,
  113167. setDesc: $Object.defineProperty,
  113168. setDescs: $Object.defineProperties,
  113169. getKeys: $Object.keys,
  113170. getNames: $Object.getOwnPropertyNames,
  113171. getSymbols: $Object.getOwnPropertySymbols,
  113172. each: [].forEach
  113173. };
  113174. /***/ }),
  113175. /* 10 */
  113176. /***/ (function(module, exports, __webpack_require__) {
  113177. 'use strict';
  113178. var _interopRequireDefault = __webpack_require__(1)['default'];
  113179. exports.__esModule = true;
  113180. exports.registerDefaultHelpers = registerDefaultHelpers;
  113181. var _helpersBlockHelperMissing = __webpack_require__(11);
  113182. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  113183. var _helpersEach = __webpack_require__(12);
  113184. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  113185. var _helpersHelperMissing = __webpack_require__(13);
  113186. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  113187. var _helpersIf = __webpack_require__(14);
  113188. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  113189. var _helpersLog = __webpack_require__(15);
  113190. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  113191. var _helpersLookup = __webpack_require__(16);
  113192. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  113193. var _helpersWith = __webpack_require__(17);
  113194. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  113195. function registerDefaultHelpers(instance) {
  113196. _helpersBlockHelperMissing2['default'](instance);
  113197. _helpersEach2['default'](instance);
  113198. _helpersHelperMissing2['default'](instance);
  113199. _helpersIf2['default'](instance);
  113200. _helpersLog2['default'](instance);
  113201. _helpersLookup2['default'](instance);
  113202. _helpersWith2['default'](instance);
  113203. }
  113204. /***/ }),
  113205. /* 11 */
  113206. /***/ (function(module, exports, __webpack_require__) {
  113207. 'use strict';
  113208. exports.__esModule = true;
  113209. var _utils = __webpack_require__(5);
  113210. exports['default'] = function (instance) {
  113211. instance.registerHelper('blockHelperMissing', function (context, options) {
  113212. var inverse = options.inverse,
  113213. fn = options.fn;
  113214. if (context === true) {
  113215. return fn(this);
  113216. } else if (context === false || context == null) {
  113217. return inverse(this);
  113218. } else if (_utils.isArray(context)) {
  113219. if (context.length > 0) {
  113220. if (options.ids) {
  113221. options.ids = [options.name];
  113222. }
  113223. return instance.helpers.each(context, options);
  113224. } else {
  113225. return inverse(this);
  113226. }
  113227. } else {
  113228. if (options.data && options.ids) {
  113229. var data = _utils.createFrame(options.data);
  113230. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  113231. options = { data: data };
  113232. }
  113233. return fn(context, options);
  113234. }
  113235. });
  113236. };
  113237. module.exports = exports['default'];
  113238. /***/ }),
  113239. /* 12 */
  113240. /***/ (function(module, exports, __webpack_require__) {
  113241. 'use strict';
  113242. var _interopRequireDefault = __webpack_require__(1)['default'];
  113243. exports.__esModule = true;
  113244. var _utils = __webpack_require__(5);
  113245. var _exception = __webpack_require__(6);
  113246. var _exception2 = _interopRequireDefault(_exception);
  113247. exports['default'] = function (instance) {
  113248. instance.registerHelper('each', function (context, options) {
  113249. if (!options) {
  113250. throw new _exception2['default']('Must pass iterator to #each');
  113251. }
  113252. var fn = options.fn,
  113253. inverse = options.inverse,
  113254. i = 0,
  113255. ret = '',
  113256. data = undefined,
  113257. contextPath = undefined;
  113258. if (options.data && options.ids) {
  113259. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  113260. }
  113261. if (_utils.isFunction(context)) {
  113262. context = context.call(this);
  113263. }
  113264. if (options.data) {
  113265. data = _utils.createFrame(options.data);
  113266. }
  113267. function execIteration(field, index, last) {
  113268. if (data) {
  113269. data.key = field;
  113270. data.index = index;
  113271. data.first = index === 0;
  113272. data.last = !!last;
  113273. if (contextPath) {
  113274. data.contextPath = contextPath + field;
  113275. }
  113276. }
  113277. ret = ret + fn(context[field], {
  113278. data: data,
  113279. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  113280. });
  113281. }
  113282. if (context && typeof context === 'object') {
  113283. if (_utils.isArray(context)) {
  113284. for (var j = context.length; i < j; i++) {
  113285. if (i in context) {
  113286. execIteration(i, i, i === context.length - 1);
  113287. }
  113288. }
  113289. } else {
  113290. var priorKey = undefined;
  113291. for (var key in context) {
  113292. if (context.hasOwnProperty(key)) {
  113293. // We're running the iterations one step out of sync so we can detect
  113294. // the last iteration without have to scan the object twice and create
  113295. // an itermediate keys array.
  113296. if (priorKey !== undefined) {
  113297. execIteration(priorKey, i - 1);
  113298. }
  113299. priorKey = key;
  113300. i++;
  113301. }
  113302. }
  113303. if (priorKey !== undefined) {
  113304. execIteration(priorKey, i - 1, true);
  113305. }
  113306. }
  113307. }
  113308. if (i === 0) {
  113309. ret = inverse(this);
  113310. }
  113311. return ret;
  113312. });
  113313. };
  113314. module.exports = exports['default'];
  113315. /***/ }),
  113316. /* 13 */
  113317. /***/ (function(module, exports, __webpack_require__) {
  113318. 'use strict';
  113319. var _interopRequireDefault = __webpack_require__(1)['default'];
  113320. exports.__esModule = true;
  113321. var _exception = __webpack_require__(6);
  113322. var _exception2 = _interopRequireDefault(_exception);
  113323. exports['default'] = function (instance) {
  113324. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  113325. if (arguments.length === 1) {
  113326. // A missing field in a {{foo}} construct.
  113327. return undefined;
  113328. } else {
  113329. // Someone is actually trying to call something, blow up.
  113330. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  113331. }
  113332. });
  113333. };
  113334. module.exports = exports['default'];
  113335. /***/ }),
  113336. /* 14 */
  113337. /***/ (function(module, exports, __webpack_require__) {
  113338. 'use strict';
  113339. exports.__esModule = true;
  113340. var _utils = __webpack_require__(5);
  113341. exports['default'] = function (instance) {
  113342. instance.registerHelper('if', function (conditional, options) {
  113343. if (_utils.isFunction(conditional)) {
  113344. conditional = conditional.call(this);
  113345. }
  113346. // Default behavior is to render the positive path if the value is truthy and not empty.
  113347. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  113348. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  113349. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  113350. return options.inverse(this);
  113351. } else {
  113352. return options.fn(this);
  113353. }
  113354. });
  113355. instance.registerHelper('unless', function (conditional, options) {
  113356. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  113357. });
  113358. };
  113359. module.exports = exports['default'];
  113360. /***/ }),
  113361. /* 15 */
  113362. /***/ (function(module, exports) {
  113363. 'use strict';
  113364. exports.__esModule = true;
  113365. exports['default'] = function (instance) {
  113366. instance.registerHelper('log', function () /* message, options */{
  113367. var args = [undefined],
  113368. options = arguments[arguments.length - 1];
  113369. for (var i = 0; i < arguments.length - 1; i++) {
  113370. args.push(arguments[i]);
  113371. }
  113372. var level = 1;
  113373. if (options.hash.level != null) {
  113374. level = options.hash.level;
  113375. } else if (options.data && options.data.level != null) {
  113376. level = options.data.level;
  113377. }
  113378. args[0] = level;
  113379. instance.log.apply(instance, args);
  113380. });
  113381. };
  113382. module.exports = exports['default'];
  113383. /***/ }),
  113384. /* 16 */
  113385. /***/ (function(module, exports) {
  113386. 'use strict';
  113387. exports.__esModule = true;
  113388. exports['default'] = function (instance) {
  113389. instance.registerHelper('lookup', function (obj, field) {
  113390. return obj && obj[field];
  113391. });
  113392. };
  113393. module.exports = exports['default'];
  113394. /***/ }),
  113395. /* 17 */
  113396. /***/ (function(module, exports, __webpack_require__) {
  113397. 'use strict';
  113398. exports.__esModule = true;
  113399. var _utils = __webpack_require__(5);
  113400. exports['default'] = function (instance) {
  113401. instance.registerHelper('with', function (context, options) {
  113402. if (_utils.isFunction(context)) {
  113403. context = context.call(this);
  113404. }
  113405. var fn = options.fn;
  113406. if (!_utils.isEmpty(context)) {
  113407. var data = options.data;
  113408. if (options.data && options.ids) {
  113409. data = _utils.createFrame(options.data);
  113410. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  113411. }
  113412. return fn(context, {
  113413. data: data,
  113414. blockParams: _utils.blockParams([context], [data && data.contextPath])
  113415. });
  113416. } else {
  113417. return options.inverse(this);
  113418. }
  113419. });
  113420. };
  113421. module.exports = exports['default'];
  113422. /***/ }),
  113423. /* 18 */
  113424. /***/ (function(module, exports, __webpack_require__) {
  113425. 'use strict';
  113426. var _interopRequireDefault = __webpack_require__(1)['default'];
  113427. exports.__esModule = true;
  113428. exports.registerDefaultDecorators = registerDefaultDecorators;
  113429. var _decoratorsInline = __webpack_require__(19);
  113430. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  113431. function registerDefaultDecorators(instance) {
  113432. _decoratorsInline2['default'](instance);
  113433. }
  113434. /***/ }),
  113435. /* 19 */
  113436. /***/ (function(module, exports, __webpack_require__) {
  113437. 'use strict';
  113438. exports.__esModule = true;
  113439. var _utils = __webpack_require__(5);
  113440. exports['default'] = function (instance) {
  113441. instance.registerDecorator('inline', function (fn, props, container, options) {
  113442. var ret = fn;
  113443. if (!props.partials) {
  113444. props.partials = {};
  113445. ret = function (context, options) {
  113446. // Create a new partials stack frame prior to exec.
  113447. var original = container.partials;
  113448. container.partials = _utils.extend({}, original, props.partials);
  113449. var ret = fn(context, options);
  113450. container.partials = original;
  113451. return ret;
  113452. };
  113453. }
  113454. props.partials[options.args[0]] = options.fn;
  113455. return ret;
  113456. });
  113457. };
  113458. module.exports = exports['default'];
  113459. /***/ }),
  113460. /* 20 */
  113461. /***/ (function(module, exports, __webpack_require__) {
  113462. 'use strict';
  113463. exports.__esModule = true;
  113464. var _utils = __webpack_require__(5);
  113465. var logger = {
  113466. methodMap: ['debug', 'info', 'warn', 'error'],
  113467. level: 'info',
  113468. // Maps a given level value to the `methodMap` indexes above.
  113469. lookupLevel: function lookupLevel(level) {
  113470. if (typeof level === 'string') {
  113471. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  113472. if (levelMap >= 0) {
  113473. level = levelMap;
  113474. } else {
  113475. level = parseInt(level, 10);
  113476. }
  113477. }
  113478. return level;
  113479. },
  113480. // Can be overridden in the host environment
  113481. log: function log(level) {
  113482. level = logger.lookupLevel(level);
  113483. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  113484. var method = logger.methodMap[level];
  113485. if (!console[method]) {
  113486. // eslint-disable-line no-console
  113487. method = 'log';
  113488. }
  113489. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  113490. message[_key - 1] = arguments[_key];
  113491. }
  113492. console[method].apply(console, message); // eslint-disable-line no-console
  113493. }
  113494. }
  113495. };
  113496. exports['default'] = logger;
  113497. module.exports = exports['default'];
  113498. /***/ }),
  113499. /* 21 */
  113500. /***/ (function(module, exports) {
  113501. // Build out our basic SafeString type
  113502. 'use strict';
  113503. exports.__esModule = true;
  113504. function SafeString(string) {
  113505. this.string = string;
  113506. }
  113507. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  113508. return '' + this.string;
  113509. };
  113510. exports['default'] = SafeString;
  113511. module.exports = exports['default'];
  113512. /***/ }),
  113513. /* 22 */
  113514. /***/ (function(module, exports, __webpack_require__) {
  113515. 'use strict';
  113516. var _Object$seal = __webpack_require__(23)['default'];
  113517. var _interopRequireWildcard = __webpack_require__(3)['default'];
  113518. var _interopRequireDefault = __webpack_require__(1)['default'];
  113519. exports.__esModule = true;
  113520. exports.checkRevision = checkRevision;
  113521. exports.template = template;
  113522. exports.wrapProgram = wrapProgram;
  113523. exports.resolvePartial = resolvePartial;
  113524. exports.invokePartial = invokePartial;
  113525. exports.noop = noop;
  113526. var _utils = __webpack_require__(5);
  113527. var Utils = _interopRequireWildcard(_utils);
  113528. var _exception = __webpack_require__(6);
  113529. var _exception2 = _interopRequireDefault(_exception);
  113530. var _base = __webpack_require__(4);
  113531. function checkRevision(compilerInfo) {
  113532. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  113533. currentRevision = _base.COMPILER_REVISION;
  113534. if (compilerRevision !== currentRevision) {
  113535. if (compilerRevision < currentRevision) {
  113536. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  113537. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  113538. throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
  113539. } else {
  113540. // Use the embedded version info since the runtime doesn't know about this revision yet
  113541. throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
  113542. }
  113543. }
  113544. }
  113545. function template(templateSpec, env) {
  113546. /* istanbul ignore next */
  113547. if (!env) {
  113548. throw new _exception2['default']('No environment passed to template');
  113549. }
  113550. if (!templateSpec || !templateSpec.main) {
  113551. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  113552. }
  113553. templateSpec.main.decorator = templateSpec.main_d;
  113554. // Note: Using env.VM references rather than local var references throughout this section to allow
  113555. // for external users to override these as psuedo-supported APIs.
  113556. env.VM.checkRevision(templateSpec.compiler);
  113557. function invokePartialWrapper(partial, context, options) {
  113558. if (options.hash) {
  113559. context = Utils.extend({}, context, options.hash);
  113560. if (options.ids) {
  113561. options.ids[0] = true;
  113562. }
  113563. }
  113564. partial = env.VM.resolvePartial.call(this, partial, context, options);
  113565. var result = env.VM.invokePartial.call(this, partial, context, options);
  113566. if (result == null && env.compile) {
  113567. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  113568. result = options.partials[options.name](context, options);
  113569. }
  113570. if (result != null) {
  113571. if (options.indent) {
  113572. var lines = result.split('\n');
  113573. for (var i = 0, l = lines.length; i < l; i++) {
  113574. if (!lines[i] && i + 1 === l) {
  113575. break;
  113576. }
  113577. lines[i] = options.indent + lines[i];
  113578. }
  113579. result = lines.join('\n');
  113580. }
  113581. return result;
  113582. } else {
  113583. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  113584. }
  113585. }
  113586. // Just add water
  113587. var container = {
  113588. strict: function strict(obj, name) {
  113589. if (!(name in obj)) {
  113590. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  113591. }
  113592. return obj[name];
  113593. },
  113594. lookup: function lookup(depths, name) {
  113595. var len = depths.length;
  113596. for (var i = 0; i < len; i++) {
  113597. if (depths[i] && depths[i][name] != null) {
  113598. return depths[i][name];
  113599. }
  113600. }
  113601. },
  113602. lambda: function lambda(current, context) {
  113603. return typeof current === 'function' ? current.call(context) : current;
  113604. },
  113605. escapeExpression: Utils.escapeExpression,
  113606. invokePartial: invokePartialWrapper,
  113607. fn: function fn(i) {
  113608. var ret = templateSpec[i];
  113609. ret.decorator = templateSpec[i + '_d'];
  113610. return ret;
  113611. },
  113612. programs: [],
  113613. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  113614. var programWrapper = this.programs[i],
  113615. fn = this.fn(i);
  113616. if (data || depths || blockParams || declaredBlockParams) {
  113617. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  113618. } else if (!programWrapper) {
  113619. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  113620. }
  113621. return programWrapper;
  113622. },
  113623. data: function data(value, depth) {
  113624. while (value && depth--) {
  113625. value = value._parent;
  113626. }
  113627. return value;
  113628. },
  113629. merge: function merge(param, common) {
  113630. var obj = param || common;
  113631. if (param && common && param !== common) {
  113632. obj = Utils.extend({}, common, param);
  113633. }
  113634. return obj;
  113635. },
  113636. // An empty object to use as replacement for null-contexts
  113637. nullContext: _Object$seal({}),
  113638. noop: env.VM.noop,
  113639. compilerInfo: templateSpec.compiler
  113640. };
  113641. function ret(context) {
  113642. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  113643. var data = options.data;
  113644. ret._setup(options);
  113645. if (!options.partial && templateSpec.useData) {
  113646. data = initData(context, data);
  113647. }
  113648. var depths = undefined,
  113649. blockParams = templateSpec.useBlockParams ? [] : undefined;
  113650. if (templateSpec.useDepths) {
  113651. if (options.depths) {
  113652. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  113653. } else {
  113654. depths = [context];
  113655. }
  113656. }
  113657. function main(context /*, options*/) {
  113658. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  113659. }
  113660. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  113661. return main(context, options);
  113662. }
  113663. ret.isTop = true;
  113664. ret._setup = function (options) {
  113665. if (!options.partial) {
  113666. container.helpers = container.merge(options.helpers, env.helpers);
  113667. if (templateSpec.usePartial) {
  113668. container.partials = container.merge(options.partials, env.partials);
  113669. }
  113670. if (templateSpec.usePartial || templateSpec.useDecorators) {
  113671. container.decorators = container.merge(options.decorators, env.decorators);
  113672. }
  113673. } else {
  113674. container.helpers = options.helpers;
  113675. container.partials = options.partials;
  113676. container.decorators = options.decorators;
  113677. }
  113678. };
  113679. ret._child = function (i, data, blockParams, depths) {
  113680. if (templateSpec.useBlockParams && !blockParams) {
  113681. throw new _exception2['default']('must pass block params');
  113682. }
  113683. if (templateSpec.useDepths && !depths) {
  113684. throw new _exception2['default']('must pass parent depths');
  113685. }
  113686. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  113687. };
  113688. return ret;
  113689. }
  113690. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  113691. function prog(context) {
  113692. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  113693. var currentDepths = depths;
  113694. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  113695. currentDepths = [context].concat(depths);
  113696. }
  113697. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  113698. }
  113699. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  113700. prog.program = i;
  113701. prog.depth = depths ? depths.length : 0;
  113702. prog.blockParams = declaredBlockParams || 0;
  113703. return prog;
  113704. }
  113705. function resolvePartial(partial, context, options) {
  113706. if (!partial) {
  113707. if (options.name === '@partial-block') {
  113708. partial = options.data['partial-block'];
  113709. } else {
  113710. partial = options.partials[options.name];
  113711. }
  113712. } else if (!partial.call && !options.name) {
  113713. // This is a dynamic partial that returned a string
  113714. options.name = partial;
  113715. partial = options.partials[partial];
  113716. }
  113717. return partial;
  113718. }
  113719. function invokePartial(partial, context, options) {
  113720. // Use the current closure context to save the partial-block if this partial
  113721. var currentPartialBlock = options.data && options.data['partial-block'];
  113722. options.partial = true;
  113723. if (options.ids) {
  113724. options.data.contextPath = options.ids[0] || options.data.contextPath;
  113725. }
  113726. var partialBlock = undefined;
  113727. if (options.fn && options.fn !== noop) {
  113728. (function () {
  113729. options.data = _base.createFrame(options.data);
  113730. // Wrapper function to get access to currentPartialBlock from the closure
  113731. var fn = options.fn;
  113732. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  113733. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  113734. // Restore the partial-block from the closure for the execution of the block
  113735. // i.e. the part inside the block of the partial call.
  113736. options.data = _base.createFrame(options.data);
  113737. options.data['partial-block'] = currentPartialBlock;
  113738. return fn(context, options);
  113739. };
  113740. if (fn.partials) {
  113741. options.partials = Utils.extend({}, options.partials, fn.partials);
  113742. }
  113743. })();
  113744. }
  113745. if (partial === undefined && partialBlock) {
  113746. partial = partialBlock;
  113747. }
  113748. if (partial === undefined) {
  113749. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  113750. } else if (partial instanceof Function) {
  113751. return partial(context, options);
  113752. }
  113753. }
  113754. function noop() {
  113755. return '';
  113756. }
  113757. function initData(context, data) {
  113758. if (!data || !('root' in data)) {
  113759. data = data ? _base.createFrame(data) : {};
  113760. data.root = context;
  113761. }
  113762. return data;
  113763. }
  113764. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  113765. if (fn.decorator) {
  113766. var props = {};
  113767. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  113768. Utils.extend(prog, props);
  113769. }
  113770. return prog;
  113771. }
  113772. /***/ }),
  113773. /* 23 */
  113774. /***/ (function(module, exports, __webpack_require__) {
  113775. module.exports = { "default": __webpack_require__(24), __esModule: true };
  113776. /***/ }),
  113777. /* 24 */
  113778. /***/ (function(module, exports, __webpack_require__) {
  113779. __webpack_require__(25);
  113780. module.exports = __webpack_require__(30).Object.seal;
  113781. /***/ }),
  113782. /* 25 */
  113783. /***/ (function(module, exports, __webpack_require__) {
  113784. // 19.1.2.17 Object.seal(O)
  113785. var isObject = __webpack_require__(26);
  113786. __webpack_require__(27)('seal', function($seal){
  113787. return function seal(it){
  113788. return $seal && isObject(it) ? $seal(it) : it;
  113789. };
  113790. });
  113791. /***/ }),
  113792. /* 26 */
  113793. /***/ (function(module, exports) {
  113794. module.exports = function(it){
  113795. return typeof it === 'object' ? it !== null : typeof it === 'function';
  113796. };
  113797. /***/ }),
  113798. /* 27 */
  113799. /***/ (function(module, exports, __webpack_require__) {
  113800. // most Object methods by ES6 should accept primitives
  113801. var $export = __webpack_require__(28)
  113802. , core = __webpack_require__(30)
  113803. , fails = __webpack_require__(33);
  113804. module.exports = function(KEY, exec){
  113805. var fn = (core.Object || {})[KEY] || Object[KEY]
  113806. , exp = {};
  113807. exp[KEY] = exec(fn);
  113808. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  113809. };
  113810. /***/ }),
  113811. /* 28 */
  113812. /***/ (function(module, exports, __webpack_require__) {
  113813. var global = __webpack_require__(29)
  113814. , core = __webpack_require__(30)
  113815. , ctx = __webpack_require__(31)
  113816. , PROTOTYPE = 'prototype';
  113817. var $export = function(type, name, source){
  113818. var IS_FORCED = type & $export.F
  113819. , IS_GLOBAL = type & $export.G
  113820. , IS_STATIC = type & $export.S
  113821. , IS_PROTO = type & $export.P
  113822. , IS_BIND = type & $export.B
  113823. , IS_WRAP = type & $export.W
  113824. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  113825. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  113826. , key, own, out;
  113827. if(IS_GLOBAL)source = name;
  113828. for(key in source){
  113829. // contains in native
  113830. own = !IS_FORCED && target && key in target;
  113831. if(own && key in exports)continue;
  113832. // export native or passed
  113833. out = own ? target[key] : source[key];
  113834. // prevent global pollution for namespaces
  113835. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  113836. // bind timers to global for call from export context
  113837. : IS_BIND && own ? ctx(out, global)
  113838. // wrap global constructors for prevent change them in library
  113839. : IS_WRAP && target[key] == out ? (function(C){
  113840. var F = function(param){
  113841. return this instanceof C ? new C(param) : C(param);
  113842. };
  113843. F[PROTOTYPE] = C[PROTOTYPE];
  113844. return F;
  113845. // make static versions for prototype methods
  113846. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  113847. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  113848. }
  113849. };
  113850. // type bitmap
  113851. $export.F = 1; // forced
  113852. $export.G = 2; // global
  113853. $export.S = 4; // static
  113854. $export.P = 8; // proto
  113855. $export.B = 16; // bind
  113856. $export.W = 32; // wrap
  113857. module.exports = $export;
  113858. /***/ }),
  113859. /* 29 */
  113860. /***/ (function(module, exports) {
  113861. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  113862. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  113863. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  113864. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  113865. /***/ }),
  113866. /* 30 */
  113867. /***/ (function(module, exports) {
  113868. var core = module.exports = {version: '1.2.6'};
  113869. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  113870. /***/ }),
  113871. /* 31 */
  113872. /***/ (function(module, exports, __webpack_require__) {
  113873. // optional / simple context binding
  113874. var aFunction = __webpack_require__(32);
  113875. module.exports = function(fn, that, length){
  113876. aFunction(fn);
  113877. if(that === undefined)return fn;
  113878. switch(length){
  113879. case 1: return function(a){
  113880. return fn.call(that, a);
  113881. };
  113882. case 2: return function(a, b){
  113883. return fn.call(that, a, b);
  113884. };
  113885. case 3: return function(a, b, c){
  113886. return fn.call(that, a, b, c);
  113887. };
  113888. }
  113889. return function(/* ...args */){
  113890. return fn.apply(that, arguments);
  113891. };
  113892. };
  113893. /***/ }),
  113894. /* 32 */
  113895. /***/ (function(module, exports) {
  113896. module.exports = function(it){
  113897. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  113898. return it;
  113899. };
  113900. /***/ }),
  113901. /* 33 */
  113902. /***/ (function(module, exports) {
  113903. module.exports = function(exec){
  113904. try {
  113905. return !!exec();
  113906. } catch(e){
  113907. return true;
  113908. }
  113909. };
  113910. /***/ }),
  113911. /* 34 */
  113912. /***/ (function(module, exports) {
  113913. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  113914. 'use strict';
  113915. exports.__esModule = true;
  113916. exports['default'] = function (Handlebars) {
  113917. /* istanbul ignore next */
  113918. var root = typeof global !== 'undefined' ? global : window,
  113919. $Handlebars = root.Handlebars;
  113920. /* istanbul ignore next */
  113921. Handlebars.noConflict = function () {
  113922. if (root.Handlebars === Handlebars) {
  113923. root.Handlebars = $Handlebars;
  113924. }
  113925. return Handlebars;
  113926. };
  113927. };
  113928. module.exports = exports['default'];
  113929. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  113930. /***/ }),
  113931. /* 35 */
  113932. /***/ (function(module, exports) {
  113933. 'use strict';
  113934. exports.__esModule = true;
  113935. var AST = {
  113936. // Public API used to evaluate derived attributes regarding AST nodes
  113937. helpers: {
  113938. // a mustache is definitely a helper if:
  113939. // * it is an eligible helper, and
  113940. // * it has at least one parameter or hash segment
  113941. helperExpression: function helperExpression(node) {
  113942. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  113943. },
  113944. scopedId: function scopedId(path) {
  113945. return (/^\.|this\b/.test(path.original)
  113946. );
  113947. },
  113948. // an ID is simple if it only has one part, and that part is not
  113949. // `..` or `this`.
  113950. simpleId: function simpleId(path) {
  113951. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  113952. }
  113953. }
  113954. };
  113955. // Must be exported as an object rather than the root of the module as the jison lexer
  113956. // must modify the object to operate properly.
  113957. exports['default'] = AST;
  113958. module.exports = exports['default'];
  113959. /***/ }),
  113960. /* 36 */
  113961. /***/ (function(module, exports, __webpack_require__) {
  113962. 'use strict';
  113963. var _interopRequireDefault = __webpack_require__(1)['default'];
  113964. var _interopRequireWildcard = __webpack_require__(3)['default'];
  113965. exports.__esModule = true;
  113966. exports.parse = parse;
  113967. var _parser = __webpack_require__(37);
  113968. var _parser2 = _interopRequireDefault(_parser);
  113969. var _whitespaceControl = __webpack_require__(38);
  113970. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  113971. var _helpers = __webpack_require__(40);
  113972. var Helpers = _interopRequireWildcard(_helpers);
  113973. var _utils = __webpack_require__(5);
  113974. exports.parser = _parser2['default'];
  113975. var yy = {};
  113976. _utils.extend(yy, Helpers);
  113977. function parse(input, options) {
  113978. // Just return if an already-compiled AST was passed in.
  113979. if (input.type === 'Program') {
  113980. return input;
  113981. }
  113982. _parser2['default'].yy = yy;
  113983. // Altering the shared object here, but this is ok as parser is a sync operation
  113984. yy.locInfo = function (locInfo) {
  113985. return new yy.SourceLocation(options && options.srcName, locInfo);
  113986. };
  113987. var strip = new _whitespaceControl2['default'](options);
  113988. return strip.accept(_parser2['default'].parse(input));
  113989. }
  113990. /***/ }),
  113991. /* 37 */
  113992. /***/ (function(module, exports) {
  113993. // File ignored in coverage tests via setting in .istanbul.yml
  113994. /* Jison generated parser */
  113995. "use strict";
  113996. exports.__esModule = true;
  113997. var handlebars = (function () {
  113998. var parser = { trace: function trace() {},
  113999. yy: {},
  114000. 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 },
  114001. 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" },
  114002. 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]],
  114003. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  114004. /**/) {
  114005. var $0 = $$.length - 1;
  114006. switch (yystate) {
  114007. case 1:
  114008. return $$[$0 - 1];
  114009. break;
  114010. case 2:
  114011. this.$ = yy.prepareProgram($$[$0]);
  114012. break;
  114013. case 3:
  114014. this.$ = $$[$0];
  114015. break;
  114016. case 4:
  114017. this.$ = $$[$0];
  114018. break;
  114019. case 5:
  114020. this.$ = $$[$0];
  114021. break;
  114022. case 6:
  114023. this.$ = $$[$0];
  114024. break;
  114025. case 7:
  114026. this.$ = $$[$0];
  114027. break;
  114028. case 8:
  114029. this.$ = $$[$0];
  114030. break;
  114031. case 9:
  114032. this.$ = {
  114033. type: 'CommentStatement',
  114034. value: yy.stripComment($$[$0]),
  114035. strip: yy.stripFlags($$[$0], $$[$0]),
  114036. loc: yy.locInfo(this._$)
  114037. };
  114038. break;
  114039. case 10:
  114040. this.$ = {
  114041. type: 'ContentStatement',
  114042. original: $$[$0],
  114043. value: $$[$0],
  114044. loc: yy.locInfo(this._$)
  114045. };
  114046. break;
  114047. case 11:
  114048. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114049. break;
  114050. case 12:
  114051. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  114052. break;
  114053. case 13:
  114054. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  114055. break;
  114056. case 14:
  114057. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  114058. break;
  114059. case 15:
  114060. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114061. break;
  114062. case 16:
  114063. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114064. break;
  114065. case 17:
  114066. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114067. break;
  114068. case 18:
  114069. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  114070. break;
  114071. case 19:
  114072. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  114073. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  114074. program.chained = true;
  114075. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  114076. break;
  114077. case 20:
  114078. this.$ = $$[$0];
  114079. break;
  114080. case 21:
  114081. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  114082. break;
  114083. case 22:
  114084. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114085. break;
  114086. case 23:
  114087. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114088. break;
  114089. case 24:
  114090. this.$ = {
  114091. type: 'PartialStatement',
  114092. name: $$[$0 - 3],
  114093. params: $$[$0 - 2],
  114094. hash: $$[$0 - 1],
  114095. indent: '',
  114096. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  114097. loc: yy.locInfo(this._$)
  114098. };
  114099. break;
  114100. case 25:
  114101. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114102. break;
  114103. case 26:
  114104. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  114105. break;
  114106. case 27:
  114107. this.$ = $$[$0];
  114108. break;
  114109. case 28:
  114110. this.$ = $$[$0];
  114111. break;
  114112. case 29:
  114113. this.$ = {
  114114. type: 'SubExpression',
  114115. path: $$[$0 - 3],
  114116. params: $$[$0 - 2],
  114117. hash: $$[$0 - 1],
  114118. loc: yy.locInfo(this._$)
  114119. };
  114120. break;
  114121. case 30:
  114122. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  114123. break;
  114124. case 31:
  114125. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  114126. break;
  114127. case 32:
  114128. this.$ = yy.id($$[$0 - 1]);
  114129. break;
  114130. case 33:
  114131. this.$ = $$[$0];
  114132. break;
  114133. case 34:
  114134. this.$ = $$[$0];
  114135. break;
  114136. case 35:
  114137. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  114138. break;
  114139. case 36:
  114140. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  114141. break;
  114142. case 37:
  114143. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  114144. break;
  114145. case 38:
  114146. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  114147. break;
  114148. case 39:
  114149. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  114150. break;
  114151. case 40:
  114152. this.$ = $$[$0];
  114153. break;
  114154. case 41:
  114155. this.$ = $$[$0];
  114156. break;
  114157. case 42:
  114158. this.$ = yy.preparePath(true, $$[$0], this._$);
  114159. break;
  114160. case 43:
  114161. this.$ = yy.preparePath(false, $$[$0], this._$);
  114162. break;
  114163. case 44:
  114164. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  114165. break;
  114166. case 45:
  114167. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  114168. break;
  114169. case 46:
  114170. this.$ = [];
  114171. break;
  114172. case 47:
  114173. $$[$0 - 1].push($$[$0]);
  114174. break;
  114175. case 48:
  114176. this.$ = [$$[$0]];
  114177. break;
  114178. case 49:
  114179. $$[$0 - 1].push($$[$0]);
  114180. break;
  114181. case 50:
  114182. this.$ = [];
  114183. break;
  114184. case 51:
  114185. $$[$0 - 1].push($$[$0]);
  114186. break;
  114187. case 58:
  114188. this.$ = [];
  114189. break;
  114190. case 59:
  114191. $$[$0 - 1].push($$[$0]);
  114192. break;
  114193. case 64:
  114194. this.$ = [];
  114195. break;
  114196. case 65:
  114197. $$[$0 - 1].push($$[$0]);
  114198. break;
  114199. case 70:
  114200. this.$ = [];
  114201. break;
  114202. case 71:
  114203. $$[$0 - 1].push($$[$0]);
  114204. break;
  114205. case 78:
  114206. this.$ = [];
  114207. break;
  114208. case 79:
  114209. $$[$0 - 1].push($$[$0]);
  114210. break;
  114211. case 82:
  114212. this.$ = [];
  114213. break;
  114214. case 83:
  114215. $$[$0 - 1].push($$[$0]);
  114216. break;
  114217. case 86:
  114218. this.$ = [];
  114219. break;
  114220. case 87:
  114221. $$[$0 - 1].push($$[$0]);
  114222. break;
  114223. case 90:
  114224. this.$ = [];
  114225. break;
  114226. case 91:
  114227. $$[$0 - 1].push($$[$0]);
  114228. break;
  114229. case 94:
  114230. this.$ = [];
  114231. break;
  114232. case 95:
  114233. $$[$0 - 1].push($$[$0]);
  114234. break;
  114235. case 98:
  114236. this.$ = [$$[$0]];
  114237. break;
  114238. case 99:
  114239. $$[$0 - 1].push($$[$0]);
  114240. break;
  114241. case 100:
  114242. this.$ = [$$[$0]];
  114243. break;
  114244. case 101:
  114245. $$[$0 - 1].push($$[$0]);
  114246. break;
  114247. }
  114248. },
  114249. 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], 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] }],
  114250. 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] },
  114251. parseError: function parseError(str, hash) {
  114252. throw new Error(str);
  114253. },
  114254. parse: function parse(input) {
  114255. var self = this,
  114256. stack = [0],
  114257. vstack = [null],
  114258. lstack = [],
  114259. table = this.table,
  114260. yytext = "",
  114261. yylineno = 0,
  114262. yyleng = 0,
  114263. recovering = 0,
  114264. TERROR = 2,
  114265. EOF = 1;
  114266. this.lexer.setInput(input);
  114267. this.lexer.yy = this.yy;
  114268. this.yy.lexer = this.lexer;
  114269. this.yy.parser = this;
  114270. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  114271. var yyloc = this.lexer.yylloc;
  114272. lstack.push(yyloc);
  114273. var ranges = this.lexer.options && this.lexer.options.ranges;
  114274. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  114275. function popStack(n) {
  114276. stack.length = stack.length - 2 * n;
  114277. vstack.length = vstack.length - n;
  114278. lstack.length = lstack.length - n;
  114279. }
  114280. function lex() {
  114281. var token;
  114282. token = self.lexer.lex() || 1;
  114283. if (typeof token !== "number") {
  114284. token = self.symbols_[token] || token;
  114285. }
  114286. return token;
  114287. }
  114288. var symbol,
  114289. preErrorSymbol,
  114290. state,
  114291. action,
  114292. a,
  114293. r,
  114294. yyval = {},
  114295. p,
  114296. len,
  114297. newState,
  114298. expected;
  114299. while (true) {
  114300. state = stack[stack.length - 1];
  114301. if (this.defaultActions[state]) {
  114302. action = this.defaultActions[state];
  114303. } else {
  114304. if (symbol === null || typeof symbol == "undefined") {
  114305. symbol = lex();
  114306. }
  114307. action = table[state] && table[state][symbol];
  114308. }
  114309. if (typeof action === "undefined" || !action.length || !action[0]) {
  114310. var errStr = "";
  114311. if (!recovering) {
  114312. expected = [];
  114313. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  114314. expected.push("'" + this.terminals_[p] + "'");
  114315. }
  114316. if (this.lexer.showPosition) {
  114317. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  114318. } else {
  114319. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  114320. }
  114321. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  114322. }
  114323. }
  114324. if (action[0] instanceof Array && action.length > 1) {
  114325. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  114326. }
  114327. switch (action[0]) {
  114328. case 1:
  114329. stack.push(symbol);
  114330. vstack.push(this.lexer.yytext);
  114331. lstack.push(this.lexer.yylloc);
  114332. stack.push(action[1]);
  114333. symbol = null;
  114334. if (!preErrorSymbol) {
  114335. yyleng = this.lexer.yyleng;
  114336. yytext = this.lexer.yytext;
  114337. yylineno = this.lexer.yylineno;
  114338. yyloc = this.lexer.yylloc;
  114339. if (recovering > 0) recovering--;
  114340. } else {
  114341. symbol = preErrorSymbol;
  114342. preErrorSymbol = null;
  114343. }
  114344. break;
  114345. case 2:
  114346. len = this.productions_[action[1]][1];
  114347. yyval.$ = vstack[vstack.length - len];
  114348. yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column };
  114349. if (ranges) {
  114350. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  114351. }
  114352. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  114353. if (typeof r !== "undefined") {
  114354. return r;
  114355. }
  114356. if (len) {
  114357. stack = stack.slice(0, -1 * len * 2);
  114358. vstack = vstack.slice(0, -1 * len);
  114359. lstack = lstack.slice(0, -1 * len);
  114360. }
  114361. stack.push(this.productions_[action[1]][0]);
  114362. vstack.push(yyval.$);
  114363. lstack.push(yyval._$);
  114364. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  114365. stack.push(newState);
  114366. break;
  114367. case 3:
  114368. return true;
  114369. }
  114370. }
  114371. return true;
  114372. }
  114373. };
  114374. /* Jison generated lexer */
  114375. var lexer = (function () {
  114376. var lexer = { EOF: 1,
  114377. parseError: function parseError(str, hash) {
  114378. if (this.yy.parser) {
  114379. this.yy.parser.parseError(str, hash);
  114380. } else {
  114381. throw new Error(str);
  114382. }
  114383. },
  114384. setInput: function setInput(input) {
  114385. this._input = input;
  114386. this._more = this._less = this.done = false;
  114387. this.yylineno = this.yyleng = 0;
  114388. this.yytext = this.matched = this.match = '';
  114389. this.conditionStack = ['INITIAL'];
  114390. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  114391. if (this.options.ranges) this.yylloc.range = [0, 0];
  114392. this.offset = 0;
  114393. return this;
  114394. },
  114395. input: function input() {
  114396. var ch = this._input[0];
  114397. this.yytext += ch;
  114398. this.yyleng++;
  114399. this.offset++;
  114400. this.match += ch;
  114401. this.matched += ch;
  114402. var lines = ch.match(/(?:\r\n?|\n).*/g);
  114403. if (lines) {
  114404. this.yylineno++;
  114405. this.yylloc.last_line++;
  114406. } else {
  114407. this.yylloc.last_column++;
  114408. }
  114409. if (this.options.ranges) this.yylloc.range[1]++;
  114410. this._input = this._input.slice(1);
  114411. return ch;
  114412. },
  114413. unput: function unput(ch) {
  114414. var len = ch.length;
  114415. var lines = ch.split(/(?:\r\n?|\n)/g);
  114416. this._input = ch + this._input;
  114417. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  114418. //this.yyleng -= len;
  114419. this.offset -= len;
  114420. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  114421. this.match = this.match.substr(0, this.match.length - 1);
  114422. this.matched = this.matched.substr(0, this.matched.length - 1);
  114423. if (lines.length - 1) this.yylineno -= lines.length - 1;
  114424. var r = this.yylloc.range;
  114425. this.yylloc = { first_line: this.yylloc.first_line,
  114426. last_line: this.yylineno + 1,
  114427. first_column: this.yylloc.first_column,
  114428. last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
  114429. };
  114430. if (this.options.ranges) {
  114431. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  114432. }
  114433. return this;
  114434. },
  114435. more: function more() {
  114436. this._more = true;
  114437. return this;
  114438. },
  114439. less: function less(n) {
  114440. this.unput(this.match.slice(n));
  114441. },
  114442. pastInput: function pastInput() {
  114443. var past = this.matched.substr(0, this.matched.length - this.match.length);
  114444. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  114445. },
  114446. upcomingInput: function upcomingInput() {
  114447. var next = this.match;
  114448. if (next.length < 20) {
  114449. next += this._input.substr(0, 20 - next.length);
  114450. }
  114451. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  114452. },
  114453. showPosition: function showPosition() {
  114454. var pre = this.pastInput();
  114455. var c = new Array(pre.length + 1).join("-");
  114456. return pre + this.upcomingInput() + "\n" + c + "^";
  114457. },
  114458. next: function next() {
  114459. if (this.done) {
  114460. return this.EOF;
  114461. }
  114462. if (!this._input) this.done = true;
  114463. var token, match, tempMatch, index, col, lines;
  114464. if (!this._more) {
  114465. this.yytext = '';
  114466. this.match = '';
  114467. }
  114468. var rules = this._currentRules();
  114469. for (var i = 0; i < rules.length; i++) {
  114470. tempMatch = this._input.match(this.rules[rules[i]]);
  114471. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  114472. match = tempMatch;
  114473. index = i;
  114474. if (!this.options.flex) break;
  114475. }
  114476. }
  114477. if (match) {
  114478. lines = match[0].match(/(?:\r\n?|\n).*/g);
  114479. if (lines) this.yylineno += lines.length;
  114480. this.yylloc = { first_line: this.yylloc.last_line,
  114481. last_line: this.yylineno + 1,
  114482. first_column: this.yylloc.last_column,
  114483. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  114484. this.yytext += match[0];
  114485. this.match += match[0];
  114486. this.matches = match;
  114487. this.yyleng = this.yytext.length;
  114488. if (this.options.ranges) {
  114489. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  114490. }
  114491. this._more = false;
  114492. this._input = this._input.slice(match[0].length);
  114493. this.matched += match[0];
  114494. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  114495. if (this.done && this._input) this.done = false;
  114496. if (token) return token;else return;
  114497. }
  114498. if (this._input === "") {
  114499. return this.EOF;
  114500. } else {
  114501. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  114502. }
  114503. },
  114504. lex: function lex() {
  114505. var r = this.next();
  114506. if (typeof r !== 'undefined') {
  114507. return r;
  114508. } else {
  114509. return this.lex();
  114510. }
  114511. },
  114512. begin: function begin(condition) {
  114513. this.conditionStack.push(condition);
  114514. },
  114515. popState: function popState() {
  114516. return this.conditionStack.pop();
  114517. },
  114518. _currentRules: function _currentRules() {
  114519. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  114520. },
  114521. topState: function topState() {
  114522. return this.conditionStack[this.conditionStack.length - 2];
  114523. },
  114524. pushState: function begin(condition) {
  114525. this.begin(condition);
  114526. } };
  114527. lexer.options = {};
  114528. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  114529. /**/) {
  114530. function strip(start, end) {
  114531. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  114532. }
  114533. var YYSTATE = YY_START;
  114534. switch ($avoiding_name_collisions) {
  114535. case 0:
  114536. if (yy_.yytext.slice(-2) === "\\\\") {
  114537. strip(0, 1);
  114538. this.begin("mu");
  114539. } else if (yy_.yytext.slice(-1) === "\\") {
  114540. strip(0, 1);
  114541. this.begin("emu");
  114542. } else {
  114543. this.begin("mu");
  114544. }
  114545. if (yy_.yytext) return 15;
  114546. break;
  114547. case 1:
  114548. return 15;
  114549. break;
  114550. case 2:
  114551. this.popState();
  114552. return 15;
  114553. break;
  114554. case 3:
  114555. this.begin('raw');return 15;
  114556. break;
  114557. case 4:
  114558. this.popState();
  114559. // Should be using `this.topState()` below, but it currently
  114560. // returns the second top instead of the first top. Opened an
  114561. // issue about it at https://github.com/zaach/jison/issues/291
  114562. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  114563. return 15;
  114564. } else {
  114565. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  114566. return 'END_RAW_BLOCK';
  114567. }
  114568. break;
  114569. case 5:
  114570. return 15;
  114571. break;
  114572. case 6:
  114573. this.popState();
  114574. return 14;
  114575. break;
  114576. case 7:
  114577. return 65;
  114578. break;
  114579. case 8:
  114580. return 68;
  114581. break;
  114582. case 9:
  114583. return 19;
  114584. break;
  114585. case 10:
  114586. this.popState();
  114587. this.begin('raw');
  114588. return 23;
  114589. break;
  114590. case 11:
  114591. return 55;
  114592. break;
  114593. case 12:
  114594. return 60;
  114595. break;
  114596. case 13:
  114597. return 29;
  114598. break;
  114599. case 14:
  114600. return 47;
  114601. break;
  114602. case 15:
  114603. this.popState();return 44;
  114604. break;
  114605. case 16:
  114606. this.popState();return 44;
  114607. break;
  114608. case 17:
  114609. return 34;
  114610. break;
  114611. case 18:
  114612. return 39;
  114613. break;
  114614. case 19:
  114615. return 51;
  114616. break;
  114617. case 20:
  114618. return 48;
  114619. break;
  114620. case 21:
  114621. this.unput(yy_.yytext);
  114622. this.popState();
  114623. this.begin('com');
  114624. break;
  114625. case 22:
  114626. this.popState();
  114627. return 14;
  114628. break;
  114629. case 23:
  114630. return 48;
  114631. break;
  114632. case 24:
  114633. return 73;
  114634. break;
  114635. case 25:
  114636. return 72;
  114637. break;
  114638. case 26:
  114639. return 72;
  114640. break;
  114641. case 27:
  114642. return 87;
  114643. break;
  114644. case 28:
  114645. // ignore whitespace
  114646. break;
  114647. case 29:
  114648. this.popState();return 54;
  114649. break;
  114650. case 30:
  114651. this.popState();return 33;
  114652. break;
  114653. case 31:
  114654. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  114655. break;
  114656. case 32:
  114657. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  114658. break;
  114659. case 33:
  114660. return 85;
  114661. break;
  114662. case 34:
  114663. return 82;
  114664. break;
  114665. case 35:
  114666. return 82;
  114667. break;
  114668. case 36:
  114669. return 83;
  114670. break;
  114671. case 37:
  114672. return 84;
  114673. break;
  114674. case 38:
  114675. return 81;
  114676. break;
  114677. case 39:
  114678. return 75;
  114679. break;
  114680. case 40:
  114681. return 77;
  114682. break;
  114683. case 41:
  114684. return 72;
  114685. break;
  114686. case 42:
  114687. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  114688. break;
  114689. case 43:
  114690. return 'INVALID';
  114691. break;
  114692. case 44:
  114693. return 5;
  114694. break;
  114695. }
  114696. };
  114697. lexer.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\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  114698. lexer.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": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } };
  114699. return lexer;
  114700. })();
  114701. parser.lexer = lexer;
  114702. function Parser() {
  114703. this.yy = {};
  114704. }Parser.prototype = parser;parser.Parser = Parser;
  114705. return new Parser();
  114706. })();exports["default"] = handlebars;
  114707. module.exports = exports["default"];
  114708. /***/ }),
  114709. /* 38 */
  114710. /***/ (function(module, exports, __webpack_require__) {
  114711. 'use strict';
  114712. var _interopRequireDefault = __webpack_require__(1)['default'];
  114713. exports.__esModule = true;
  114714. var _visitor = __webpack_require__(39);
  114715. var _visitor2 = _interopRequireDefault(_visitor);
  114716. function WhitespaceControl() {
  114717. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  114718. this.options = options;
  114719. }
  114720. WhitespaceControl.prototype = new _visitor2['default']();
  114721. WhitespaceControl.prototype.Program = function (program) {
  114722. var doStandalone = !this.options.ignoreStandalone;
  114723. var isRoot = !this.isRootSeen;
  114724. this.isRootSeen = true;
  114725. var body = program.body;
  114726. for (var i = 0, l = body.length; i < l; i++) {
  114727. var current = body[i],
  114728. strip = this.accept(current);
  114729. if (!strip) {
  114730. continue;
  114731. }
  114732. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  114733. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  114734. openStandalone = strip.openStandalone && _isPrevWhitespace,
  114735. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  114736. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  114737. if (strip.close) {
  114738. omitRight(body, i, true);
  114739. }
  114740. if (strip.open) {
  114741. omitLeft(body, i, true);
  114742. }
  114743. if (doStandalone && inlineStandalone) {
  114744. omitRight(body, i);
  114745. if (omitLeft(body, i)) {
  114746. // If we are on a standalone node, save the indent info for partials
  114747. if (current.type === 'PartialStatement') {
  114748. // Pull out the whitespace from the final line
  114749. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  114750. }
  114751. }
  114752. }
  114753. if (doStandalone && openStandalone) {
  114754. omitRight((current.program || current.inverse).body);
  114755. // Strip out the previous content node if it's whitespace only
  114756. omitLeft(body, i);
  114757. }
  114758. if (doStandalone && closeStandalone) {
  114759. // Always strip the next node
  114760. omitRight(body, i);
  114761. omitLeft((current.inverse || current.program).body);
  114762. }
  114763. }
  114764. return program;
  114765. };
  114766. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  114767. this.accept(block.program);
  114768. this.accept(block.inverse);
  114769. // Find the inverse program that is involed with whitespace stripping.
  114770. var program = block.program || block.inverse,
  114771. inverse = block.program && block.inverse,
  114772. firstInverse = inverse,
  114773. lastInverse = inverse;
  114774. if (inverse && inverse.chained) {
  114775. firstInverse = inverse.body[0].program;
  114776. // Walk the inverse chain to find the last inverse that is actually in the chain.
  114777. while (lastInverse.chained) {
  114778. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  114779. }
  114780. }
  114781. var strip = {
  114782. open: block.openStrip.open,
  114783. close: block.closeStrip.close,
  114784. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  114785. // so our parent can determine if we actually are standalone
  114786. openStandalone: isNextWhitespace(program.body),
  114787. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  114788. };
  114789. if (block.openStrip.close) {
  114790. omitRight(program.body, null, true);
  114791. }
  114792. if (inverse) {
  114793. var inverseStrip = block.inverseStrip;
  114794. if (inverseStrip.open) {
  114795. omitLeft(program.body, null, true);
  114796. }
  114797. if (inverseStrip.close) {
  114798. omitRight(firstInverse.body, null, true);
  114799. }
  114800. if (block.closeStrip.open) {
  114801. omitLeft(lastInverse.body, null, true);
  114802. }
  114803. // Find standalone else statments
  114804. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  114805. omitLeft(program.body);
  114806. omitRight(firstInverse.body);
  114807. }
  114808. } else if (block.closeStrip.open) {
  114809. omitLeft(program.body, null, true);
  114810. }
  114811. return strip;
  114812. };
  114813. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  114814. return mustache.strip;
  114815. };
  114816. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  114817. /* istanbul ignore next */
  114818. var strip = node.strip || {};
  114819. return {
  114820. inlineStandalone: true,
  114821. open: strip.open,
  114822. close: strip.close
  114823. };
  114824. };
  114825. function isPrevWhitespace(body, i, isRoot) {
  114826. if (i === undefined) {
  114827. i = body.length;
  114828. }
  114829. // Nodes that end with newlines are considered whitespace (but are special
  114830. // cased for strip operations)
  114831. var prev = body[i - 1],
  114832. sibling = body[i - 2];
  114833. if (!prev) {
  114834. return isRoot;
  114835. }
  114836. if (prev.type === 'ContentStatement') {
  114837. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  114838. }
  114839. }
  114840. function isNextWhitespace(body, i, isRoot) {
  114841. if (i === undefined) {
  114842. i = -1;
  114843. }
  114844. var next = body[i + 1],
  114845. sibling = body[i + 2];
  114846. if (!next) {
  114847. return isRoot;
  114848. }
  114849. if (next.type === 'ContentStatement') {
  114850. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  114851. }
  114852. }
  114853. // Marks the node to the right of the position as omitted.
  114854. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  114855. //
  114856. // If i is undefined, then the first child will be marked as such.
  114857. //
  114858. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  114859. // content is met.
  114860. function omitRight(body, i, multiple) {
  114861. var current = body[i == null ? 0 : i + 1];
  114862. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  114863. return;
  114864. }
  114865. var original = current.value;
  114866. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  114867. current.rightStripped = current.value !== original;
  114868. }
  114869. // Marks the node to the left of the position as omitted.
  114870. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  114871. //
  114872. // If i is undefined then the last child will be marked as such.
  114873. //
  114874. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  114875. // content is met.
  114876. function omitLeft(body, i, multiple) {
  114877. var current = body[i == null ? body.length - 1 : i - 1];
  114878. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  114879. return;
  114880. }
  114881. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  114882. var original = current.value;
  114883. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  114884. current.leftStripped = current.value !== original;
  114885. return current.leftStripped;
  114886. }
  114887. exports['default'] = WhitespaceControl;
  114888. module.exports = exports['default'];
  114889. /***/ }),
  114890. /* 39 */
  114891. /***/ (function(module, exports, __webpack_require__) {
  114892. 'use strict';
  114893. var _interopRequireDefault = __webpack_require__(1)['default'];
  114894. exports.__esModule = true;
  114895. var _exception = __webpack_require__(6);
  114896. var _exception2 = _interopRequireDefault(_exception);
  114897. function Visitor() {
  114898. this.parents = [];
  114899. }
  114900. Visitor.prototype = {
  114901. constructor: Visitor,
  114902. mutating: false,
  114903. // Visits a given value. If mutating, will replace the value if necessary.
  114904. acceptKey: function acceptKey(node, name) {
  114905. var value = this.accept(node[name]);
  114906. if (this.mutating) {
  114907. // Hacky sanity check: This may have a few false positives for type for the helper
  114908. // methods but will generally do the right thing without a lot of overhead.
  114909. if (value && !Visitor.prototype[value.type]) {
  114910. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  114911. }
  114912. node[name] = value;
  114913. }
  114914. },
  114915. // Performs an accept operation with added sanity check to ensure
  114916. // required keys are not removed.
  114917. acceptRequired: function acceptRequired(node, name) {
  114918. this.acceptKey(node, name);
  114919. if (!node[name]) {
  114920. throw new _exception2['default'](node.type + ' requires ' + name);
  114921. }
  114922. },
  114923. // Traverses a given array. If mutating, empty respnses will be removed
  114924. // for child elements.
  114925. acceptArray: function acceptArray(array) {
  114926. for (var i = 0, l = array.length; i < l; i++) {
  114927. this.acceptKey(array, i);
  114928. if (!array[i]) {
  114929. array.splice(i, 1);
  114930. i--;
  114931. l--;
  114932. }
  114933. }
  114934. },
  114935. accept: function accept(object) {
  114936. if (!object) {
  114937. return;
  114938. }
  114939. /* istanbul ignore next: Sanity code */
  114940. if (!this[object.type]) {
  114941. throw new _exception2['default']('Unknown type: ' + object.type, object);
  114942. }
  114943. if (this.current) {
  114944. this.parents.unshift(this.current);
  114945. }
  114946. this.current = object;
  114947. var ret = this[object.type](object);
  114948. this.current = this.parents.shift();
  114949. if (!this.mutating || ret) {
  114950. return ret;
  114951. } else if (ret !== false) {
  114952. return object;
  114953. }
  114954. },
  114955. Program: function Program(program) {
  114956. this.acceptArray(program.body);
  114957. },
  114958. MustacheStatement: visitSubExpression,
  114959. Decorator: visitSubExpression,
  114960. BlockStatement: visitBlock,
  114961. DecoratorBlock: visitBlock,
  114962. PartialStatement: visitPartial,
  114963. PartialBlockStatement: function PartialBlockStatement(partial) {
  114964. visitPartial.call(this, partial);
  114965. this.acceptKey(partial, 'program');
  114966. },
  114967. ContentStatement: function ContentStatement() /* content */{},
  114968. CommentStatement: function CommentStatement() /* comment */{},
  114969. SubExpression: visitSubExpression,
  114970. PathExpression: function PathExpression() /* path */{},
  114971. StringLiteral: function StringLiteral() /* string */{},
  114972. NumberLiteral: function NumberLiteral() /* number */{},
  114973. BooleanLiteral: function BooleanLiteral() /* bool */{},
  114974. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  114975. NullLiteral: function NullLiteral() /* literal */{},
  114976. Hash: function Hash(hash) {
  114977. this.acceptArray(hash.pairs);
  114978. },
  114979. HashPair: function HashPair(pair) {
  114980. this.acceptRequired(pair, 'value');
  114981. }
  114982. };
  114983. function visitSubExpression(mustache) {
  114984. this.acceptRequired(mustache, 'path');
  114985. this.acceptArray(mustache.params);
  114986. this.acceptKey(mustache, 'hash');
  114987. }
  114988. function visitBlock(block) {
  114989. visitSubExpression.call(this, block);
  114990. this.acceptKey(block, 'program');
  114991. this.acceptKey(block, 'inverse');
  114992. }
  114993. function visitPartial(partial) {
  114994. this.acceptRequired(partial, 'name');
  114995. this.acceptArray(partial.params);
  114996. this.acceptKey(partial, 'hash');
  114997. }
  114998. exports['default'] = Visitor;
  114999. module.exports = exports['default'];
  115000. /***/ }),
  115001. /* 40 */
  115002. /***/ (function(module, exports, __webpack_require__) {
  115003. 'use strict';
  115004. var _interopRequireDefault = __webpack_require__(1)['default'];
  115005. exports.__esModule = true;
  115006. exports.SourceLocation = SourceLocation;
  115007. exports.id = id;
  115008. exports.stripFlags = stripFlags;
  115009. exports.stripComment = stripComment;
  115010. exports.preparePath = preparePath;
  115011. exports.prepareMustache = prepareMustache;
  115012. exports.prepareRawBlock = prepareRawBlock;
  115013. exports.prepareBlock = prepareBlock;
  115014. exports.prepareProgram = prepareProgram;
  115015. exports.preparePartialBlock = preparePartialBlock;
  115016. var _exception = __webpack_require__(6);
  115017. var _exception2 = _interopRequireDefault(_exception);
  115018. function validateClose(open, close) {
  115019. close = close.path ? close.path.original : close;
  115020. if (open.path.original !== close) {
  115021. var errorNode = { loc: open.path.loc };
  115022. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  115023. }
  115024. }
  115025. function SourceLocation(source, locInfo) {
  115026. this.source = source;
  115027. this.start = {
  115028. line: locInfo.first_line,
  115029. column: locInfo.first_column
  115030. };
  115031. this.end = {
  115032. line: locInfo.last_line,
  115033. column: locInfo.last_column
  115034. };
  115035. }
  115036. function id(token) {
  115037. if (/^\[.*\]$/.test(token)) {
  115038. return token.substr(1, token.length - 2);
  115039. } else {
  115040. return token;
  115041. }
  115042. }
  115043. function stripFlags(open, close) {
  115044. return {
  115045. open: open.charAt(2) === '~',
  115046. close: close.charAt(close.length - 3) === '~'
  115047. };
  115048. }
  115049. function stripComment(comment) {
  115050. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  115051. }
  115052. function preparePath(data, parts, loc) {
  115053. loc = this.locInfo(loc);
  115054. var original = data ? '@' : '',
  115055. dig = [],
  115056. depth = 0,
  115057. depthString = '';
  115058. for (var i = 0, l = parts.length; i < l; i++) {
  115059. var part = parts[i].part,
  115060. // If we have [] syntax then we do not treat path references as operators,
  115061. // i.e. foo.[this] resolves to approximately context.foo['this']
  115062. isLiteral = parts[i].original !== part;
  115063. original += (parts[i].separator || '') + part;
  115064. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  115065. if (dig.length > 0) {
  115066. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  115067. } else if (part === '..') {
  115068. depth++;
  115069. depthString += '../';
  115070. }
  115071. } else {
  115072. dig.push(part);
  115073. }
  115074. }
  115075. return {
  115076. type: 'PathExpression',
  115077. data: data,
  115078. depth: depth,
  115079. parts: dig,
  115080. original: original,
  115081. loc: loc
  115082. };
  115083. }
  115084. function prepareMustache(path, params, hash, open, strip, locInfo) {
  115085. // Must use charAt to support IE pre-10
  115086. var escapeFlag = open.charAt(3) || open.charAt(2),
  115087. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  115088. var decorator = /\*/.test(open);
  115089. return {
  115090. type: decorator ? 'Decorator' : 'MustacheStatement',
  115091. path: path,
  115092. params: params,
  115093. hash: hash,
  115094. escaped: escaped,
  115095. strip: strip,
  115096. loc: this.locInfo(locInfo)
  115097. };
  115098. }
  115099. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  115100. validateClose(openRawBlock, close);
  115101. locInfo = this.locInfo(locInfo);
  115102. var program = {
  115103. type: 'Program',
  115104. body: contents,
  115105. strip: {},
  115106. loc: locInfo
  115107. };
  115108. return {
  115109. type: 'BlockStatement',
  115110. path: openRawBlock.path,
  115111. params: openRawBlock.params,
  115112. hash: openRawBlock.hash,
  115113. program: program,
  115114. openStrip: {},
  115115. inverseStrip: {},
  115116. closeStrip: {},
  115117. loc: locInfo
  115118. };
  115119. }
  115120. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  115121. if (close && close.path) {
  115122. validateClose(openBlock, close);
  115123. }
  115124. var decorator = /\*/.test(openBlock.open);
  115125. program.blockParams = openBlock.blockParams;
  115126. var inverse = undefined,
  115127. inverseStrip = undefined;
  115128. if (inverseAndProgram) {
  115129. if (decorator) {
  115130. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  115131. }
  115132. if (inverseAndProgram.chain) {
  115133. inverseAndProgram.program.body[0].closeStrip = close.strip;
  115134. }
  115135. inverseStrip = inverseAndProgram.strip;
  115136. inverse = inverseAndProgram.program;
  115137. }
  115138. if (inverted) {
  115139. inverted = inverse;
  115140. inverse = program;
  115141. program = inverted;
  115142. }
  115143. return {
  115144. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  115145. path: openBlock.path,
  115146. params: openBlock.params,
  115147. hash: openBlock.hash,
  115148. program: program,
  115149. inverse: inverse,
  115150. openStrip: openBlock.strip,
  115151. inverseStrip: inverseStrip,
  115152. closeStrip: close && close.strip,
  115153. loc: this.locInfo(locInfo)
  115154. };
  115155. }
  115156. function prepareProgram(statements, loc) {
  115157. if (!loc && statements.length) {
  115158. var firstLoc = statements[0].loc,
  115159. lastLoc = statements[statements.length - 1].loc;
  115160. /* istanbul ignore else */
  115161. if (firstLoc && lastLoc) {
  115162. loc = {
  115163. source: firstLoc.source,
  115164. start: {
  115165. line: firstLoc.start.line,
  115166. column: firstLoc.start.column
  115167. },
  115168. end: {
  115169. line: lastLoc.end.line,
  115170. column: lastLoc.end.column
  115171. }
  115172. };
  115173. }
  115174. }
  115175. return {
  115176. type: 'Program',
  115177. body: statements,
  115178. strip: {},
  115179. loc: loc
  115180. };
  115181. }
  115182. function preparePartialBlock(open, program, close, locInfo) {
  115183. validateClose(open, close);
  115184. return {
  115185. type: 'PartialBlockStatement',
  115186. name: open.path,
  115187. params: open.params,
  115188. hash: open.hash,
  115189. program: program,
  115190. openStrip: open.strip,
  115191. closeStrip: close && close.strip,
  115192. loc: this.locInfo(locInfo)
  115193. };
  115194. }
  115195. /***/ }),
  115196. /* 41 */
  115197. /***/ (function(module, exports, __webpack_require__) {
  115198. /* eslint-disable new-cap */
  115199. 'use strict';
  115200. var _interopRequireDefault = __webpack_require__(1)['default'];
  115201. exports.__esModule = true;
  115202. exports.Compiler = Compiler;
  115203. exports.precompile = precompile;
  115204. exports.compile = compile;
  115205. var _exception = __webpack_require__(6);
  115206. var _exception2 = _interopRequireDefault(_exception);
  115207. var _utils = __webpack_require__(5);
  115208. var _ast = __webpack_require__(35);
  115209. var _ast2 = _interopRequireDefault(_ast);
  115210. var slice = [].slice;
  115211. function Compiler() {}
  115212. // the foundHelper register will disambiguate helper lookup from finding a
  115213. // function in a context. This is necessary for mustache compatibility, which
  115214. // requires that context functions in blocks are evaluated by blockHelperMissing,
  115215. // and then proceed as if the resulting value was provided to blockHelperMissing.
  115216. Compiler.prototype = {
  115217. compiler: Compiler,
  115218. equals: function equals(other) {
  115219. var len = this.opcodes.length;
  115220. if (other.opcodes.length !== len) {
  115221. return false;
  115222. }
  115223. for (var i = 0; i < len; i++) {
  115224. var opcode = this.opcodes[i],
  115225. otherOpcode = other.opcodes[i];
  115226. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  115227. return false;
  115228. }
  115229. }
  115230. // We know that length is the same between the two arrays because they are directly tied
  115231. // to the opcode behavior above.
  115232. len = this.children.length;
  115233. for (var i = 0; i < len; i++) {
  115234. if (!this.children[i].equals(other.children[i])) {
  115235. return false;
  115236. }
  115237. }
  115238. return true;
  115239. },
  115240. guid: 0,
  115241. compile: function compile(program, options) {
  115242. this.sourceNode = [];
  115243. this.opcodes = [];
  115244. this.children = [];
  115245. this.options = options;
  115246. this.stringParams = options.stringParams;
  115247. this.trackIds = options.trackIds;
  115248. options.blockParams = options.blockParams || [];
  115249. // These changes will propagate to the other compiler components
  115250. var knownHelpers = options.knownHelpers;
  115251. options.knownHelpers = {
  115252. 'helperMissing': true,
  115253. 'blockHelperMissing': true,
  115254. 'each': true,
  115255. 'if': true,
  115256. 'unless': true,
  115257. 'with': true,
  115258. 'log': true,
  115259. 'lookup': true
  115260. };
  115261. if (knownHelpers) {
  115262. for (var _name in knownHelpers) {
  115263. /* istanbul ignore else */
  115264. if (_name in knownHelpers) {
  115265. this.options.knownHelpers[_name] = knownHelpers[_name];
  115266. }
  115267. }
  115268. }
  115269. return this.accept(program);
  115270. },
  115271. compileProgram: function compileProgram(program) {
  115272. var childCompiler = new this.compiler(),
  115273. // eslint-disable-line new-cap
  115274. result = childCompiler.compile(program, this.options),
  115275. guid = this.guid++;
  115276. this.usePartial = this.usePartial || result.usePartial;
  115277. this.children[guid] = result;
  115278. this.useDepths = this.useDepths || result.useDepths;
  115279. return guid;
  115280. },
  115281. accept: function accept(node) {
  115282. /* istanbul ignore next: Sanity code */
  115283. if (!this[node.type]) {
  115284. throw new _exception2['default']('Unknown type: ' + node.type, node);
  115285. }
  115286. this.sourceNode.unshift(node);
  115287. var ret = this[node.type](node);
  115288. this.sourceNode.shift();
  115289. return ret;
  115290. },
  115291. Program: function Program(program) {
  115292. this.options.blockParams.unshift(program.blockParams);
  115293. var body = program.body,
  115294. bodyLength = body.length;
  115295. for (var i = 0; i < bodyLength; i++) {
  115296. this.accept(body[i]);
  115297. }
  115298. this.options.blockParams.shift();
  115299. this.isSimple = bodyLength === 1;
  115300. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  115301. return this;
  115302. },
  115303. BlockStatement: function BlockStatement(block) {
  115304. transformLiteralToPath(block);
  115305. var program = block.program,
  115306. inverse = block.inverse;
  115307. program = program && this.compileProgram(program);
  115308. inverse = inverse && this.compileProgram(inverse);
  115309. var type = this.classifySexpr(block);
  115310. if (type === 'helper') {
  115311. this.helperSexpr(block, program, inverse);
  115312. } else if (type === 'simple') {
  115313. this.simpleSexpr(block);
  115314. // now that the simple mustache is resolved, we need to
  115315. // evaluate it by executing `blockHelperMissing`
  115316. this.opcode('pushProgram', program);
  115317. this.opcode('pushProgram', inverse);
  115318. this.opcode('emptyHash');
  115319. this.opcode('blockValue', block.path.original);
  115320. } else {
  115321. this.ambiguousSexpr(block, program, inverse);
  115322. // now that the simple mustache is resolved, we need to
  115323. // evaluate it by executing `blockHelperMissing`
  115324. this.opcode('pushProgram', program);
  115325. this.opcode('pushProgram', inverse);
  115326. this.opcode('emptyHash');
  115327. this.opcode('ambiguousBlockValue');
  115328. }
  115329. this.opcode('append');
  115330. },
  115331. DecoratorBlock: function DecoratorBlock(decorator) {
  115332. var program = decorator.program && this.compileProgram(decorator.program);
  115333. var params = this.setupFullMustacheParams(decorator, program, undefined),
  115334. path = decorator.path;
  115335. this.useDecorators = true;
  115336. this.opcode('registerDecorator', params.length, path.original);
  115337. },
  115338. PartialStatement: function PartialStatement(partial) {
  115339. this.usePartial = true;
  115340. var program = partial.program;
  115341. if (program) {
  115342. program = this.compileProgram(partial.program);
  115343. }
  115344. var params = partial.params;
  115345. if (params.length > 1) {
  115346. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  115347. } else if (!params.length) {
  115348. if (this.options.explicitPartialContext) {
  115349. this.opcode('pushLiteral', 'undefined');
  115350. } else {
  115351. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  115352. }
  115353. }
  115354. var partialName = partial.name.original,
  115355. isDynamic = partial.name.type === 'SubExpression';
  115356. if (isDynamic) {
  115357. this.accept(partial.name);
  115358. }
  115359. this.setupFullMustacheParams(partial, program, undefined, true);
  115360. var indent = partial.indent || '';
  115361. if (this.options.preventIndent && indent) {
  115362. this.opcode('appendContent', indent);
  115363. indent = '';
  115364. }
  115365. this.opcode('invokePartial', isDynamic, partialName, indent);
  115366. this.opcode('append');
  115367. },
  115368. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  115369. this.PartialStatement(partialBlock);
  115370. },
  115371. MustacheStatement: function MustacheStatement(mustache) {
  115372. this.SubExpression(mustache);
  115373. if (mustache.escaped && !this.options.noEscape) {
  115374. this.opcode('appendEscaped');
  115375. } else {
  115376. this.opcode('append');
  115377. }
  115378. },
  115379. Decorator: function Decorator(decorator) {
  115380. this.DecoratorBlock(decorator);
  115381. },
  115382. ContentStatement: function ContentStatement(content) {
  115383. if (content.value) {
  115384. this.opcode('appendContent', content.value);
  115385. }
  115386. },
  115387. CommentStatement: function CommentStatement() {},
  115388. SubExpression: function SubExpression(sexpr) {
  115389. transformLiteralToPath(sexpr);
  115390. var type = this.classifySexpr(sexpr);
  115391. if (type === 'simple') {
  115392. this.simpleSexpr(sexpr);
  115393. } else if (type === 'helper') {
  115394. this.helperSexpr(sexpr);
  115395. } else {
  115396. this.ambiguousSexpr(sexpr);
  115397. }
  115398. },
  115399. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  115400. var path = sexpr.path,
  115401. name = path.parts[0],
  115402. isBlock = program != null || inverse != null;
  115403. this.opcode('getContext', path.depth);
  115404. this.opcode('pushProgram', program);
  115405. this.opcode('pushProgram', inverse);
  115406. path.strict = true;
  115407. this.accept(path);
  115408. this.opcode('invokeAmbiguous', name, isBlock);
  115409. },
  115410. simpleSexpr: function simpleSexpr(sexpr) {
  115411. var path = sexpr.path;
  115412. path.strict = true;
  115413. this.accept(path);
  115414. this.opcode('resolvePossibleLambda');
  115415. },
  115416. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  115417. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  115418. path = sexpr.path,
  115419. name = path.parts[0];
  115420. if (this.options.knownHelpers[name]) {
  115421. this.opcode('invokeKnownHelper', params.length, name);
  115422. } else if (this.options.knownHelpersOnly) {
  115423. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  115424. } else {
  115425. path.strict = true;
  115426. path.falsy = true;
  115427. this.accept(path);
  115428. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  115429. }
  115430. },
  115431. PathExpression: function PathExpression(path) {
  115432. this.addDepth(path.depth);
  115433. this.opcode('getContext', path.depth);
  115434. var name = path.parts[0],
  115435. scoped = _ast2['default'].helpers.scopedId(path),
  115436. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  115437. if (blockParamId) {
  115438. this.opcode('lookupBlockParam', blockParamId, path.parts);
  115439. } else if (!name) {
  115440. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  115441. this.opcode('pushContext');
  115442. } else if (path.data) {
  115443. this.options.data = true;
  115444. this.opcode('lookupData', path.depth, path.parts, path.strict);
  115445. } else {
  115446. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  115447. }
  115448. },
  115449. StringLiteral: function StringLiteral(string) {
  115450. this.opcode('pushString', string.value);
  115451. },
  115452. NumberLiteral: function NumberLiteral(number) {
  115453. this.opcode('pushLiteral', number.value);
  115454. },
  115455. BooleanLiteral: function BooleanLiteral(bool) {
  115456. this.opcode('pushLiteral', bool.value);
  115457. },
  115458. UndefinedLiteral: function UndefinedLiteral() {
  115459. this.opcode('pushLiteral', 'undefined');
  115460. },
  115461. NullLiteral: function NullLiteral() {
  115462. this.opcode('pushLiteral', 'null');
  115463. },
  115464. Hash: function Hash(hash) {
  115465. var pairs = hash.pairs,
  115466. i = 0,
  115467. l = pairs.length;
  115468. this.opcode('pushHash');
  115469. for (; i < l; i++) {
  115470. this.pushParam(pairs[i].value);
  115471. }
  115472. while (i--) {
  115473. this.opcode('assignToHash', pairs[i].key);
  115474. }
  115475. this.opcode('popHash');
  115476. },
  115477. // HELPERS
  115478. opcode: function opcode(name) {
  115479. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  115480. },
  115481. addDepth: function addDepth(depth) {
  115482. if (!depth) {
  115483. return;
  115484. }
  115485. this.useDepths = true;
  115486. },
  115487. classifySexpr: function classifySexpr(sexpr) {
  115488. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  115489. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  115490. // a mustache is an eligible helper if:
  115491. // * its id is simple (a single part, not `this` or `..`)
  115492. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  115493. // if a mustache is an eligible helper but not a definite
  115494. // helper, it is ambiguous, and will be resolved in a later
  115495. // pass or at runtime.
  115496. var isEligible = !isBlockParam && (isHelper || isSimple);
  115497. // if ambiguous, we can possibly resolve the ambiguity now
  115498. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  115499. if (isEligible && !isHelper) {
  115500. var _name2 = sexpr.path.parts[0],
  115501. options = this.options;
  115502. if (options.knownHelpers[_name2]) {
  115503. isHelper = true;
  115504. } else if (options.knownHelpersOnly) {
  115505. isEligible = false;
  115506. }
  115507. }
  115508. if (isHelper) {
  115509. return 'helper';
  115510. } else if (isEligible) {
  115511. return 'ambiguous';
  115512. } else {
  115513. return 'simple';
  115514. }
  115515. },
  115516. pushParams: function pushParams(params) {
  115517. for (var i = 0, l = params.length; i < l; i++) {
  115518. this.pushParam(params[i]);
  115519. }
  115520. },
  115521. pushParam: function pushParam(val) {
  115522. var value = val.value != null ? val.value : val.original || '';
  115523. if (this.stringParams) {
  115524. if (value.replace) {
  115525. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  115526. }
  115527. if (val.depth) {
  115528. this.addDepth(val.depth);
  115529. }
  115530. this.opcode('getContext', val.depth || 0);
  115531. this.opcode('pushStringParam', value, val.type);
  115532. if (val.type === 'SubExpression') {
  115533. // SubExpressions get evaluated and passed in
  115534. // in string params mode.
  115535. this.accept(val);
  115536. }
  115537. } else {
  115538. if (this.trackIds) {
  115539. var blockParamIndex = undefined;
  115540. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  115541. blockParamIndex = this.blockParamIndex(val.parts[0]);
  115542. }
  115543. if (blockParamIndex) {
  115544. var blockParamChild = val.parts.slice(1).join('.');
  115545. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  115546. } else {
  115547. value = val.original || value;
  115548. if (value.replace) {
  115549. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  115550. }
  115551. this.opcode('pushId', val.type, value);
  115552. }
  115553. }
  115554. this.accept(val);
  115555. }
  115556. },
  115557. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  115558. var params = sexpr.params;
  115559. this.pushParams(params);
  115560. this.opcode('pushProgram', program);
  115561. this.opcode('pushProgram', inverse);
  115562. if (sexpr.hash) {
  115563. this.accept(sexpr.hash);
  115564. } else {
  115565. this.opcode('emptyHash', omitEmpty);
  115566. }
  115567. return params;
  115568. },
  115569. blockParamIndex: function blockParamIndex(name) {
  115570. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  115571. var blockParams = this.options.blockParams[depth],
  115572. param = blockParams && _utils.indexOf(blockParams, name);
  115573. if (blockParams && param >= 0) {
  115574. return [depth, param];
  115575. }
  115576. }
  115577. }
  115578. };
  115579. function precompile(input, options, env) {
  115580. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  115581. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  115582. }
  115583. options = options || {};
  115584. if (!('data' in options)) {
  115585. options.data = true;
  115586. }
  115587. if (options.compat) {
  115588. options.useDepths = true;
  115589. }
  115590. var ast = env.parse(input, options),
  115591. environment = new env.Compiler().compile(ast, options);
  115592. return new env.JavaScriptCompiler().compile(environment, options);
  115593. }
  115594. function compile(input, options, env) {
  115595. if (options === undefined) options = {};
  115596. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  115597. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  115598. }
  115599. options = _utils.extend({}, options);
  115600. if (!('data' in options)) {
  115601. options.data = true;
  115602. }
  115603. if (options.compat) {
  115604. options.useDepths = true;
  115605. }
  115606. var compiled = undefined;
  115607. function compileInput() {
  115608. var ast = env.parse(input, options),
  115609. environment = new env.Compiler().compile(ast, options),
  115610. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  115611. return env.template(templateSpec);
  115612. }
  115613. // Template is only compiled on first use and cached after that point.
  115614. function ret(context, execOptions) {
  115615. if (!compiled) {
  115616. compiled = compileInput();
  115617. }
  115618. return compiled.call(this, context, execOptions);
  115619. }
  115620. ret._setup = function (setupOptions) {
  115621. if (!compiled) {
  115622. compiled = compileInput();
  115623. }
  115624. return compiled._setup(setupOptions);
  115625. };
  115626. ret._child = function (i, data, blockParams, depths) {
  115627. if (!compiled) {
  115628. compiled = compileInput();
  115629. }
  115630. return compiled._child(i, data, blockParams, depths);
  115631. };
  115632. return ret;
  115633. }
  115634. function argEquals(a, b) {
  115635. if (a === b) {
  115636. return true;
  115637. }
  115638. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  115639. for (var i = 0; i < a.length; i++) {
  115640. if (!argEquals(a[i], b[i])) {
  115641. return false;
  115642. }
  115643. }
  115644. return true;
  115645. }
  115646. }
  115647. function transformLiteralToPath(sexpr) {
  115648. if (!sexpr.path.parts) {
  115649. var literal = sexpr.path;
  115650. // Casting to string here to make false and 0 literal values play nicely with the rest
  115651. // of the system.
  115652. sexpr.path = {
  115653. type: 'PathExpression',
  115654. data: false,
  115655. depth: 0,
  115656. parts: [literal.original + ''],
  115657. original: literal.original + '',
  115658. loc: literal.loc
  115659. };
  115660. }
  115661. }
  115662. /***/ }),
  115663. /* 42 */
  115664. /***/ (function(module, exports, __webpack_require__) {
  115665. 'use strict';
  115666. var _interopRequireDefault = __webpack_require__(1)['default'];
  115667. exports.__esModule = true;
  115668. var _base = __webpack_require__(4);
  115669. var _exception = __webpack_require__(6);
  115670. var _exception2 = _interopRequireDefault(_exception);
  115671. var _utils = __webpack_require__(5);
  115672. var _codeGen = __webpack_require__(43);
  115673. var _codeGen2 = _interopRequireDefault(_codeGen);
  115674. function Literal(value) {
  115675. this.value = value;
  115676. }
  115677. function JavaScriptCompiler() {}
  115678. JavaScriptCompiler.prototype = {
  115679. // PUBLIC API: You can override these methods in a subclass to provide
  115680. // alternative compiled forms for name lookup and buffering semantics
  115681. nameLookup: function nameLookup(parent, name /* , type*/) {
  115682. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  115683. return [parent, '.', name];
  115684. } else {
  115685. return [parent, '[', JSON.stringify(name), ']'];
  115686. }
  115687. },
  115688. depthedLookup: function depthedLookup(name) {
  115689. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  115690. },
  115691. compilerInfo: function compilerInfo() {
  115692. var revision = _base.COMPILER_REVISION,
  115693. versions = _base.REVISION_CHANGES[revision];
  115694. return [revision, versions];
  115695. },
  115696. appendToBuffer: function appendToBuffer(source, location, explicit) {
  115697. // Force a source as this simplifies the merge logic.
  115698. if (!_utils.isArray(source)) {
  115699. source = [source];
  115700. }
  115701. source = this.source.wrap(source, location);
  115702. if (this.environment.isSimple) {
  115703. return ['return ', source, ';'];
  115704. } else if (explicit) {
  115705. // This is a case where the buffer operation occurs as a child of another
  115706. // construct, generally braces. We have to explicitly output these buffer
  115707. // operations to ensure that the emitted code goes in the correct location.
  115708. return ['buffer += ', source, ';'];
  115709. } else {
  115710. source.appendToBuffer = true;
  115711. return source;
  115712. }
  115713. },
  115714. initializeBuffer: function initializeBuffer() {
  115715. return this.quotedString('');
  115716. },
  115717. // END PUBLIC API
  115718. compile: function compile(environment, options, context, asObject) {
  115719. this.environment = environment;
  115720. this.options = options;
  115721. this.stringParams = this.options.stringParams;
  115722. this.trackIds = this.options.trackIds;
  115723. this.precompile = !asObject;
  115724. this.name = this.environment.name;
  115725. this.isChild = !!context;
  115726. this.context = context || {
  115727. decorators: [],
  115728. programs: [],
  115729. environments: []
  115730. };
  115731. this.preamble();
  115732. this.stackSlot = 0;
  115733. this.stackVars = [];
  115734. this.aliases = {};
  115735. this.registers = { list: [] };
  115736. this.hashes = [];
  115737. this.compileStack = [];
  115738. this.inlineStack = [];
  115739. this.blockParams = [];
  115740. this.compileChildren(environment, options);
  115741. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  115742. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  115743. var opcodes = environment.opcodes,
  115744. opcode = undefined,
  115745. firstLoc = undefined,
  115746. i = undefined,
  115747. l = undefined;
  115748. for (i = 0, l = opcodes.length; i < l; i++) {
  115749. opcode = opcodes[i];
  115750. this.source.currentLocation = opcode.loc;
  115751. firstLoc = firstLoc || opcode.loc;
  115752. this[opcode.opcode].apply(this, opcode.args);
  115753. }
  115754. // Flush any trailing content that might be pending.
  115755. this.source.currentLocation = firstLoc;
  115756. this.pushSource('');
  115757. /* istanbul ignore next */
  115758. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  115759. throw new _exception2['default']('Compile completed with content left on stack');
  115760. }
  115761. if (!this.decorators.isEmpty()) {
  115762. this.useDecorators = true;
  115763. this.decorators.prepend('var decorators = container.decorators;\n');
  115764. this.decorators.push('return fn;');
  115765. if (asObject) {
  115766. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  115767. } else {
  115768. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  115769. this.decorators.push('}\n');
  115770. this.decorators = this.decorators.merge();
  115771. }
  115772. } else {
  115773. this.decorators = undefined;
  115774. }
  115775. var fn = this.createFunctionContext(asObject);
  115776. if (!this.isChild) {
  115777. var ret = {
  115778. compiler: this.compilerInfo(),
  115779. main: fn
  115780. };
  115781. if (this.decorators) {
  115782. ret.main_d = this.decorators; // eslint-disable-line camelcase
  115783. ret.useDecorators = true;
  115784. }
  115785. var _context = this.context;
  115786. var programs = _context.programs;
  115787. var decorators = _context.decorators;
  115788. for (i = 0, l = programs.length; i < l; i++) {
  115789. if (programs[i]) {
  115790. ret[i] = programs[i];
  115791. if (decorators[i]) {
  115792. ret[i + '_d'] = decorators[i];
  115793. ret.useDecorators = true;
  115794. }
  115795. }
  115796. }
  115797. if (this.environment.usePartial) {
  115798. ret.usePartial = true;
  115799. }
  115800. if (this.options.data) {
  115801. ret.useData = true;
  115802. }
  115803. if (this.useDepths) {
  115804. ret.useDepths = true;
  115805. }
  115806. if (this.useBlockParams) {
  115807. ret.useBlockParams = true;
  115808. }
  115809. if (this.options.compat) {
  115810. ret.compat = true;
  115811. }
  115812. if (!asObject) {
  115813. ret.compiler = JSON.stringify(ret.compiler);
  115814. this.source.currentLocation = { start: { line: 1, column: 0 } };
  115815. ret = this.objectLiteral(ret);
  115816. if (options.srcName) {
  115817. ret = ret.toStringWithSourceMap({ file: options.destName });
  115818. ret.map = ret.map && ret.map.toString();
  115819. } else {
  115820. ret = ret.toString();
  115821. }
  115822. } else {
  115823. ret.compilerOptions = this.options;
  115824. }
  115825. return ret;
  115826. } else {
  115827. return fn;
  115828. }
  115829. },
  115830. preamble: function preamble() {
  115831. // track the last context pushed into place to allow skipping the
  115832. // getContext opcode when it would be a noop
  115833. this.lastContext = 0;
  115834. this.source = new _codeGen2['default'](this.options.srcName);
  115835. this.decorators = new _codeGen2['default'](this.options.srcName);
  115836. },
  115837. createFunctionContext: function createFunctionContext(asObject) {
  115838. var varDeclarations = '';
  115839. var locals = this.stackVars.concat(this.registers.list);
  115840. if (locals.length > 0) {
  115841. varDeclarations += ', ' + locals.join(', ');
  115842. }
  115843. // Generate minimizer alias mappings
  115844. //
  115845. // When using true SourceNodes, this will update all references to the given alias
  115846. // as the source nodes are reused in situ. For the non-source node compilation mode,
  115847. // aliases will not be used, but this case is already being run on the client and
  115848. // we aren't concern about minimizing the template size.
  115849. var aliasCount = 0;
  115850. for (var alias in this.aliases) {
  115851. // eslint-disable-line guard-for-in
  115852. var node = this.aliases[alias];
  115853. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  115854. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  115855. node.children[0] = 'alias' + aliasCount;
  115856. }
  115857. }
  115858. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  115859. if (this.useBlockParams || this.useDepths) {
  115860. params.push('blockParams');
  115861. }
  115862. if (this.useDepths) {
  115863. params.push('depths');
  115864. }
  115865. // Perform a second pass over the output to merge content when possible
  115866. var source = this.mergeSource(varDeclarations);
  115867. if (asObject) {
  115868. params.push(source);
  115869. return Function.apply(this, params);
  115870. } else {
  115871. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  115872. }
  115873. },
  115874. mergeSource: function mergeSource(varDeclarations) {
  115875. var isSimple = this.environment.isSimple,
  115876. appendOnly = !this.forceBuffer,
  115877. appendFirst = undefined,
  115878. sourceSeen = undefined,
  115879. bufferStart = undefined,
  115880. bufferEnd = undefined;
  115881. this.source.each(function (line) {
  115882. if (line.appendToBuffer) {
  115883. if (bufferStart) {
  115884. line.prepend(' + ');
  115885. } else {
  115886. bufferStart = line;
  115887. }
  115888. bufferEnd = line;
  115889. } else {
  115890. if (bufferStart) {
  115891. if (!sourceSeen) {
  115892. appendFirst = true;
  115893. } else {
  115894. bufferStart.prepend('buffer += ');
  115895. }
  115896. bufferEnd.add(';');
  115897. bufferStart = bufferEnd = undefined;
  115898. }
  115899. sourceSeen = true;
  115900. if (!isSimple) {
  115901. appendOnly = false;
  115902. }
  115903. }
  115904. });
  115905. if (appendOnly) {
  115906. if (bufferStart) {
  115907. bufferStart.prepend('return ');
  115908. bufferEnd.add(';');
  115909. } else if (!sourceSeen) {
  115910. this.source.push('return "";');
  115911. }
  115912. } else {
  115913. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  115914. if (bufferStart) {
  115915. bufferStart.prepend('return buffer + ');
  115916. bufferEnd.add(';');
  115917. } else {
  115918. this.source.push('return buffer;');
  115919. }
  115920. }
  115921. if (varDeclarations) {
  115922. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  115923. }
  115924. return this.source.merge();
  115925. },
  115926. // [blockValue]
  115927. //
  115928. // On stack, before: hash, inverse, program, value
  115929. // On stack, after: return value of blockHelperMissing
  115930. //
  115931. // The purpose of this opcode is to take a block of the form
  115932. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  115933. // replace it on the stack with the result of properly
  115934. // invoking blockHelperMissing.
  115935. blockValue: function blockValue(name) {
  115936. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  115937. params = [this.contextName(0)];
  115938. this.setupHelperArgs(name, 0, params);
  115939. var blockName = this.popStack();
  115940. params.splice(1, 0, blockName);
  115941. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  115942. },
  115943. // [ambiguousBlockValue]
  115944. //
  115945. // On stack, before: hash, inverse, program, value
  115946. // Compiler value, before: lastHelper=value of last found helper, if any
  115947. // On stack, after, if no lastHelper: same as [blockValue]
  115948. // On stack, after, if lastHelper: value
  115949. ambiguousBlockValue: function ambiguousBlockValue() {
  115950. // We're being a bit cheeky and reusing the options value from the prior exec
  115951. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  115952. params = [this.contextName(0)];
  115953. this.setupHelperArgs('', 0, params, true);
  115954. this.flushInline();
  115955. var current = this.topStack();
  115956. params.splice(1, 0, current);
  115957. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  115958. },
  115959. // [appendContent]
  115960. //
  115961. // On stack, before: ...
  115962. // On stack, after: ...
  115963. //
  115964. // Appends the string value of `content` to the current buffer
  115965. appendContent: function appendContent(content) {
  115966. if (this.pendingContent) {
  115967. content = this.pendingContent + content;
  115968. } else {
  115969. this.pendingLocation = this.source.currentLocation;
  115970. }
  115971. this.pendingContent = content;
  115972. },
  115973. // [append]
  115974. //
  115975. // On stack, before: value, ...
  115976. // On stack, after: ...
  115977. //
  115978. // Coerces `value` to a String and appends it to the current buffer.
  115979. //
  115980. // If `value` is truthy, or 0, it is coerced into a string and appended
  115981. // Otherwise, the empty string is appended
  115982. append: function append() {
  115983. if (this.isInline()) {
  115984. this.replaceStack(function (current) {
  115985. return [' != null ? ', current, ' : ""'];
  115986. });
  115987. this.pushSource(this.appendToBuffer(this.popStack()));
  115988. } else {
  115989. var local = this.popStack();
  115990. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  115991. if (this.environment.isSimple) {
  115992. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  115993. }
  115994. }
  115995. },
  115996. // [appendEscaped]
  115997. //
  115998. // On stack, before: value, ...
  115999. // On stack, after: ...
  116000. //
  116001. // Escape `value` and append it to the buffer
  116002. appendEscaped: function appendEscaped() {
  116003. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  116004. },
  116005. // [getContext]
  116006. //
  116007. // On stack, before: ...
  116008. // On stack, after: ...
  116009. // Compiler value, after: lastContext=depth
  116010. //
  116011. // Set the value of the `lastContext` compiler value to the depth
  116012. getContext: function getContext(depth) {
  116013. this.lastContext = depth;
  116014. },
  116015. // [pushContext]
  116016. //
  116017. // On stack, before: ...
  116018. // On stack, after: currentContext, ...
  116019. //
  116020. // Pushes the value of the current context onto the stack.
  116021. pushContext: function pushContext() {
  116022. this.pushStackLiteral(this.contextName(this.lastContext));
  116023. },
  116024. // [lookupOnContext]
  116025. //
  116026. // On stack, before: ...
  116027. // On stack, after: currentContext[name], ...
  116028. //
  116029. // Looks up the value of `name` on the current context and pushes
  116030. // it onto the stack.
  116031. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  116032. var i = 0;
  116033. if (!scoped && this.options.compat && !this.lastContext) {
  116034. // The depthed query is expected to handle the undefined logic for the root level that
  116035. // is implemented below, so we evaluate that directly in compat mode
  116036. this.push(this.depthedLookup(parts[i++]));
  116037. } else {
  116038. this.pushContext();
  116039. }
  116040. this.resolvePath('context', parts, i, falsy, strict);
  116041. },
  116042. // [lookupBlockParam]
  116043. //
  116044. // On stack, before: ...
  116045. // On stack, after: blockParam[name], ...
  116046. //
  116047. // Looks up the value of `parts` on the given block param and pushes
  116048. // it onto the stack.
  116049. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  116050. this.useBlockParams = true;
  116051. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  116052. this.resolvePath('context', parts, 1);
  116053. },
  116054. // [lookupData]
  116055. //
  116056. // On stack, before: ...
  116057. // On stack, after: data, ...
  116058. //
  116059. // Push the data lookup operator
  116060. lookupData: function lookupData(depth, parts, strict) {
  116061. if (!depth) {
  116062. this.pushStackLiteral('data');
  116063. } else {
  116064. this.pushStackLiteral('container.data(data, ' + depth + ')');
  116065. }
  116066. this.resolvePath('data', parts, 0, true, strict);
  116067. },
  116068. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  116069. // istanbul ignore next
  116070. var _this = this;
  116071. if (this.options.strict || this.options.assumeObjects) {
  116072. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  116073. return;
  116074. }
  116075. var len = parts.length;
  116076. for (; i < len; i++) {
  116077. /* eslint-disable no-loop-func */
  116078. this.replaceStack(function (current) {
  116079. var lookup = _this.nameLookup(current, parts[i], type);
  116080. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  116081. // needs to have the special handling for these values.
  116082. if (!falsy) {
  116083. return [' != null ? ', lookup, ' : ', current];
  116084. } else {
  116085. // Otherwise we can use generic falsy handling
  116086. return [' && ', lookup];
  116087. }
  116088. });
  116089. /* eslint-enable no-loop-func */
  116090. }
  116091. },
  116092. // [resolvePossibleLambda]
  116093. //
  116094. // On stack, before: value, ...
  116095. // On stack, after: resolved value, ...
  116096. //
  116097. // If the `value` is a lambda, replace it on the stack by
  116098. // the return value of the lambda
  116099. resolvePossibleLambda: function resolvePossibleLambda() {
  116100. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  116101. },
  116102. // [pushStringParam]
  116103. //
  116104. // On stack, before: ...
  116105. // On stack, after: string, currentContext, ...
  116106. //
  116107. // This opcode is designed for use in string mode, which
  116108. // provides the string value of a parameter along with its
  116109. // depth rather than resolving it immediately.
  116110. pushStringParam: function pushStringParam(string, type) {
  116111. this.pushContext();
  116112. this.pushString(type);
  116113. // If it's a subexpression, the string result
  116114. // will be pushed after this opcode.
  116115. if (type !== 'SubExpression') {
  116116. if (typeof string === 'string') {
  116117. this.pushString(string);
  116118. } else {
  116119. this.pushStackLiteral(string);
  116120. }
  116121. }
  116122. },
  116123. emptyHash: function emptyHash(omitEmpty) {
  116124. if (this.trackIds) {
  116125. this.push('{}'); // hashIds
  116126. }
  116127. if (this.stringParams) {
  116128. this.push('{}'); // hashContexts
  116129. this.push('{}'); // hashTypes
  116130. }
  116131. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  116132. },
  116133. pushHash: function pushHash() {
  116134. if (this.hash) {
  116135. this.hashes.push(this.hash);
  116136. }
  116137. this.hash = { values: [], types: [], contexts: [], ids: [] };
  116138. },
  116139. popHash: function popHash() {
  116140. var hash = this.hash;
  116141. this.hash = this.hashes.pop();
  116142. if (this.trackIds) {
  116143. this.push(this.objectLiteral(hash.ids));
  116144. }
  116145. if (this.stringParams) {
  116146. this.push(this.objectLiteral(hash.contexts));
  116147. this.push(this.objectLiteral(hash.types));
  116148. }
  116149. this.push(this.objectLiteral(hash.values));
  116150. },
  116151. // [pushString]
  116152. //
  116153. // On stack, before: ...
  116154. // On stack, after: quotedString(string), ...
  116155. //
  116156. // Push a quoted version of `string` onto the stack
  116157. pushString: function pushString(string) {
  116158. this.pushStackLiteral(this.quotedString(string));
  116159. },
  116160. // [pushLiteral]
  116161. //
  116162. // On stack, before: ...
  116163. // On stack, after: value, ...
  116164. //
  116165. // Pushes a value onto the stack. This operation prevents
  116166. // the compiler from creating a temporary variable to hold
  116167. // it.
  116168. pushLiteral: function pushLiteral(value) {
  116169. this.pushStackLiteral(value);
  116170. },
  116171. // [pushProgram]
  116172. //
  116173. // On stack, before: ...
  116174. // On stack, after: program(guid), ...
  116175. //
  116176. // Push a program expression onto the stack. This takes
  116177. // a compile-time guid and converts it into a runtime-accessible
  116178. // expression.
  116179. pushProgram: function pushProgram(guid) {
  116180. if (guid != null) {
  116181. this.pushStackLiteral(this.programExpression(guid));
  116182. } else {
  116183. this.pushStackLiteral(null);
  116184. }
  116185. },
  116186. // [registerDecorator]
  116187. //
  116188. // On stack, before: hash, program, params..., ...
  116189. // On stack, after: ...
  116190. //
  116191. // Pops off the decorator's parameters, invokes the decorator,
  116192. // and inserts the decorator into the decorators list.
  116193. registerDecorator: function registerDecorator(paramSize, name) {
  116194. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  116195. options = this.setupHelperArgs(name, paramSize);
  116196. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  116197. },
  116198. // [invokeHelper]
  116199. //
  116200. // On stack, before: hash, inverse, program, params..., ...
  116201. // On stack, after: result of helper invocation
  116202. //
  116203. // Pops off the helper's parameters, invokes the helper,
  116204. // and pushes the helper's return value onto the stack.
  116205. //
  116206. // If the helper is not found, `helperMissing` is called.
  116207. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  116208. var nonHelper = this.popStack(),
  116209. helper = this.setupHelper(paramSize, name),
  116210. simple = isSimple ? [helper.name, ' || '] : '';
  116211. var lookup = ['('].concat(simple, nonHelper);
  116212. if (!this.options.strict) {
  116213. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  116214. }
  116215. lookup.push(')');
  116216. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  116217. },
  116218. // [invokeKnownHelper]
  116219. //
  116220. // On stack, before: hash, inverse, program, params..., ...
  116221. // On stack, after: result of helper invocation
  116222. //
  116223. // This operation is used when the helper is known to exist,
  116224. // so a `helperMissing` fallback is not required.
  116225. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  116226. var helper = this.setupHelper(paramSize, name);
  116227. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  116228. },
  116229. // [invokeAmbiguous]
  116230. //
  116231. // On stack, before: hash, inverse, program, params..., ...
  116232. // On stack, after: result of disambiguation
  116233. //
  116234. // This operation is used when an expression like `{{foo}}`
  116235. // is provided, but we don't know at compile-time whether it
  116236. // is a helper or a path.
  116237. //
  116238. // This operation emits more code than the other options,
  116239. // and can be avoided by passing the `knownHelpers` and
  116240. // `knownHelpersOnly` flags at compile-time.
  116241. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  116242. this.useRegister('helper');
  116243. var nonHelper = this.popStack();
  116244. this.emptyHash();
  116245. var helper = this.setupHelper(0, name, helperCall);
  116246. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  116247. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  116248. if (!this.options.strict) {
  116249. lookup[0] = '(helper = ';
  116250. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  116251. }
  116252. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  116253. },
  116254. // [invokePartial]
  116255. //
  116256. // On stack, before: context, ...
  116257. // On stack after: result of partial invocation
  116258. //
  116259. // This operation pops off a context, invokes a partial with that context,
  116260. // and pushes the result of the invocation back.
  116261. invokePartial: function invokePartial(isDynamic, name, indent) {
  116262. var params = [],
  116263. options = this.setupParams(name, 1, params);
  116264. if (isDynamic) {
  116265. name = this.popStack();
  116266. delete options.name;
  116267. }
  116268. if (indent) {
  116269. options.indent = JSON.stringify(indent);
  116270. }
  116271. options.helpers = 'helpers';
  116272. options.partials = 'partials';
  116273. options.decorators = 'container.decorators';
  116274. if (!isDynamic) {
  116275. params.unshift(this.nameLookup('partials', name, 'partial'));
  116276. } else {
  116277. params.unshift(name);
  116278. }
  116279. if (this.options.compat) {
  116280. options.depths = 'depths';
  116281. }
  116282. options = this.objectLiteral(options);
  116283. params.push(options);
  116284. this.push(this.source.functionCall('container.invokePartial', '', params));
  116285. },
  116286. // [assignToHash]
  116287. //
  116288. // On stack, before: value, ..., hash, ...
  116289. // On stack, after: ..., hash, ...
  116290. //
  116291. // Pops a value off the stack and assigns it to the current hash
  116292. assignToHash: function assignToHash(key) {
  116293. var value = this.popStack(),
  116294. context = undefined,
  116295. type = undefined,
  116296. id = undefined;
  116297. if (this.trackIds) {
  116298. id = this.popStack();
  116299. }
  116300. if (this.stringParams) {
  116301. type = this.popStack();
  116302. context = this.popStack();
  116303. }
  116304. var hash = this.hash;
  116305. if (context) {
  116306. hash.contexts[key] = context;
  116307. }
  116308. if (type) {
  116309. hash.types[key] = type;
  116310. }
  116311. if (id) {
  116312. hash.ids[key] = id;
  116313. }
  116314. hash.values[key] = value;
  116315. },
  116316. pushId: function pushId(type, name, child) {
  116317. if (type === 'BlockParam') {
  116318. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  116319. } else if (type === 'PathExpression') {
  116320. this.pushString(name);
  116321. } else if (type === 'SubExpression') {
  116322. this.pushStackLiteral('true');
  116323. } else {
  116324. this.pushStackLiteral('null');
  116325. }
  116326. },
  116327. // HELPERS
  116328. compiler: JavaScriptCompiler,
  116329. compileChildren: function compileChildren(environment, options) {
  116330. var children = environment.children,
  116331. child = undefined,
  116332. compiler = undefined;
  116333. for (var i = 0, l = children.length; i < l; i++) {
  116334. child = children[i];
  116335. compiler = new this.compiler(); // eslint-disable-line new-cap
  116336. var existing = this.matchExistingProgram(child);
  116337. if (existing == null) {
  116338. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  116339. var index = this.context.programs.length;
  116340. child.index = index;
  116341. child.name = 'program' + index;
  116342. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  116343. this.context.decorators[index] = compiler.decorators;
  116344. this.context.environments[index] = child;
  116345. this.useDepths = this.useDepths || compiler.useDepths;
  116346. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  116347. child.useDepths = this.useDepths;
  116348. child.useBlockParams = this.useBlockParams;
  116349. } else {
  116350. child.index = existing.index;
  116351. child.name = 'program' + existing.index;
  116352. this.useDepths = this.useDepths || existing.useDepths;
  116353. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  116354. }
  116355. }
  116356. },
  116357. matchExistingProgram: function matchExistingProgram(child) {
  116358. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  116359. var environment = this.context.environments[i];
  116360. if (environment && environment.equals(child)) {
  116361. return environment;
  116362. }
  116363. }
  116364. },
  116365. programExpression: function programExpression(guid) {
  116366. var child = this.environment.children[guid],
  116367. programParams = [child.index, 'data', child.blockParams];
  116368. if (this.useBlockParams || this.useDepths) {
  116369. programParams.push('blockParams');
  116370. }
  116371. if (this.useDepths) {
  116372. programParams.push('depths');
  116373. }
  116374. return 'container.program(' + programParams.join(', ') + ')';
  116375. },
  116376. useRegister: function useRegister(name) {
  116377. if (!this.registers[name]) {
  116378. this.registers[name] = true;
  116379. this.registers.list.push(name);
  116380. }
  116381. },
  116382. push: function push(expr) {
  116383. if (!(expr instanceof Literal)) {
  116384. expr = this.source.wrap(expr);
  116385. }
  116386. this.inlineStack.push(expr);
  116387. return expr;
  116388. },
  116389. pushStackLiteral: function pushStackLiteral(item) {
  116390. this.push(new Literal(item));
  116391. },
  116392. pushSource: function pushSource(source) {
  116393. if (this.pendingContent) {
  116394. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  116395. this.pendingContent = undefined;
  116396. }
  116397. if (source) {
  116398. this.source.push(source);
  116399. }
  116400. },
  116401. replaceStack: function replaceStack(callback) {
  116402. var prefix = ['('],
  116403. stack = undefined,
  116404. createdStack = undefined,
  116405. usedLiteral = undefined;
  116406. /* istanbul ignore next */
  116407. if (!this.isInline()) {
  116408. throw new _exception2['default']('replaceStack on non-inline');
  116409. }
  116410. // We want to merge the inline statement into the replacement statement via ','
  116411. var top = this.popStack(true);
  116412. if (top instanceof Literal) {
  116413. // Literals do not need to be inlined
  116414. stack = [top.value];
  116415. prefix = ['(', stack];
  116416. usedLiteral = true;
  116417. } else {
  116418. // Get or create the current stack name for use by the inline
  116419. createdStack = true;
  116420. var _name = this.incrStack();
  116421. prefix = ['((', this.push(_name), ' = ', top, ')'];
  116422. stack = this.topStack();
  116423. }
  116424. var item = callback.call(this, stack);
  116425. if (!usedLiteral) {
  116426. this.popStack();
  116427. }
  116428. if (createdStack) {
  116429. this.stackSlot--;
  116430. }
  116431. this.push(prefix.concat(item, ')'));
  116432. },
  116433. incrStack: function incrStack() {
  116434. this.stackSlot++;
  116435. if (this.stackSlot > this.stackVars.length) {
  116436. this.stackVars.push('stack' + this.stackSlot);
  116437. }
  116438. return this.topStackName();
  116439. },
  116440. topStackName: function topStackName() {
  116441. return 'stack' + this.stackSlot;
  116442. },
  116443. flushInline: function flushInline() {
  116444. var inlineStack = this.inlineStack;
  116445. this.inlineStack = [];
  116446. for (var i = 0, len = inlineStack.length; i < len; i++) {
  116447. var entry = inlineStack[i];
  116448. /* istanbul ignore if */
  116449. if (entry instanceof Literal) {
  116450. this.compileStack.push(entry);
  116451. } else {
  116452. var stack = this.incrStack();
  116453. this.pushSource([stack, ' = ', entry, ';']);
  116454. this.compileStack.push(stack);
  116455. }
  116456. }
  116457. },
  116458. isInline: function isInline() {
  116459. return this.inlineStack.length;
  116460. },
  116461. popStack: function popStack(wrapped) {
  116462. var inline = this.isInline(),
  116463. item = (inline ? this.inlineStack : this.compileStack).pop();
  116464. if (!wrapped && item instanceof Literal) {
  116465. return item.value;
  116466. } else {
  116467. if (!inline) {
  116468. /* istanbul ignore next */
  116469. if (!this.stackSlot) {
  116470. throw new _exception2['default']('Invalid stack pop');
  116471. }
  116472. this.stackSlot--;
  116473. }
  116474. return item;
  116475. }
  116476. },
  116477. topStack: function topStack() {
  116478. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  116479. item = stack[stack.length - 1];
  116480. /* istanbul ignore if */
  116481. if (item instanceof Literal) {
  116482. return item.value;
  116483. } else {
  116484. return item;
  116485. }
  116486. },
  116487. contextName: function contextName(context) {
  116488. if (this.useDepths && context) {
  116489. return 'depths[' + context + ']';
  116490. } else {
  116491. return 'depth' + context;
  116492. }
  116493. },
  116494. quotedString: function quotedString(str) {
  116495. return this.source.quotedString(str);
  116496. },
  116497. objectLiteral: function objectLiteral(obj) {
  116498. return this.source.objectLiteral(obj);
  116499. },
  116500. aliasable: function aliasable(name) {
  116501. var ret = this.aliases[name];
  116502. if (ret) {
  116503. ret.referenceCount++;
  116504. return ret;
  116505. }
  116506. ret = this.aliases[name] = this.source.wrap(name);
  116507. ret.aliasable = true;
  116508. ret.referenceCount = 1;
  116509. return ret;
  116510. },
  116511. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  116512. var params = [],
  116513. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  116514. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  116515. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  116516. return {
  116517. params: params,
  116518. paramsInit: paramsInit,
  116519. name: foundHelper,
  116520. callParams: [callContext].concat(params)
  116521. };
  116522. },
  116523. setupParams: function setupParams(helper, paramSize, params) {
  116524. var options = {},
  116525. contexts = [],
  116526. types = [],
  116527. ids = [],
  116528. objectArgs = !params,
  116529. param = undefined;
  116530. if (objectArgs) {
  116531. params = [];
  116532. }
  116533. options.name = this.quotedString(helper);
  116534. options.hash = this.popStack();
  116535. if (this.trackIds) {
  116536. options.hashIds = this.popStack();
  116537. }
  116538. if (this.stringParams) {
  116539. options.hashTypes = this.popStack();
  116540. options.hashContexts = this.popStack();
  116541. }
  116542. var inverse = this.popStack(),
  116543. program = this.popStack();
  116544. // Avoid setting fn and inverse if neither are set. This allows
  116545. // helpers to do a check for `if (options.fn)`
  116546. if (program || inverse) {
  116547. options.fn = program || 'container.noop';
  116548. options.inverse = inverse || 'container.noop';
  116549. }
  116550. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  116551. // so we need to pop them off the stack in reverse order
  116552. var i = paramSize;
  116553. while (i--) {
  116554. param = this.popStack();
  116555. params[i] = param;
  116556. if (this.trackIds) {
  116557. ids[i] = this.popStack();
  116558. }
  116559. if (this.stringParams) {
  116560. types[i] = this.popStack();
  116561. contexts[i] = this.popStack();
  116562. }
  116563. }
  116564. if (objectArgs) {
  116565. options.args = this.source.generateArray(params);
  116566. }
  116567. if (this.trackIds) {
  116568. options.ids = this.source.generateArray(ids);
  116569. }
  116570. if (this.stringParams) {
  116571. options.types = this.source.generateArray(types);
  116572. options.contexts = this.source.generateArray(contexts);
  116573. }
  116574. if (this.options.data) {
  116575. options.data = 'data';
  116576. }
  116577. if (this.useBlockParams) {
  116578. options.blockParams = 'blockParams';
  116579. }
  116580. return options;
  116581. },
  116582. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  116583. var options = this.setupParams(helper, paramSize, params);
  116584. options = this.objectLiteral(options);
  116585. if (useRegister) {
  116586. this.useRegister('options');
  116587. params.push('options');
  116588. return ['options=', options];
  116589. } else if (params) {
  116590. params.push(options);
  116591. return '';
  116592. } else {
  116593. return options;
  116594. }
  116595. }
  116596. };
  116597. (function () {
  116598. var reservedWords = ('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(' ');
  116599. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  116600. for (var i = 0, l = reservedWords.length; i < l; i++) {
  116601. compilerWords[reservedWords[i]] = true;
  116602. }
  116603. })();
  116604. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  116605. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  116606. };
  116607. function strictLookup(requireTerminal, compiler, parts, type) {
  116608. var stack = compiler.popStack(),
  116609. i = 0,
  116610. len = parts.length;
  116611. if (requireTerminal) {
  116612. len--;
  116613. }
  116614. for (; i < len; i++) {
  116615. stack = compiler.nameLookup(stack, parts[i], type);
  116616. }
  116617. if (requireTerminal) {
  116618. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  116619. } else {
  116620. return stack;
  116621. }
  116622. }
  116623. exports['default'] = JavaScriptCompiler;
  116624. module.exports = exports['default'];
  116625. /***/ }),
  116626. /* 43 */
  116627. /***/ (function(module, exports, __webpack_require__) {
  116628. /* global define */
  116629. 'use strict';
  116630. exports.__esModule = true;
  116631. var _utils = __webpack_require__(5);
  116632. var SourceNode = undefined;
  116633. try {
  116634. /* istanbul ignore next */
  116635. if (false) {
  116636. // We don't support this in AMD environments. For these environments, we asusme that
  116637. // they are running on the browser and thus have no need for the source-map library.
  116638. var SourceMap = require('source-map');
  116639. SourceNode = SourceMap.SourceNode;
  116640. }
  116641. } catch (err) {}
  116642. /* NOP */
  116643. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  116644. if (!SourceNode) {
  116645. SourceNode = function (line, column, srcFile, chunks) {
  116646. this.src = '';
  116647. if (chunks) {
  116648. this.add(chunks);
  116649. }
  116650. };
  116651. /* istanbul ignore next */
  116652. SourceNode.prototype = {
  116653. add: function add(chunks) {
  116654. if (_utils.isArray(chunks)) {
  116655. chunks = chunks.join('');
  116656. }
  116657. this.src += chunks;
  116658. },
  116659. prepend: function prepend(chunks) {
  116660. if (_utils.isArray(chunks)) {
  116661. chunks = chunks.join('');
  116662. }
  116663. this.src = chunks + this.src;
  116664. },
  116665. toStringWithSourceMap: function toStringWithSourceMap() {
  116666. return { code: this.toString() };
  116667. },
  116668. toString: function toString() {
  116669. return this.src;
  116670. }
  116671. };
  116672. }
  116673. function castChunk(chunk, codeGen, loc) {
  116674. if (_utils.isArray(chunk)) {
  116675. var ret = [];
  116676. for (var i = 0, len = chunk.length; i < len; i++) {
  116677. ret.push(codeGen.wrap(chunk[i], loc));
  116678. }
  116679. return ret;
  116680. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  116681. // Handle primitives that the SourceNode will throw up on
  116682. return chunk + '';
  116683. }
  116684. return chunk;
  116685. }
  116686. function CodeGen(srcFile) {
  116687. this.srcFile = srcFile;
  116688. this.source = [];
  116689. }
  116690. CodeGen.prototype = {
  116691. isEmpty: function isEmpty() {
  116692. return !this.source.length;
  116693. },
  116694. prepend: function prepend(source, loc) {
  116695. this.source.unshift(this.wrap(source, loc));
  116696. },
  116697. push: function push(source, loc) {
  116698. this.source.push(this.wrap(source, loc));
  116699. },
  116700. merge: function merge() {
  116701. var source = this.empty();
  116702. this.each(function (line) {
  116703. source.add([' ', line, '\n']);
  116704. });
  116705. return source;
  116706. },
  116707. each: function each(iter) {
  116708. for (var i = 0, len = this.source.length; i < len; i++) {
  116709. iter(this.source[i]);
  116710. }
  116711. },
  116712. empty: function empty() {
  116713. var loc = this.currentLocation || { start: {} };
  116714. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  116715. },
  116716. wrap: function wrap(chunk) {
  116717. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  116718. if (chunk instanceof SourceNode) {
  116719. return chunk;
  116720. }
  116721. chunk = castChunk(chunk, this, loc);
  116722. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  116723. },
  116724. functionCall: function functionCall(fn, type, params) {
  116725. params = this.generateList(params);
  116726. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  116727. },
  116728. quotedString: function quotedString(str) {
  116729. return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
  116730. .replace(/\u2029/g, '\\u2029') + '"';
  116731. },
  116732. objectLiteral: function objectLiteral(obj) {
  116733. var pairs = [];
  116734. for (var key in obj) {
  116735. if (obj.hasOwnProperty(key)) {
  116736. var value = castChunk(obj[key], this);
  116737. if (value !== 'undefined') {
  116738. pairs.push([this.quotedString(key), ':', value]);
  116739. }
  116740. }
  116741. }
  116742. var ret = this.generateList(pairs);
  116743. ret.prepend('{');
  116744. ret.add('}');
  116745. return ret;
  116746. },
  116747. generateList: function generateList(entries) {
  116748. var ret = this.empty();
  116749. for (var i = 0, len = entries.length; i < len; i++) {
  116750. if (i) {
  116751. ret.add(',');
  116752. }
  116753. ret.add(castChunk(entries[i], this));
  116754. }
  116755. return ret;
  116756. },
  116757. generateArray: function generateArray(entries) {
  116758. var ret = this.generateList(entries);
  116759. ret.prepend('[');
  116760. ret.add(']');
  116761. return ret;
  116762. }
  116763. };
  116764. exports['default'] = CodeGen;
  116765. module.exports = exports['default'];
  116766. /***/ })
  116767. /******/ ])
  116768. });
  116769. ;
  116770. /***/ }),
  116771. /* 18 */
  116772. /***/ (function(module, exports, __webpack_require__) {
  116773. "use strict";
  116774. Object.defineProperty(exports, "__esModule", { value: true });
  116775. var Handlebars = __webpack_require__(17);
  116776. var AbstractViewerNavbarButton = /** @class */ (function () {
  116777. function AbstractViewerNavbarButton() {
  116778. this.templateName = "navBar";
  116779. this.eventsToAttach = ['pointerdown'];
  116780. this._prepend = true;
  116781. }
  116782. AbstractViewerNavbarButton.prototype.interactionPredicate = function (event) {
  116783. var pointerDown = event.event;
  116784. if (pointerDown.button !== 0)
  116785. return false;
  116786. var element = event.event.target;
  116787. if (!element) {
  116788. return false;
  116789. }
  116790. var elementClasses = element.classList;
  116791. for (var i = 0; i < elementClasses.length; ++i) {
  116792. var className = elementClasses[i];
  116793. if (className.indexOf(this._buttonClass) !== -1) {
  116794. return true;
  116795. }
  116796. }
  116797. return false;
  116798. };
  116799. AbstractViewerNavbarButton.prototype.addHTMLTemplate = function (template) {
  116800. var element = this._generateHTMLElement(template);
  116801. var container = template.parent.querySelector("div.default-control");
  116802. if (container) {
  116803. if (this._prepend) {
  116804. container.insertBefore(element, container.firstChild);
  116805. }
  116806. else {
  116807. container.appendChild(element);
  116808. }
  116809. }
  116810. };
  116811. AbstractViewerNavbarButton.prototype._generateHTMLElement = function (template) {
  116812. var compiledTemplate = Handlebars.compile(this._htmlTemplate, { noEscape: (template.configuration.params && !!template.configuration.params.noEscape) });
  116813. var config = template.configuration.params || {};
  116814. var rawHtml = compiledTemplate(config);
  116815. var fragment;
  116816. try {
  116817. fragment = document.createRange().createContextualFragment(rawHtml);
  116818. }
  116819. catch (e) {
  116820. var test = document.createElement(this._buttonClass);
  116821. test.innerHTML = rawHtml;
  116822. fragment = test;
  116823. }
  116824. return fragment;
  116825. };
  116826. return AbstractViewerNavbarButton;
  116827. }());
  116828. exports.AbstractViewerNavbarButton = AbstractViewerNavbarButton;
  116829. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyVGVtcGxhdGVQbHVnaW4uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvdGVtcGxhdGluZy92aWV3ZXJUZW1wbGF0ZVBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVEQUF5RDtBQVl6RDtJQUFBO1FBRW9CLGlCQUFZLEdBQVcsUUFBUSxDQUFDO1FBQ2hDLG1CQUFjLEdBQWtCLENBQUMsYUFBYSxDQUFDLENBQUM7UUFDdEQsYUFBUSxHQUFZLElBQUksQ0FBQztJQW9EdkMsQ0FBQztJQWhERyx5REFBb0IsR0FBcEIsVUFBcUIsS0FBb0I7UUFDckMsSUFBSSxXQUFXLEdBQWlCLEtBQUssQ0FBQyxLQUFLLENBQUM7UUFDNUMsSUFBSSxXQUFXLENBQUMsTUFBTSxLQUFLLENBQUM7WUFBRSxPQUFPLEtBQUssQ0FBQztRQUMzQyxJQUFJLE9BQU8sR0FBaUIsS0FBSyxDQUFDLEtBQUssQ0FBQyxNQUFPLENBQUM7UUFFaEQsSUFBSSxDQUFDLE9BQU8sRUFBRTtZQUNWLE9BQU8sS0FBSyxDQUFDO1NBQ2hCO1FBRUQsSUFBSSxjQUFjLEdBQUcsT0FBTyxDQUFDLFNBQVMsQ0FBQztRQUV2QyxLQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsY0FBYyxDQUFDLE1BQU0sRUFBRSxFQUFFLENBQUMsRUFBRTtZQU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UFFLENBQUM7UUFDakQsSUFBSSxPQUFPLEdBQUcsZ0JBQWdCLENBQUMsTUFBTSxDQUFDLENBQUM7UUFDdkMsSUFBSSxRQUFvQyxDQUFDO1FBQ3pDLElBQUk7WUFDQSxRQUFRLEdBQUcsUUFBUSxDQUFDLFdBQVcsRUFBRSxDQUFDLHdCQUF3QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1NBQ3ZFO1FBQUMsT0FBTyxDQUFDLEVBQUU7WUFDUixJQUFJLElBQUksR0FBRyxRQUFRLENBQUMsYUFBYSxDQUFDLElBQUksQ0FBQyxZQUFZLENBQUMsQ0FBQztZQUNyRCxJQUFJLENBQUMsU0FBUyxHQUFHLE9BQU8sQ0FBQztZQUN6QixRQUFRLEdBQUcsSUFBSSxDQUFDO1NBQ25CO1FBQ0QsT0FBTyxRQUFRLENBQUM7SUFDcEIsQ0FBQztJQUNMLGlDQUFDO0FBQUQsQ0FBQyxBQXhERCxJQXdEQztBQXhEcUIsZ0VBQTBCIn0=
  116830. /***/ }),
  116831. /* 19 */
  116832. /***/ (function(module, exports, __webpack_require__) {
  116833. module.exports = __webpack_require__(20);
  116834. /***/ }),
  116835. /* 20 */
  116836. /***/ (function(module, exports, __webpack_require__) {
  116837. "use strict";
  116838. function __export(m) {
  116839. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  116840. }
  116841. Object.defineProperty(exports, "__esModule", { value: true });
  116842. var mappers_1 = __webpack_require__(3);
  116843. exports.mapperManager = mappers_1.mapperManager;
  116844. var globals_1 = __webpack_require__(4);
  116845. exports.viewerGlobals = globals_1.viewerGlobals;
  116846. var viewerManager_1 = __webpack_require__(7);
  116847. exports.viewerManager = viewerManager_1.viewerManager;
  116848. var defaultViewer_1 = __webpack_require__(8);
  116849. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  116850. var viewer_1 = __webpack_require__(9);
  116851. exports.AbstractViewer = viewer_1.AbstractViewer;
  116852. var telemetryManager_1 = __webpack_require__(6);
  116853. exports.telemetryManager = telemetryManager_1.telemetryManager;
  116854. var modelLoader_1 = __webpack_require__(12);
  116855. exports.ModelLoader = modelLoader_1.ModelLoader;
  116856. var viewerModel_1 = __webpack_require__(5);
  116857. exports.ViewerModel = viewerModel_1.ViewerModel;
  116858. exports.ModelState = viewerModel_1.ModelState;
  116859. var viewerTemplatePlugin_1 = __webpack_require__(18);
  116860. exports.AbstractViewerNavbarButton = viewerTemplatePlugin_1.AbstractViewerNavbarButton;
  116861. var custom_1 = __webpack_require__(16);
  116862. exports.registerCustomOptimizer = custom_1.registerCustomOptimizer;
  116863. /**
  116864. * BabylonJS Viewer
  116865. *
  116866. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  116867. */
  116868. var BABYLON = __webpack_require__(0);
  116869. exports.BABYLON = BABYLON;
  116870. // load needed modules.
  116871. __webpack_require__(13);
  116872. __webpack_require__(66);
  116873. var initializer_1 = __webpack_require__(67);
  116874. exports.InitTags = initializer_1.InitTags;
  116875. // promise polyfill, if needed!
  116876. BABYLON.PromisePolyfill.Apply();
  116877. initializer_1.initListeners();
  116878. //deprectaed, here for backwards compatibility
  116879. var disableInit = globals_1.viewerGlobals.disableInit;
  116880. exports.disableInit = disableInit;
  116881. /**
  116882. * Dispose all viewers currently registered
  116883. */
  116884. function disposeAll() {
  116885. viewerManager_1.viewerManager.dispose();
  116886. mappers_1.mapperManager.dispose();
  116887. telemetryManager_1.telemetryManager.dispose();
  116888. }
  116889. exports.disposeAll = disposeAll;
  116890. var Version = globals_1.viewerGlobals.version;
  116891. exports.Version = Version;
  116892. console.log("Babylon.js viewer (v" + Version + ")");
  116893. // export publicliy all configuration interfaces
  116894. __export(__webpack_require__(14));
  116895. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5nc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QWEsQ0FBQyxPQUFPLEVBQUUsQ0FBQztJQUN4QixtQ0FBZ0IsQ0FBQyxPQUFPLEVBQUUsQ0FBQztBQUMvQixDQUFDO0FBTytJLGdDQUFVO0FBTDFKLElBQU0sT0FBTyxHQUFHLHVCQUFhLENBQUMsT0FBTyxDQUFDO0FBS3BCLDBCQUFPO0FBSHpCLE9BQU8sQ0FBQyxHQUFHLENBQUMsc0JBQXNCLEdBQUcsT0FBTyxHQUFHLEdBQUcsQ0FBQyxDQUFDO0FBSXBELGdEQUFnRDtBQUNoRCxxQ0FBZ0MifQ==
  116896. /***/ }),
  116897. /* 21 */
  116898. /***/ (function(module, exports) {
  116899. var g;
  116900. // This works in non-strict mode
  116901. g = (function() {
  116902. return this;
  116903. })();
  116904. try {
  116905. // This works if eval is allowed (see CSP)
  116906. g = g || Function("return this")() || (1,eval)("this");
  116907. } catch(e) {
  116908. // This works if the window reference is available
  116909. if(typeof window === "object")
  116910. g = window;
  116911. }
  116912. // g can still be undefined, but nothing to do about it...
  116913. // We return undefined, instead of nothing here, so it's
  116914. // easier to handle this case. if(!global) { ...}
  116915. module.exports = g;
  116916. /***/ }),
  116917. /* 22 */
  116918. /***/ (function(module, exports) {
  116919. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  116920. module.exports = CANNON;
  116921. /***/ }),
  116922. /* 23 */
  116923. /***/ (function(module, exports) {
  116924. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  116925. module.exports = OIMO;
  116926. /***/ }),
  116927. /* 24 */
  116928. /***/ (function(module, exports) {
  116929. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  116930. module.exports = earcut;
  116931. /***/ }),
  116932. /* 25 */
  116933. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  116934. "use strict";
  116935. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  116936. var isMergeableObject = function isMergeableObject(value) {
  116937. return isNonNullObject(value)
  116938. && !isSpecial(value)
  116939. };
  116940. function isNonNullObject(value) {
  116941. return !!value && typeof value === 'object'
  116942. }
  116943. function isSpecial(value) {
  116944. var stringValue = Object.prototype.toString.call(value);
  116945. return stringValue === '[object RegExp]'
  116946. || stringValue === '[object Date]'
  116947. || isReactElement(value)
  116948. }
  116949. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  116950. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  116951. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  116952. function isReactElement(value) {
  116953. return value.$$typeof === REACT_ELEMENT_TYPE
  116954. }
  116955. function emptyTarget(val) {
  116956. return Array.isArray(val) ? [] : {}
  116957. }
  116958. function cloneUnlessOtherwiseSpecified(value, options) {
  116959. return (options.clone !== false && options.isMergeableObject(value))
  116960. ? deepmerge(emptyTarget(value), value, options)
  116961. : value
  116962. }
  116963. function defaultArrayMerge(target, source, options) {
  116964. return target.concat(source).map(function(element) {
  116965. return cloneUnlessOtherwiseSpecified(element, options)
  116966. })
  116967. }
  116968. function mergeObject(target, source, options) {
  116969. var destination = {};
  116970. if (options.isMergeableObject(target)) {
  116971. Object.keys(target).forEach(function(key) {
  116972. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  116973. });
  116974. }
  116975. Object.keys(source).forEach(function(key) {
  116976. if (!options.isMergeableObject(source[key]) || !target[key]) {
  116977. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  116978. } else {
  116979. destination[key] = deepmerge(target[key], source[key], options);
  116980. }
  116981. });
  116982. return destination
  116983. }
  116984. function deepmerge(target, source, options) {
  116985. options = options || {};
  116986. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  116987. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  116988. var sourceIsArray = Array.isArray(source);
  116989. var targetIsArray = Array.isArray(target);
  116990. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  116991. if (!sourceAndTargetTypesMatch) {
  116992. return cloneUnlessOtherwiseSpecified(source, options)
  116993. } else if (sourceIsArray) {
  116994. return options.arrayMerge(target, source, options)
  116995. } else {
  116996. return mergeObject(target, source, options)
  116997. }
  116998. }
  116999. deepmerge.all = function deepmergeAll(array, options) {
  117000. if (!Array.isArray(array)) {
  117001. throw new Error('first argument should be an array')
  117002. }
  117003. return array.reduce(function(prev, next) {
  117004. return deepmerge(prev, next, options)
  117005. }, {})
  117006. };
  117007. var deepmerge_1 = deepmerge;
  117008. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  117009. /***/ }),
  117010. /* 26 */
  117011. /***/ (function(module, exports, __webpack_require__) {
  117012. "use strict";
  117013. Object.defineProperty(exports, "__esModule", { value: true });
  117014. var babylonjs_1 = __webpack_require__(0);
  117015. var ConfigurationContainer = /** @class */ (function () {
  117016. function ConfigurationContainer() {
  117017. this.mainColor = babylonjs_1.Color3.White();
  117018. this.reflectionColor = babylonjs_1.Color3.White();
  117019. }
  117020. return ConfigurationContainer;
  117021. }());
  117022. exports.ConfigurationContainer = ConfigurationContainer;
  117023. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBMEM7QUFFMUM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUVwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHdEQUFzQiJ9
  117024. /***/ }),
  117025. /* 27 */
  117026. /***/ (function(module, exports, __webpack_require__) {
  117027. "use strict";
  117028. Object.defineProperty(exports, "__esModule", { value: true });
  117029. var mappers_1 = __webpack_require__(3);
  117030. var types_1 = __webpack_require__(28);
  117031. var configurationCompatibility_1 = __webpack_require__(10);
  117032. var _1 = __webpack_require__(1);
  117033. var babylonjs_1 = __webpack_require__(0);
  117034. /**
  117035. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  117036. * parse the object and return a conform ViewerConfiguration.
  117037. * It is a private member of the scene.
  117038. */
  117039. var ConfigurationLoader = /** @class */ (function () {
  117040. function ConfigurationLoader(_enableCache) {
  117041. if (_enableCache === void 0) { _enableCache = false; }
  117042. this._enableCache = _enableCache;
  117043. this._configurationCache = {};
  117044. this._loadRequests = [];
  117045. }
  117046. /**
  117047. * load a configuration object that is defined in the initial configuration provided.
  117048. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  117049. *
  117050. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  117051. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  117052. * @returns A promise that delivers the extended viewer configuration, when done.
  117053. */
  117054. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  117055. var _this = this;
  117056. if (initConfig === void 0) { initConfig = {}; }
  117057. var loadedConfig = _1.deepmerge({}, initConfig);
  117058. this._processInitialConfiguration(loadedConfig);
  117059. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "extended");
  117060. if (loadedConfig.configuration) {
  117061. var mapperType_1 = "json";
  117062. return Promise.resolve().then(function () {
  117063. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  117064. // a file to load
  117065. var url = '';
  117066. if (typeof loadedConfig.configuration === "string") {
  117067. url = loadedConfig.configuration;
  117068. }
  117069. // if configuration is an object
  117070. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  117071. url = loadedConfig.configuration.url;
  117072. var type = loadedConfig.configuration.mapper;
  117073. // empty string?
  117074. if (!type) {
  117075. // load mapper type from filename / url
  117076. type = loadedConfig.configuration.url.split('.').pop();
  117077. }
  117078. mapperType_1 = type || mapperType_1;
  117079. }
  117080. return _this._loadFile(url);
  117081. }
  117082. else {
  117083. if (typeof loadedConfig.configuration === "object") {
  117084. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  117085. return loadedConfig.configuration.payload || {};
  117086. }
  117087. return {};
  117088. }
  117089. }).then(function (data) {
  117090. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  117091. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  117092. var merged = _1.deepmerge(extendedConfiguration, parsed);
  117093. configurationCompatibility_1.processConfigurationCompatibility(merged);
  117094. if (callback)
  117095. callback(merged);
  117096. return merged;
  117097. });
  117098. }
  117099. else {
  117100. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  117101. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  117102. if (callback)
  117103. callback(loadedConfig);
  117104. return Promise.resolve(loadedConfig);
  117105. }
  117106. };
  117107. /**
  117108. * Dispose the configuration loader. This will cancel file requests, if active.
  117109. */
  117110. ConfigurationLoader.prototype.dispose = function () {
  117111. this._loadRequests.forEach(function (request) {
  117112. request.abort();
  117113. });
  117114. this._loadRequests.length = 0;
  117115. };
  117116. /**
  117117. * This function will process the initial configuration and make needed changes for the viewer to work.
  117118. * @param config the mutable(!) initial configuration to process
  117119. */
  117120. ConfigurationLoader.prototype._processInitialConfiguration = function (config) {
  117121. if (config.model) {
  117122. if (typeof config.model === "string") {
  117123. config.model = {
  117124. url: config.model
  117125. };
  117126. }
  117127. }
  117128. };
  117129. ConfigurationLoader.prototype._loadFile = function (url) {
  117130. var _this = this;
  117131. var cacheReference = this._configurationCache;
  117132. if (this._enableCache && cacheReference[url]) {
  117133. return Promise.resolve(cacheReference[url]);
  117134. }
  117135. return new Promise(function (resolve, reject) {
  117136. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  117137. var idx = _this._loadRequests.indexOf(fileRequest);
  117138. if (idx !== -1)
  117139. _this._loadRequests.splice(idx, 1);
  117140. if (_this._enableCache)
  117141. cacheReference[url] = result;
  117142. resolve(result);
  117143. }, undefined, undefined, false, function (request, error) {
  117144. var idx = _this._loadRequests.indexOf(fileRequest);
  117145. if (idx !== -1)
  117146. _this._loadRequests.splice(idx, 1);
  117147. reject(error);
  117148. });
  117149. _this._loadRequests.push(fileRequest);
  117150. });
  117151. };
  117152. return ConfigurationLoader;
  117153. }());
  117154. exports.ConfigurationLoader = ConfigurationLoader;
  117155. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2NvbmZpZ3VyYXRpb24vbG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQTBDO0FBRTFDLGlDQUErQztBQUMvQywyRUFBaUY7QUFFakYsK0JBQXVDO0FBQ3ZDLHVDQUFnRDtBQUVoRDs7OztHQUlHO0FBQ0g7SUFNSSw2QkFBb0IsWUFBNkI7UUFBN0IsNkJBQUEsRUFBQSxvQkFBNkI7UUFBN0IsaUJBQVksR0FBWixZQUFZLENBQWlCO1FBQzdDLElBQUksQ0FBQyxtQkFBbUIsR0FBRyxFQUFFLENBQUM7UUFDOUIsSUFBSSxDQUFDLGFBQWEsR0FBRyxFQUFFLENBQUM7SUFDNUIsQ0FBQztJQUVEOzs7Ozs7O09BT0c7SUFDSSwrQ0FBaUIsR0FBeEIsVUFBeUIsVUFBb0MsRUFBRSxRQUFnRDtRQUEvRyxpQkFxREM7UUFyRHdCLDJCQUFBLEVBQUEsZUFBb0M7U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MvQixJQUFJLFdBQVcsR0FBRyxpQkFBSyxDQUFDLFFBQVEsQ0FBQyxHQUFHLEVBQUUsVUFBQyxNQUFNO2dCQUN6QyxJQUFJLEdBQUcsR0FBRyxLQUFJLENBQUMsYUFBYSxDQUFDLE9BQU8sQ0FBQyxXQUFXLENBQUMsQ0FBQztnQkFDbEQsSUFBSSxHQUFHLEtBQUssQ0FBQyxDQUFDO29CQUNWLEtBQUksQ0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLEdBQUcsRUFBRSxDQUFDLENBQUMsQ0FBQztnQkFDdEMsSUFBSSxLQUFJLENBQUMsWUFBWTtvQkFBRSxjQUFjLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDO2dCQUNwRCxPQUFPLENBQUMsTUFBTSxDQUFDLENBQUM7WUFDcEIsQ0FBQyxFQUFFLFNBQVMsRUFBRSxTQUFTLEVBQUUsS0FBSyxFQUFFLFVBQUMsT0FBTyxFQUFFLEtBQVU7Z0JBQ2hELElBQUksR0FBRyxHQUFHLEtBQUksQ0FBQyxhQUFhLENBQUMsT0FBTyxDQUFDLFdBQVcsQ0FBQyxDQUFDO2dCQUNsRCxJQUFJLEdBQUcsS0FBSyxDQUFDLENBQUM7b0JBQ1YsS0FBSSxDQUFDLGFBQWEsQ0FBQyxNQUFNLENBQUMsR0FBRyxFQUFFLENBQUMsQ0FBQyxDQUFDO2dCQUN0QyxNQUFNLENBQUMsS0FBSyxDQUFDLENBQUM7WUFDbEIsQ0FBQyxDQUFDLENBQUM7WUFDSCxLQUFJLENBQUMsYUFBYSxDQUFDLElBQUksQ0FBQyxXQUFXLENBQUMsQ0FBQztRQUN6QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFFTCwwQkFBQztBQUFELENBQUMsQUF6SEQsSUF5SEM7QUF6SFksa0RBQW1CIn0=
  117156. /***/ }),
  117157. /* 28 */
  117158. /***/ (function(module, exports, __webpack_require__) {
  117159. "use strict";
  117160. Object.defineProperty(exports, "__esModule", { value: true });
  117161. var minimal_1 = __webpack_require__(29);
  117162. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  117163. var default_1 = __webpack_require__(48);
  117164. exports.defaultConfiguration = default_1.defaultConfiguration;
  117165. var extended_1 = __webpack_require__(49);
  117166. var shadowLight_1 = __webpack_require__(50);
  117167. var environmentMap_1 = __webpack_require__(51);
  117168. var _1 = __webpack_require__(1);
  117169. /**
  117170. * Get the configuration type you need to use as the base for your viewer.
  117171. * The types can either be a single string, or comma separated types that will extend each other. for example:
  117172. *
  117173. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  117174. *
  117175. * @param types a comma-separated string of the type(s) or configuration to load.
  117176. */
  117177. var getConfigurationType = function (types) {
  117178. var config = {};
  117179. var typesSeparated = types.split(",");
  117180. typesSeparated.forEach(function (type) {
  117181. switch (type.trim()) {
  117182. case 'environmentMap':
  117183. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  117184. break;
  117185. case 'shadowDirectionalLight':
  117186. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  117187. break;
  117188. case 'shadowSpotLight':
  117189. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  117190. break;
  117191. case 'default':
  117192. config = _1.deepmerge(config, default_1.defaultConfiguration);
  117193. break;
  117194. case 'minimal':
  117195. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  117196. break;
  117197. case 'none':
  117198. break;
  117199. case 'extended':
  117200. default:
  117201. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  117202. break;
  117203. }
  117204. if (config.extends) {
  117205. config = _1.deepmerge(config, getConfigurationType(config.extends));
  117206. }
  117207. });
  117208. return config;
  117209. };
  117210. exports.getConfigurationType = getConfigurationType;
  117211. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8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RSw4QkFBb0IsQ0FBQyxDQUFDO2dCQUNqRCxNQUFNO1lBQ1YsS0FBSyxNQUFNO2dCQUNQLE1BQU07WUFDVixLQUFLLFVBQVUsQ0FBQztZQUNoQjtnQkFDSSxNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxnQ0FBcUIsQ0FBQyxDQUFDO2dCQUNsRCxNQUFNO1NBQ2I7UUFFRCxJQUFJLE1BQU0sQ0FBQyxPQUFPLEVBQUU7WUFDaEIsTUFBTSxHQUFHLFlBQVMsQ0FBQyxNQUFNLEVBQUUsb0JBQW9CLENBQUMsTUFBTSxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUM7U0FDcEU7SUFDTCxDQUFDLENBQUMsQ0FBQztJQUNILE9BQU8sTUFBTSxDQUFDO0FBRWxCLENBQUMsQ0FBQTtBQUVRLG9EQUFvQiJ9
  117212. /***/ }),
  117213. /* 29 */
  117214. /***/ (function(module, exports, __webpack_require__) {
  117215. "use strict";
  117216. Object.defineProperty(exports, "__esModule", { value: true });
  117217. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  117218. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  117219. /**
  117220. * The minimal configuration needed to make the viewer work.
  117221. * Some functionalities might not work correctly (like fill-screen)
  117222. */
  117223. exports.minimalConfiguration = {
  117224. version: "0.1",
  117225. templates: {
  117226. main: {
  117227. html: babylonjs_viewer_assets_1.defaultTemplate
  117228. },
  117229. fillContainer: {
  117230. html: babylonjs_viewer_assets_1.fillContainer,
  117231. params: {
  117232. disable: false
  117233. }
  117234. },
  117235. loadingScreen: {
  117236. html: babylonjs_viewer_assets_1.loadingScreen,
  117237. params: {
  117238. backgroundColor: "#000000",
  117239. loadingImage: babylonjs_viewer_assets_2.loading
  117240. }
  117241. },
  117242. viewer: {
  117243. html: babylonjs_viewer_assets_1.defaultViewer,
  117244. },
  117245. overlay: {
  117246. html: babylonjs_viewer_assets_1.overlay,
  117247. params: {
  117248. closeImage: babylonjs_viewer_assets_2.close,
  117249. closeText: 'Close'
  117250. }
  117251. },
  117252. error: {
  117253. html: babylonjs_viewer_assets_1.error
  117254. }
  117255. },
  117256. engine: {
  117257. antialiasing: true
  117258. }
  117259. };
  117260. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  117261. /***/ }),
  117262. /* 30 */
  117263. /***/ (function(module, exports, __webpack_require__) {
  117264. "use strict";
  117265. Object.defineProperty(exports, "__esModule", { value: true });
  117266. exports.babylonFont = __webpack_require__(31);
  117267. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  117268. /***/ }),
  117269. /* 31 */
  117270. /***/ (function(module, exports) {
  117271. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABTkAA8AAAAAJEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEgAAABgSlp+MVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAACIAAAA3oTfhSJjdnQgAAAEMAAAACAAAAAqCdkJr2ZwZ20AAARQAAAA8AAAAVn8nuaOZ2FzcAAABUAAAAAMAAAADAAIABtnbHlmAAAFTAAACPgAAAzOOMLcQmhlYWQAAA5EAAAAMgAAADb+Z7dYaGhlYQAADngAAAAVAAAAJBABCAZobXR4AAAOkAAAACsAAAA2EzQDvGxvY2EAAA68AAAALgAAAC4W1hOObWF4cAAADuwAAAAcAAAAIACPANFuYW1lAAAPCAAABTwAAAvzL/OWdXBvc3QAABREAAAAEwAAACD/UQB3cHJlcAAAFFgAAACJAAAA03i98g542mNgZp/IOIGBlYGDdRarMQMDozSEZr7IkMYkxMHKysXIxAgGDEAgwIAAvsEKCgwODLzf0zjAfAjJAFbHAuEpMDAAAL2BB0542hXJUxQYBgAEwclf2qa2bdu2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s12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA="
  117272. /***/ }),
  117273. /* 32 */
  117274. /***/ (function(module, exports, __webpack_require__) {
  117275. "use strict";
  117276. Object.defineProperty(exports, "__esModule", { value: true });
  117277. exports.babylonLogo = __webpack_require__(33);
  117278. exports.close = __webpack_require__(34);
  117279. exports.fullscreen = __webpack_require__(35);
  117280. exports.helpCircle = __webpack_require__(36);
  117281. exports.loading = __webpack_require__(37);
  117282. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  117283. /***/ }),
  117284. /* 33 */
  117285. /***/ (function(module, exports) {
  117286. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCo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0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  117287. /***/ }),
  117288. /* 34 */
  117289. /***/ (function(module, exports) {
  117290. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  117291. /***/ }),
  117292. /* 35 */
  117293. /***/ (function(module, exports) {
  117294. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  117295. /***/ }),
  117296. /* 36 */
  117297. /***/ (function(module, exports) {
  117298. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAB/ElEQVR42u3Xs4JdQRzH8X9sqYrNNnbqtPELxKgWD7AsI71B7BcI21W9rNa+d27zjSac/5kzZ2J8yqPfGUn++xMwis2UcpsGuilQoJt6blHCJkbKt2I+FbSRpJVy5kos5nAVQxrDJWbFfP4wXYTqYL9kwRiuk9VFRksYJvKEGA+ZEPb3+udrOcNaJjGJtZyhTo8IKIVaOXmOMfKrrnsCo1WU+HFE/fxu9dk9asR+f8fswnU08fmTuDo8nZarat2P/DjobtFPP3dY8bGi6jNUE/MxuM58vNsFVvfHiHNqleqjmwo0a+zdW3zutr26Dk2ZPqW1oZli7/fzuT57dQqaFmUaZDNZ9HoDYIMbUEoWt+xb69EVuwG3CdfNcvtWNbqbbkB9ePVgK4DFDKGrcwO6CNPHJvvGdGpI0uEGGELk2WGfn8or33OxAUc/TulP8cnHVVENI5Vhp+mIa+TT9tm9pKkN7ab6tHEDRVo3LUGjTxuNpClyAzaRSiwGSbPeDRhJC99Ls7rno5zvpUw0zMMQQV1wdFzmezgvSZhJR1Aj+3QyW5Jx8JsD9okfV74p4ELIceNudMAjRodtfh8T4yETg7fvEf3pAqMlCw7QQah29kl2zOIiedLkOc9MicVcymkhSQtlzJVvxUg2UMxNaunCYOiihpsUsZ6R8t8f4DUz8hFGPnrb0AAAAABJRU5ErkJggg=="
  117299. /***/ }),
  117300. /* 37 */
  117301. /***/ (function(module, exports) {
  117302. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JB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hANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  117303. /***/ }),
  117304. /* 38 */
  117305. /***/ (function(module, exports, __webpack_require__) {
  117306. "use strict";
  117307. Object.defineProperty(exports, "__esModule", { value: true });
  117308. exports.defaultTemplate = __webpack_require__(39);
  117309. exports.defaultViewer = __webpack_require__(40);
  117310. exports.error = __webpack_require__(41);
  117311. exports.fillContainer = __webpack_require__(42);
  117312. exports.help = __webpack_require__(43);
  117313. exports.loadingScreen = __webpack_require__(44);
  117314. exports.navbar = __webpack_require__(45);
  117315. exports.overlay = __webpack_require__(46);
  117316. exports.share = __webpack_require__(47);
  117317. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  117318. /***/ }),
  117319. /* 39 */
  117320. /***/ (function(module, exports) {
  117321. 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>";
  117322. /***/ }),
  117323. /* 40 */
  117324. /***/ (function(module, exports) {
  117325. 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>";
  117326. /***/ }),
  117327. /* 41 */
  117328. /***/ (function(module, exports) {
  117329. module.exports = "Error loading the model";
  117330. /***/ }),
  117331. /* 42 */
  117332. /***/ (function(module, exports) {
  117333. 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>";
  117334. /***/ }),
  117335. /* 43 */
  117336. /***/ (function(module, exports) {
  117337. module.exports = "HELP";
  117338. /***/ }),
  117339. /* 44 */
  117340. /***/ (function(module, exports) {
  117341. 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}}>";
  117342. /***/ }),
  117343. /* 45 */
  117344. /***/ (function(module, exports) {
  117345. 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\"}viewer.in-fullscreen .fullscreen-icon:after{content:\"\\E73F\"}.help-icon:after{font-size:16px;content:\"\\EF4E\"}viewer.in-vr .vr-icon:after{font-size:16px;content:\"\\E7F4\"}.vr-icon:after{font-size:16px;content:\"\\F119\"}.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.in-fullscreen nav-bar{display:none}</style> {{/if}} <div class=\"nav-container 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 types-button animation-buttons\"> <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 label-option-button animation-buttons\" data-value={{this.value}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{this.label}}</span> <span class=\"control-text animation-number\">{{add @index 1}}</span> </button> {{/unless}} {{/each}} </div> </div> <div class=progress-control> <button class=\"play-pause play-pause-button\"> {{#if paused}} <span class=\"icon play-icon\"></span> {{else}} <span class=\"icon pause-icon\"></span> {{/if}} </button> <input class=progress-wrapper type=range min=0 max=100 step=0.01> </div> <div class=speed> <button class=\"flex-container 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 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 hideVr}} <button class=\"vr vr-button\" title={{text.vrButton}}> <span class=\"icon vr-icon\"></span> </button> {{/unless}}{{#unless hideHelp}} <button class=\"help help-button\" title={{text.helpButton}}> <span class=\"icon help-icon\"></span> </button> {{/unless}} {{#unless hideFullScreen}} <button class=\"fullscreen fullscreen-button\" title={{text.fullscreenButton}}> <span class=\"icon fullscreen-icon\"></span> </button> {{/unless}} </div> </div>";
  117346. /***/ }),
  117347. /* 46 */
  117348. /***/ (function(module, exports) {
  117349. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:none;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>";
  117350. /***/ }),
  117351. /* 47 */
  117352. /***/ (function(module, exports) {
  117353. module.exports = "SHARE";
  117354. /***/ }),
  117355. /* 48 */
  117356. /***/ (function(module, exports, __webpack_require__) {
  117357. "use strict";
  117358. Object.defineProperty(exports, "__esModule", { value: true });
  117359. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  117360. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  117361. var images = __webpack_require__(2);
  117362. /**
  117363. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  117364. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  117365. */
  117366. exports.defaultConfiguration = {
  117367. version: "3.2.0-alpha4",
  117368. templates: {
  117369. main: {
  117370. html: babylonjs_viewer_assets_1.defaultTemplate,
  117371. params: {
  117372. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  117373. noEscape: true
  117374. }
  117375. },
  117376. fillContainer: {
  117377. html: babylonjs_viewer_assets_1.fillContainer,
  117378. params: {
  117379. disable: false
  117380. }
  117381. },
  117382. loadingScreen: {
  117383. html: babylonjs_viewer_assets_1.loadingScreen,
  117384. params: {
  117385. backgroundColor: "#000000",
  117386. loadingImage: images.loading
  117387. }
  117388. },
  117389. viewer: {
  117390. html: babylonjs_viewer_assets_1.defaultViewer,
  117391. params: {
  117392. enableDragAndDrop: false
  117393. }
  117394. },
  117395. navBar: {
  117396. html: babylonjs_viewer_assets_1.navbar,
  117397. params: {
  117398. speedList: {
  117399. "0.5x": "0.5",
  117400. "1.0x": "1.0",
  117401. "1.5x": "1.5",
  117402. "2.0x": "2.0",
  117403. },
  117404. logoImage: images.babylonLogo,
  117405. logoText: 'BabylonJS',
  117406. logoLink: 'https://babylonjs.com',
  117407. hideHelp: true,
  117408. hideHd: true,
  117409. hideVr: true,
  117410. disableOnFullscreen: false,
  117411. text: {
  117412. hdButton: "Toggle HD",
  117413. fullscreenButton: "Fullscreen",
  117414. helpButton: "Help",
  117415. vrButton: "Toggle VR"
  117416. }
  117417. },
  117418. events: {
  117419. pointerdown: {
  117420. '.navbar-control': true,
  117421. '.help-button': true
  117422. },
  117423. input: {
  117424. '.progress-wrapper': true
  117425. },
  117426. pointerup: {
  117427. '.progress-wrapper': true
  117428. }
  117429. }
  117430. },
  117431. overlay: {
  117432. html: babylonjs_viewer_assets_1.overlay,
  117433. params: {
  117434. closeImage: images.close,
  117435. closeText: 'Close'
  117436. }
  117437. },
  117438. help: {
  117439. html: babylonjs_viewer_assets_1.help
  117440. },
  117441. share: {
  117442. html: babylonjs_viewer_assets_1.share
  117443. },
  117444. error: {
  117445. html: babylonjs_viewer_assets_1.error
  117446. }
  117447. },
  117448. camera: {
  117449. behaviors: {
  117450. autoRotate: {
  117451. type: 0
  117452. },
  117453. framing: {
  117454. type: 2,
  117455. zoomOnBoundingInfo: true,
  117456. zoomStopsAnimation: false
  117457. },
  117458. bouncing: {
  117459. type: 1
  117460. }
  117461. }
  117462. },
  117463. skybox: {},
  117464. ground: {
  117465. receiveShadows: true
  117466. },
  117467. engine: {
  117468. antialiasing: true
  117469. },
  117470. scene: {}
  117471. };
  117472. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL2RlZmF1bHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBNEk7QUFDNUksbUVBQXNEO0FBQ3RELGdEQUFrRDtBQUVsRDs7O0dBR0c7QUFDUSxRQUFBLG9CQUFvQixHQUF3QjtJQUNuRCxPQUFPLEVBQUUsY0FBYztJQUN2QixTQUFTLEVBQUU7UUFDUCxJQUFJLEVBQUU7WUFDRixJQUFJLEVBQUUseUNBQWU7WUFDckIsTUFBTSxFQUFFO2dCQUNKLFdBQVcsRUFBRSxxQ0FBVztnQkFDeEIsUUFBU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pack_require__) {
  117476. "use strict";
  117477. Object.defineProperty(exports, "__esModule", { value: true });
  117478. var babylonjs_1 = __webpack_require__(0);
  117479. /**
  117480. * The viewer's "extended" configuration.
  117481. * This configuration defines specific obejcts and parameters that we think make any model look good.
  117482. */
  117483. exports.extendedConfiguration = {
  117484. version: "3.2.0",
  117485. extends: "default",
  117486. camera: {
  117487. exposure: 3.034578,
  117488. fov: 0.7853981633974483,
  117489. contrast: 1.6,
  117490. toneMappingEnabled: true,
  117491. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  117492. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  117493. behaviors: {
  117494. framing: {
  117495. type: 2,
  117496. mode: 0,
  117497. positionScale: 0.5,
  117498. defaultElevation: 0.2617993877991494,
  117499. elevationReturnWaitTime: 3000,
  117500. elevationReturnTime: 2000,
  117501. framingTime: 500,
  117502. zoomStopsAnimation: false,
  117503. radiusScale: 0.866
  117504. },
  117505. autoRotate: {
  117506. type: 0,
  117507. idleRotationWaitTime: 4000,
  117508. idleRotationSpeed: 0.17453292519943295,
  117509. idleRotationSpinupTime: 2500,
  117510. zoomStopsAnimation: false
  117511. },
  117512. bouncing: {
  117513. type: 1,
  117514. lowerRadiusTransitionRange: 0.05,
  117515. upperRadiusTransitionRange: -0.2
  117516. }
  117517. },
  117518. upperRadiusLimit: 5,
  117519. lowerRadiusLimit: 0.5,
  117520. frameOnModelLoad: true,
  117521. framingElevation: 0.2617993877991494,
  117522. framingRotation: 1.5707963267948966,
  117523. radius: 2,
  117524. alpha: 1.5708,
  117525. beta: Math.PI * 0.5 - 0.2618,
  117526. wheelPrecision: 300,
  117527. minZ: 0.1,
  117528. maxZ: 50,
  117529. fovMode: 0,
  117530. pinchPrecision: 1500,
  117531. panningSensibility: 3000
  117532. },
  117533. lights: {
  117534. light0: {
  117535. type: 0,
  117536. frustumEdgeFalloff: 0,
  117537. intensity: 7,
  117538. intensityMode: 0,
  117539. radius: 0.6,
  117540. range: 0.6,
  117541. spotAngle: 60,
  117542. diffuse: {
  117543. r: 1,
  117544. g: 1,
  117545. b: 1
  117546. },
  117547. position: {
  117548. x: -2,
  117549. y: 2.5,
  117550. z: 2
  117551. },
  117552. target: {
  117553. x: 0,
  117554. y: 0,
  117555. z: 0
  117556. },
  117557. enabled: true,
  117558. shadowEnabled: true,
  117559. shadowBufferSize: 512,
  117560. shadowMinZ: 1,
  117561. shadowMaxZ: 10,
  117562. shadowFieldOfView: 60,
  117563. shadowFrustumSize: 2,
  117564. shadowConfig: {
  117565. useBlurCloseExponentialShadowMap: true,
  117566. useKernelBlur: true,
  117567. blurScale: 1.0,
  117568. bias: 0.001,
  117569. depthScale: 50 * (10 - 1),
  117570. frustumEdgeFalloff: 0
  117571. }
  117572. },
  117573. light1: {
  117574. type: 0,
  117575. frustumEdgeFalloff: 0,
  117576. intensity: 7,
  117577. intensityMode: 0,
  117578. radius: 0.4,
  117579. range: 0.4,
  117580. spotAngle: 57,
  117581. diffuse: {
  117582. r: 1,
  117583. g: 1,
  117584. b: 1
  117585. },
  117586. position: {
  117587. x: 4,
  117588. y: 3,
  117589. z: -0.5
  117590. },
  117591. target: {
  117592. x: 0,
  117593. y: 0,
  117594. z: 0
  117595. },
  117596. enabled: true,
  117597. shadowEnabled: false,
  117598. shadowBufferSize: 512,
  117599. shadowMinZ: 0.2,
  117600. shadowMaxZ: 10,
  117601. shadowFieldOfView: 28,
  117602. shadowFrustumSize: 2
  117603. },
  117604. light2: {
  117605. type: 0,
  117606. frustumEdgeFalloff: 0,
  117607. intensity: 1,
  117608. intensityMode: 0,
  117609. radius: 0.5,
  117610. range: 0.5,
  117611. spotAngle: 42.85,
  117612. diffuse: {
  117613. r: 0.8,
  117614. g: 0.8,
  117615. b: 0.8
  117616. },
  117617. position: {
  117618. x: -1,
  117619. y: 3,
  117620. z: -3
  117621. },
  117622. target: {
  117623. x: 0,
  117624. y: 0,
  117625. z: 0
  117626. },
  117627. enabled: true,
  117628. shadowEnabled: false,
  117629. shadowBufferSize: 512,
  117630. shadowMinZ: 0.2,
  117631. shadowMaxZ: 10,
  117632. shadowFieldOfView: 45,
  117633. shadowFrustumSize: 2
  117634. }
  117635. },
  117636. ground: {
  117637. shadowLevel: 0.9,
  117638. texture: "Ground_2.0-1024.png",
  117639. material: {
  117640. primaryColorHighlightLevel: 0.035,
  117641. primaryColorShadowLevel: 0,
  117642. enableNoise: true,
  117643. useRGBColor: false,
  117644. maxSimultaneousLights: 1,
  117645. diffuseTexture: {
  117646. gammaSpace: true
  117647. }
  117648. },
  117649. opacity: 1,
  117650. mirror: false,
  117651. receiveShadows: true,
  117652. size: 5
  117653. },
  117654. skybox: {
  117655. scale: 11,
  117656. cubeTexture: {
  117657. url: "Skybox_2.0-256.dds"
  117658. },
  117659. material: {
  117660. primaryColorHighlightLevel: 0.03,
  117661. primaryColorShadowLevel: 0.03,
  117662. enableNoise: true,
  117663. useRGBColor: false,
  117664. reflectionTexture: {
  117665. gammaSpace: true
  117666. }
  117667. }
  117668. },
  117669. engine: {
  117670. renderInBackground: true
  117671. },
  117672. scene: {
  117673. flags: {
  117674. shadowsEnabled: true,
  117675. particlesEnabled: false,
  117676. collisionsEnabled: false,
  117677. lightsEnabled: true,
  117678. texturesEnabled: true,
  117679. lensFlaresEnabled: false,
  117680. proceduralTexturesEnabled: false,
  117681. renderTargetsEnabled: true,
  117682. spritesEnabled: false,
  117683. skeletonsEnabled: true,
  117684. audioEnabled: false,
  117685. },
  117686. defaultMaterial: {
  117687. materialType: 'pbr',
  117688. reflectivityColor: {
  117689. r: 0.1,
  117690. g: 0.1,
  117691. b: 0.1
  117692. },
  117693. microSurface: 0.6
  117694. },
  117695. clearColor: {
  117696. r: 0.9,
  117697. g: 0.9,
  117698. b: 0.9,
  117699. a: 1.0
  117700. },
  117701. imageProcessingConfiguration: {
  117702. vignetteCentreX: 0,
  117703. vignetteCentreY: 0,
  117704. vignetteColor: {
  117705. r: 0.086,
  117706. g: 0.184,
  117707. b: 0.259,
  117708. a: 1
  117709. },
  117710. vignetteWeight: 0.855,
  117711. vignetteStretch: 0.5,
  117712. vignetteBlendMode: 0,
  117713. vignetteCameraFov: 0.7853981633974483,
  117714. isEnabled: true,
  117715. colorCurves: {
  117716. shadowsHue: 0,
  117717. shadowsDensity: 0,
  117718. shadowsSaturation: 0,
  117719. shadowsExposure: 0,
  117720. midtonesHue: 0,
  117721. midtonesDensity: 0,
  117722. midtonesExposure: 0,
  117723. midtonesSaturation: 0,
  117724. highlightsHue: 0,
  117725. highlightsDensity: 0,
  117726. highlightsExposure: 0,
  117727. highlightsSaturation: 0
  117728. }
  117729. },
  117730. mainColor: {
  117731. r: 0.8823529411764706,
  117732. g: 0.8823529411764706,
  117733. b: 0.8823529411764706
  117734. }
  117735. },
  117736. loaderPlugins: {
  117737. extendedMaterial: true,
  117738. applyMaterialConfig: true,
  117739. msftLod: true,
  117740. telemetry: true
  117741. },
  117742. model: {
  117743. rotationOffsetAxis: {
  117744. x: 0,
  117745. y: -1,
  117746. z: 0
  117747. },
  117748. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  117749. material: {
  117750. directEnabled: true,
  117751. directIntensity: 0.884,
  117752. emissiveIntensity: 1.04,
  117753. environmentIntensity: 0.6
  117754. },
  117755. entryAnimation: {
  117756. scaling: {
  117757. x: 0,
  117758. y: 0,
  117759. z: 0
  117760. },
  117761. time: 0.5,
  117762. easingFunction: 4,
  117763. easingMode: 1
  117764. },
  117765. exitAnimation: {
  117766. scaling: {
  117767. x: 0,
  117768. y: 0,
  117769. z: 0
  117770. },
  117771. time: 0.5,
  117772. easingFunction: 4,
  117773. easingMode: 1
  117774. },
  117775. normalize: true,
  117776. castShadow: true,
  117777. receiveShadows: true
  117778. },
  117779. lab: {
  117780. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  117781. environmentMap: {
  117782. texture: "EnvMap_2.0-256.env",
  117783. rotationY: 3,
  117784. tintLevel: 0.4
  117785. },
  117786. defaultRenderingPipelines: {
  117787. bloomEnabled: true,
  117788. bloomThreshold: 1.0,
  117789. fxaaEnabled: true,
  117790. bloomWeight: 0.05
  117791. }
  117792. }
  117793. };
  117794. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVDQUFrQztBQUVsQzs7O0dBR0c7QUFDUSxRQUFBLHFCQUFxQixHQUF3QjtJQUNwRCxPQUFPLEVBQUUsT0FBTztJQUNoQixPQUFPLEVBQUUsU0FBUztJQUNsQixNQUFNLEVBQUU7UUFDSixRQUFRLEVBQUUsUUFBUTtRQUNsQixHQUFHLEVBQUUsa0JBQWtCO1FBQ3ZCLFFBQVEsRUFBRSxHQUFHO1FBQ2Isa0JBQWtCLEVBQUUsSUFBSTtRQUN4QixjQUFjLEVBQUUsa0JBQWtCLEdBQUcsSUFBSSxDQUFDLEVBQUUsR0FBRyxDQUFDO1FBQ2hELGNBQWMsRUFBRSxDQUFDLGtCQUFrQixHQUFHLElBQUksQ0FBQyxFQUFFLEdBQUcsQ0FBQztRQUNqRCxTQUFTLEVBQUU7WUFDUCxPQUFPLEVBQUU7Z0JBQ0wsSUFBSSxFQUFFLENBQUM7Z0JBQ1AsSUFBSSxFQUFFLENBQUM7Z0JBQ1AsYUFBYSxFQUFFLEdBQUc7Z0JBQ2xCLGdCQUFnQixFQUFFLGtCQUFrQjtnQkFDcEMsdUJBQXVCLEVBQUUsSUFBSTtnQkFDN0IsbUJBQW1CLEVBQUUsSUFBSTtnQkFDekIsV0FBVyxFQUFFLEdBQUc7Z0JBQ2hCLGtCQUFrQixFQUFFLEtBQUs7Z0JBQ3pCLFdBQVcsRUFBRSxLQUFLO2FBQ3JCO1lBQ0QsVUFBVSxFQUFFO2dCQU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U8sRUFBRTtnQkFDTCxDQUFDLEVBQUUsQ0FBQztnQkFDSixDQUFDLEVBQUUsQ0FBQztnQkFDSixDQUFDLEVBQUUsQ0FBQzthQUNQO1lBQ0QsSUFBSSxFQUFFLEdBQUc7WUFDVCxjQUFjLEVBQUUsQ0FBQztZQUNqQixVQUFVLEVBQUUsQ0FBQztTQUNoQjtRQUNELGFBQWEsRUFBRTtZQUNYLE9BQU8sRUFBRTtnQkFDTCxDQUFDLEVBQUUsQ0FBQztnQkFDSixDQUFDLEVBQUUsQ0FBQztnQkFDSixDQUFDLEVBQUUsQ0FBQzthQUNQO1lBQ0QsSUFBSSxFQUFFLEdBQUc7WUFDVCxjQUFjLEVBQUUsQ0FBQztZQUNqQixVQUFVLEVBQUUsQ0FBQztTQUNoQjtRQUNELFNBQVMsRUFBRSxJQUFJO1FBQ2YsVUFBVSxFQUFFLElBQUk7UUFDaEIsY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxHQUFHLEVBQUU7UUFDRCxhQUFhLEVBQUUsa0RBQWtEO1FBQ2pFLGNBQWMsRUFBRTtZQUNaLE9BQU8sRUFBRSxvQkFBb0I7WUFDN0IsU0FBUyxFQUFFLENBQUM7WUFDWixTQUFTLEVBQUUsR0FBRztTQUNqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  117795. /***/ }),
  117796. /* 50 */
  117797. /***/ (function(module, exports, __webpack_require__) {
  117798. "use strict";
  117799. Object.defineProperty(exports, "__esModule", { value: true });
  117800. /**
  117801. * Defines a default directional shadow light for normalized objects (!)
  117802. */
  117803. exports.shadowDirectionalLightConfiguration = {
  117804. model: {
  117805. receiveShadows: true,
  117806. castShadow: true
  117807. },
  117808. ground: {
  117809. receiveShadows: true
  117810. },
  117811. lights: {
  117812. shadowDirectionalLight: {
  117813. type: 1,
  117814. shadowEnabled: true,
  117815. target: { x: 0, y: 0, z: 0.5 },
  117816. position: { x: 1.49, y: 2.39, z: -1.33 },
  117817. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  117818. intensity: 4.887,
  117819. intensityMode: 0,
  117820. shadowBufferSize: 1024,
  117821. shadowFrustumSize: 6.0,
  117822. shadowFieldOfView: 50.977,
  117823. shadowMinZ: 0.1,
  117824. shadowMaxZ: 10.0,
  117825. shadowConfig: {
  117826. blurKernel: 32,
  117827. useBlurCloseExponentialShadowMap: true
  117828. }
  117829. }
  117830. }
  117831. };
  117832. /**
  117833. * Defines a default shadow-enabled spot light for normalized objects.
  117834. */
  117835. exports.shadowSpotlLightConfiguration = {
  117836. model: {
  117837. receiveShadows: true,
  117838. castShadow: true
  117839. },
  117840. ground: {
  117841. receiveShadows: true
  117842. },
  117843. lights: {
  117844. shadowSpotLight: {
  117845. type: 2,
  117846. intensity: 2,
  117847. shadowEnabled: true,
  117848. target: { x: 0, y: 0, z: 0.5 },
  117849. position: { x: 0, y: 3.5, z: 3.7 },
  117850. angle: 1,
  117851. shadowOrthoScale: 0.5,
  117852. shadowBufferSize: 1024,
  117853. shadowMinZ: 0.1,
  117854. shadowMaxZ: 50.0,
  117855. shadowConfig: {
  117856. frustumEdgeFalloff: 0.5,
  117857. blurKernel: 32,
  117858. useBlurExponentialShadowMap: true
  117859. }
  117860. }
  117861. }
  117862. };
  117863. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0F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1FBQ0osY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxNQUFNLEVBQUU7UUFDSixlQUFlLEVBQUU7WUFDYixJQUFJLEVBQUUsQ0FBQztZQUNQLFNBQVMsRUFBRSxDQUFDO1lBQ1osYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDOUIsUUFBUSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsR0FBRyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDbEMsS0FBSyxFQUFFLENBQUM7WUFDUixnQkFBZ0IsRUFBRSxHQUFHO1lBQ3JCLGdCQUFnQixFQUFFLElBQUk7WUFDdEIsVUFBVSxFQUFFLEdBQUc7WUFDZixVQUFVLEVBQUUsSUFBSTtZQUNoQixZQUFZLEVBQUU7Z0JBQ1Ysa0JBQWtCLEVBQUUsR0FBRztnQkFDdkIsVUFBVSxFQUFFLEVBQUU7Z0JBQ2QsMkJBQTJCLEVBQUUsSUFBSTthQUNwQztTQUNKO0tBQ0o7Q0FDSixDQUFBIn0=
  117864. /***/ }),
  117865. /* 51 */
  117866. /***/ (function(module, exports, __webpack_require__) {
  117867. "use strict";
  117868. Object.defineProperty(exports, "__esModule", { value: true });
  117869. /**
  117870. * Lab-oriented default .env support
  117871. */
  117872. exports.environmentMapConfiguration = {
  117873. lab: {
  117874. assetsRootURL: '/assets/environment/',
  117875. environmentMap: {
  117876. texture: 'EnvMap_2.0-256.env',
  117877. rotationY: 0,
  117878. tintLevel: 0.4
  117879. }
  117880. }
  117881. };
  117882. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  117883. /***/ }),
  117884. /* 52 */
  117885. /***/ (function(module, exports, __webpack_require__) {
  117886. "use strict";
  117887. Object.defineProperty(exports, "__esModule", { value: true });
  117888. /**
  117889. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  117890. * native GroupAnimation class.
  117891. */
  117892. var GroupModelAnimation = /** @class */ (function () {
  117893. /**
  117894. * Create a new GroupModelAnimation object using an AnimationGroup object
  117895. * @param _animationGroup The aniamtion group to base the class on
  117896. */
  117897. function GroupModelAnimation(_animationGroup) {
  117898. var _this = this;
  117899. this._animationGroup = _animationGroup;
  117900. this._state = 0 /* INIT */;
  117901. this._playMode = 1 /* LOOP */;
  117902. this._animationGroup.onAnimationEndObservable.add(function () {
  117903. _this.stop();
  117904. _this._state = 4 /* ENDED */;
  117905. });
  117906. }
  117907. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  117908. /**
  117909. * Get the animation's name
  117910. */
  117911. get: function () {
  117912. return this._animationGroup.name;
  117913. },
  117914. enumerable: true,
  117915. configurable: true
  117916. });
  117917. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  117918. /**
  117919. * Get the current animation's state
  117920. */
  117921. get: function () {
  117922. return this._state;
  117923. },
  117924. enumerable: true,
  117925. configurable: true
  117926. });
  117927. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  117928. /**
  117929. * Gets the speed ratio to use for all animations
  117930. */
  117931. get: function () {
  117932. return this._animationGroup.speedRatio;
  117933. },
  117934. /**
  117935. * Sets the speed ratio to use for all animations
  117936. */
  117937. set: function (value) {
  117938. this._animationGroup.speedRatio = value;
  117939. },
  117940. enumerable: true,
  117941. configurable: true
  117942. });
  117943. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  117944. /**
  117945. * Get the max numbers of frame available in the animation group
  117946. *
  117947. * In correlation to an arry, this would be ".length"
  117948. */
  117949. get: function () {
  117950. return this._animationGroup.to - this._animationGroup.from;
  117951. },
  117952. enumerable: true,
  117953. configurable: true
  117954. });
  117955. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  117956. /**
  117957. * Get the current frame playing right now.
  117958. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  117959. *
  117960. * In correlation to an array, this would be the current index
  117961. */
  117962. get: function () {
  117963. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  117964. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  117965. }
  117966. else {
  117967. return 0;
  117968. }
  117969. },
  117970. enumerable: true,
  117971. configurable: true
  117972. });
  117973. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  117974. /**
  117975. * Get the FPS value of this animation
  117976. */
  117977. get: function () {
  117978. // get the first currentFrame found
  117979. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  117980. var animatable = this._animationGroup.animatables[i];
  117981. var animations = animatable.getAnimations();
  117982. if (!animations || !animations.length) {
  117983. continue;
  117984. }
  117985. for (var idx = 0; idx < animations.length; ++idx) {
  117986. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  117987. return animations[idx].animation.framePerSecond;
  117988. }
  117989. }
  117990. }
  117991. return 0;
  117992. },
  117993. enumerable: true,
  117994. configurable: true
  117995. });
  117996. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  117997. /**
  117998. * What is the animation'S play mode (looping or played once)
  117999. */
  118000. get: function () {
  118001. return this._playMode;
  118002. },
  118003. /**
  118004. * Set the play mode.
  118005. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  118006. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  118007. */
  118008. set: function (value) {
  118009. if (value === this._playMode) {
  118010. return;
  118011. }
  118012. this._playMode = value;
  118013. if (this.state === 1 /* PLAYING */) {
  118014. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  118015. }
  118016. else {
  118017. this._animationGroup.reset();
  118018. this._state = 0 /* INIT */;
  118019. }
  118020. },
  118021. enumerable: true,
  118022. configurable: true
  118023. });
  118024. /**
  118025. * Reset the animation group
  118026. */
  118027. GroupModelAnimation.prototype.reset = function () {
  118028. this._animationGroup.reset();
  118029. };
  118030. /**
  118031. * Restart the animation group
  118032. */
  118033. GroupModelAnimation.prototype.restart = function () {
  118034. if (this.state === 2 /* PAUSED */)
  118035. this._animationGroup.restart();
  118036. else
  118037. this.start();
  118038. };
  118039. /**
  118040. *
  118041. * @param frameNumber Go to a specific frame in the animation
  118042. */
  118043. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  118044. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  118045. };
  118046. /**
  118047. * Start playing the animation.
  118048. */
  118049. GroupModelAnimation.prototype.start = function () {
  118050. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  118051. if (this._animationGroup.isStarted) {
  118052. this._state = 1 /* PLAYING */;
  118053. }
  118054. };
  118055. /**
  118056. * Pause the animation
  118057. */
  118058. GroupModelAnimation.prototype.pause = function () {
  118059. this._animationGroup.pause();
  118060. this._state = 2 /* PAUSED */;
  118061. };
  118062. /**
  118063. * Stop the animation.
  118064. * This will fail silently if the animation group is already stopped.
  118065. */
  118066. GroupModelAnimation.prototype.stop = function () {
  118067. this._animationGroup.stop();
  118068. if (!this._animationGroup.isStarted) {
  118069. this._state = 3 /* STOPPED */;
  118070. }
  118071. };
  118072. /**
  118073. * Dispose this animation object.
  118074. */
  118075. GroupModelAnimation.prototype.dispose = function () {
  118076. this._animationGroup.dispose();
  118077. };
  118078. return GroupModelAnimation;
  118079. }());
  118080. exports.GroupModelAnimation = GroupModelAnimation;
  118081. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLElBQUksQ0FBQyxNQUFNLGVBQXNCLENBQUM7UUFDbEMsSUFBSSxDQUFDLFNBQVMsZUFBeUIsQ0FBQztRQUV4QyxJQUFJLENBQUMsZUFBZSxDQUFDLHdCQUF3QixDQUFDLEdBQUcsQ0FBQztZQUM5QyxLQUFJLENBQUMsSUFBSSxFQUFFLENBQUM7WUFDWixLQUFJLENBQUMsTUFBTSxnQkFBdUIsQ0FBQztRQUN2QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFLRCxzQkFBVyxxQ0FBSTtRQUhmOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsSUFBSSxDQUFDO1FBQ3JDLENBQUM7OztPQUFBO0lBS0Qsc0JBQVcsc0NBQUs7UUFIaEI7O1dBRUc7YUFDSDtZQUNJLE9BQU8sSUFBSSxDQUFDLE1BQU0sQ0FBQztRQUN2QixDQUFDOzs7T0FBQTtJQUtELHNCQUFXLDJDQUFVO1FBSHJCOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsVUF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QUFDLElBQUksRUFBRSxDQUFDO1FBQzVCLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0=
  118082. /***/ }),
  118083. /* 53 */
  118084. /***/ (function(module, exports, __webpack_require__) {
  118085. "use strict";
  118086. Object.defineProperty(exports, "__esModule", { value: true });
  118087. var telemetryLoaderPlugin_1 = __webpack_require__(54);
  118088. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  118089. var msftLodLoaderPlugin_1 = __webpack_require__(55);
  118090. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  118091. var applyMaterialConfig_1 = __webpack_require__(56);
  118092. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  118093. var extendedMaterialLoaderPlugin_1 = __webpack_require__(57);
  118094. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  118095. var babylonjs_1 = __webpack_require__(0);
  118096. var pluginCache = {};
  118097. /**
  118098. * Get a loader plugin according to its name.
  118099. * The plugin will be cached and will be reused if called for again.
  118100. *
  118101. * @param name the name of the plugin
  118102. */
  118103. function getLoaderPluginByName(name) {
  118104. if (!pluginCache[name]) {
  118105. switch (name) {
  118106. case 'telemetry':
  118107. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  118108. break;
  118109. case 'msftLod':
  118110. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  118111. break;
  118112. case 'applyMaterialConfig':
  118113. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  118114. break;
  118115. case 'extendedMaterial':
  118116. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  118117. break;
  118118. }
  118119. }
  118120. return pluginCache[name];
  118121. }
  118122. exports.getLoaderPluginByName = getLoaderPluginByName;
  118123. /**
  118124. *
  118125. */
  118126. function addLoaderPlugin(name, plugin) {
  118127. if (pluginCache[name]) {
  118128. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  118129. }
  118130. pluginCache[name] = plugin;
  118131. }
  118132. exports.addLoaderPlugin = addLoaderPlugin;
  118133. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBZ0U7QUFTdkQsZ0NBVEEsNkNBQXFCLENBU0E7QUFQOUIsNkRBQTREO0FBT2IsOEJBUHRDLHlDQUFtQixDQU9zQztBQU5sRSw2REFBa0U7QUFNRSxvQ0FOM0QsK0NBQXlCLENBTTJEO0FBTDdGLCtFQUE4RTtBQUtpQix1Q0FMdEYsMkRBQTRCLENBS3NGO0FBSjNILHVDQUFrQztBQUVsQyxJQUFNLFdBQVcsR0FBcUMsRUFBRSxDQUFDO0FBSXpEOzs7OztHQUtHO0FBQ0gsK0JBQXNDLElBQVk7SUFDOUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLENBQUMsRUFBRTtRQUNwQixRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssV0FBVztnQkFDWixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSw2Q0FBcUIsRUFBRSxDQUFDO2dCQUNoRCxNQUFNO1lBQ1YsS0FBSyxTQUFTO2dCQUNWLFdBQVcsQ0FBQyxJQUFJLENBQUMsR0FBRyxJQUFJLHlDQUFtQixFQUFFLENBQUM7Z0JBQzlDLE1BQU07WUFDVixLQUFLLHFCQUFxQjtnQkFDdEIsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLElBQUksK0NBQXlCLEVBQUUsQ0FBQztnQkFDcEQsTUFBTTtZQUNWLEtBQUssa0JBQWtCO2dCQUNuQixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSwyREFBNEIsRUFBRSxDQUFDO2dCQUN2RCxNQUFNO1NBQ2I7S0FDSjtJQUVELE9BQU8sV0FBVyxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQzdCLENBQUM7QUFuQkQsc0RBbUJDO0FBRUQ7O0dBRUc7QUFDSCx5QkFBZ0MsSUFBWSxFQUFFLE1BQXFCO0lBQy9ELElBQUksV0FBVyxDQUFDLElBQUksQ0FBQyxFQUFFO1FBQ25CLGlCQUFLLENBQUMsSUFBSSxDQUFDLDBDQUEwQyxHQUFHLElBQUksQ0FBQyxDQUFDO0tBQ2pFO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  118134. /***/ }),
  118135. /* 54 */
  118136. /***/ (function(module, exports, __webpack_require__) {
  118137. "use strict";
  118138. Object.defineProperty(exports, "__esModule", { value: true });
  118139. var telemetryManager_1 = __webpack_require__(6);
  118140. var babylonjs_1 = __webpack_require__(0);
  118141. var TelemetryLoaderPlugin = /** @class */ (function () {
  118142. function TelemetryLoaderPlugin() {
  118143. }
  118144. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  118145. this._model = model;
  118146. this._loadStart = babylonjs_1.Tools.Now;
  118147. };
  118148. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  118149. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  118150. model: model,
  118151. loadTime: babylonjs_1.Tools.Now - this._loadStart
  118152. });
  118153. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  118154. };
  118155. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  118156. this._loadEnd = babylonjs_1.Tools.Now;
  118157. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  118158. model: this._model,
  118159. loadTime: this._loadEnd - this._loadStart
  118160. });
  118161. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  118162. };
  118163. TelemetryLoaderPlugin.prototype.onComplete = function () {
  118164. this._loadEnd = babylonjs_1.Tools.Now;
  118165. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  118166. model: this._model,
  118167. loadTime: this._loadEnd - this._loadStart
  118168. });
  118169. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  118170. };
  118171. return TelemetryLoaderPlugin;
  118172. }());
  118173. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  118174. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TG9hZGVyUGx1Z2luLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2xvYWRlci9wbHVnaW5zL3RlbGVtZXRyeUxvYWRlclBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLG9FQUFtRTtBQUVuRSx1Q0FBK0U7QUFHL0U7SUFBQTtJQXVDQSxDQUFDO0lBaENVLHNDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO1FBQ3BCLElBQUksQ0FBQyxVQUFVLEdBQUcs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BQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9
  118175. /***/ }),
  118176. /* 55 */
  118177. /***/ (function(module, exports, __webpack_require__) {
  118178. "use strict";
  118179. Object.defineProperty(exports, "__esModule", { value: true });
  118180. /**
  118181. * A loder plugin to use MSFT_lod extension correctly (glTF)
  118182. */
  118183. var MSFTLodLoaderPlugin = /** @class */ (function () {
  118184. function MSFTLodLoaderPlugin() {
  118185. }
  118186. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  118187. this._model = model;
  118188. };
  118189. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  118190. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  118191. var MSFT_lod = extension;
  118192. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  118193. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  118194. }
  118195. };
  118196. return MSFTLodLoaderPlugin;
  118197. }());
  118198. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  118199. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBTUE7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  118200. /***/ }),
  118201. /* 56 */
  118202. /***/ (function(module, exports, __webpack_require__) {
  118203. "use strict";
  118204. Object.defineProperty(exports, "__esModule", { value: true });
  118205. /**
  118206. * Force-apply material configuration right after a material was loaded.
  118207. */
  118208. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  118209. function ApplyMaterialConfigPlugin() {
  118210. }
  118211. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  118212. this._model = model;
  118213. };
  118214. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  118215. this._model && this._model._applyModelMaterialConfiguration(material);
  118216. };
  118217. return ApplyMaterialConfigPlugin;
  118218. }());
  118219. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  118220. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  118221. /***/ }),
  118222. /* 57 */
  118223. /***/ (function(module, exports, __webpack_require__) {
  118224. "use strict";
  118225. Object.defineProperty(exports, "__esModule", { value: true });
  118226. var babylonjs_1 = __webpack_require__(0);
  118227. /**
  118228. * A (PBR) material will be extended using this function.
  118229. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  118230. */
  118231. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  118232. function ExtendedMaterialLoaderPlugin() {
  118233. }
  118234. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  118235. var material = baseMaterial;
  118236. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  118237. };
  118238. return ExtendedMaterialLoaderPlugin;
  118239. }());
  118240. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  118241. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTBEO0FBSTFEOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  118242. /***/ }),
  118243. /* 58 */
  118244. /***/ (function(module, exports, __webpack_require__) {
  118245. "use strict";
  118246. Object.defineProperty(exports, "__esModule", { value: true });
  118247. var babylonjs_1 = __webpack_require__(0);
  118248. var ObservablesManager = /** @class */ (function () {
  118249. function ObservablesManager() {
  118250. this.onSceneInitObservable = new babylonjs_1.Observable();
  118251. this.onEngineInitObservable = new babylonjs_1.Observable();
  118252. this.onModelLoadedObservable = new babylonjs_1.Observable();
  118253. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  118254. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  118255. this.onModelAddedObservable = new babylonjs_1.Observable();
  118256. this.onModelRemovedObservable = new babylonjs_1.Observable();
  118257. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  118258. this.onViewerInitStartedObservable = new babylonjs_1.Observable();
  118259. this.onLoaderInitObservable = new babylonjs_1.Observable();
  118260. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  118261. }
  118262. ObservablesManager.prototype.dispose = function () {
  118263. this.onSceneInitObservable.clear();
  118264. this.onEngineInitObservable.clear();
  118265. this.onModelLoadedObservable.clear();
  118266. this.onModelLoadProgressObservable.clear();
  118267. this.onModelLoadErrorObservable.clear();
  118268. this.onModelAddedObservable.clear();
  118269. this.onModelRemovedObservable.clear();
  118270. this.onViewerInitDoneObservable.clear();
  118271. this.onLoaderInitObservable.clear();
  118272. this.onFrameRenderedObservable.clear();
  118273. };
  118274. return ObservablesManager;
  118275. }());
  118276. exports.ObservablesManager = ObservablesManager;
  118277. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL29ic2VydmFibGVzTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE2SDtBQUk3SDtJQW9ESTtRQUNJLElBQUksQ0FBQyxxQkFBcUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUM5QyxJQUFJLENBQUMsc0JBQXNCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDL0MsSUFBSSxDQUFDLHVCQUF1QixHQUFHLElBQUksc0JBQVUsRUFBRSxDQUFDO1FBQ2hELElBQUksQ0FBQyw2QkFBNkIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUN0RCxJQUFJLENBQUMsMEJBQTBCLEdBQUcsS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0FBQUQsQ0FBQyxBQS9FRCxJQStFQztBQS9FWSxnREFBa0IifQ==
  118278. /***/ }),
  118279. /* 59 */
  118280. /***/ (function(module, exports, __webpack_require__) {
  118281. "use strict";
  118282. Object.defineProperty(exports, "__esModule", { value: true });
  118283. var babylonjs_1 = __webpack_require__(0);
  118284. var configuration_1 = __webpack_require__(14);
  118285. var viewerModel_1 = __webpack_require__(5);
  118286. var helper_1 = __webpack_require__(1);
  118287. var viewerLabs_1 = __webpack_require__(60);
  118288. var _1 = __webpack_require__(16);
  118289. var SceneManager = /** @class */ (function () {
  118290. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  118291. var _this = this;
  118292. this._engine = _engine;
  118293. this._configurationContainer = _configurationContainer;
  118294. this._observablesManager = _observablesManager;
  118295. this._animationBlendingEnabled = true;
  118296. this._white = babylonjs_1.Color3.White();
  118297. this._forceShadowUpdate = false;
  118298. this._processShadows = true;
  118299. this._groundEnabled = true;
  118300. this._groundMirrorEnabled = true;
  118301. this._defaultRenderingPipelineEnabled = false;
  118302. this._globalConfiguration = {};
  118303. this._defaultRenderingPipelineShouldBuild = true;
  118304. // default from rendering pipeline
  118305. this._bloomEnabled = false;
  118306. // default from rendering pipeline
  118307. this._fxaaEnabled = false;
  118308. this._focusOnModel = function (model) {
  118309. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  118310. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  118311. var halfSizeVec = sizeVec.scale(0.5);
  118312. var center = boundingInfo.min.add(halfSizeVec);
  118313. _this.camera.setTarget(center);
  118314. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  118315. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  118316. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  118317. var sceneDiagonalLenght = sizeVec.length();
  118318. if (isFinite(sceneDiagonalLenght))
  118319. _this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  118320. if (_this._configurationContainer.configuration)
  118321. _this._configureEnvironment(_this._configurationContainer.configuration.skybox, _this._configurationContainer.configuration.ground);
  118322. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  118323. // casting ais safe, due to the constraints tested before
  118324. (<ShadowLight>light).setDirectionToTarget(center);
  118325. });*/
  118326. };
  118327. this._cameraBehaviorMapping = {};
  118328. this.models = [];
  118329. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  118330. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  118331. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  118332. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  118333. this.onSceneInitObservable = new babylonjs_1.Observable();
  118334. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  118335. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  118336. this.onVRConfiguredObservable = new babylonjs_1.Observable();
  118337. //this._viewer.onEngineInitObservable.add(() => {
  118338. this._handleHardwareLimitations();
  118339. //});
  118340. this.onSceneInitObservable.add(function (scene) {
  118341. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  118342. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  118343. var updateShadows = function () {
  118344. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  118345. var light = _a[_i];
  118346. var generator = light.getShadowGenerator();
  118347. if (generator) {
  118348. // Processing shadows if animates
  118349. var shadowMap = generator.getShadowMap();
  118350. if (shadowMap) {
  118351. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  118352. }
  118353. }
  118354. }
  118355. };
  118356. scene.registerBeforeRender(function () {
  118357. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  118358. // make sure all models are loaded
  118359. updateShadows();
  118360. _this._forceShadowUpdate = false;
  118361. }
  118362. else if (!(_this.models.every(function (model) {
  118363. if (!model.shadowsRenderedAfterLoad) {
  118364. model.shadowsRenderedAfterLoad = true;
  118365. return false;
  118366. }
  118367. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  118368. }))) {
  118369. updateShadows();
  118370. }
  118371. });
  118372. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  118373. });
  118374. if (this._observablesManager) {
  118375. this._observablesManager.onModelLoadedObservable.add(function (model) {
  118376. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  118377. var light = _a[_i];
  118378. var generator = light.getShadowGenerator();
  118379. if (generator) {
  118380. // Processing shadows if animates
  118381. var shadowMap = generator.getShadowMap();
  118382. if (shadowMap) {
  118383. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  118384. }
  118385. }
  118386. }
  118387. _this._focusOnModel(model);
  118388. });
  118389. this._observablesManager.onModelAddedObservable.add(function (model) {
  118390. _this.models.push(model);
  118391. });
  118392. this._observablesManager.onModelRemovedObservable.add(function (model) {
  118393. _this.models.splice(_this.models.indexOf(model), 1);
  118394. });
  118395. }
  118396. }
  118397. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  118398. get: function () {
  118399. return this._defaultRenderingPipeline;
  118400. },
  118401. enumerable: true,
  118402. configurable: true
  118403. });
  118404. Object.defineProperty(SceneManager.prototype, "vrHelper", {
  118405. get: function () {
  118406. return this._vrHelper;
  118407. },
  118408. enumerable: true,
  118409. configurable: true
  118410. });
  118411. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  118412. /**
  118413. * Returns a boolean representing HDR support
  118414. */
  118415. get: function () {
  118416. return this._hdrSupport;
  118417. },
  118418. enumerable: true,
  118419. configurable: true
  118420. });
  118421. Object.defineProperty(SceneManager.prototype, "mainColor", {
  118422. /**
  118423. * Return the main color defined in the configuration.
  118424. */
  118425. get: function () {
  118426. return this._configurationContainer.mainColor;
  118427. },
  118428. enumerable: true,
  118429. configurable: true
  118430. });
  118431. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  118432. get: function () {
  118433. return this._configurationContainer.reflectionColor;
  118434. },
  118435. enumerable: true,
  118436. configurable: true
  118437. });
  118438. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  118439. get: function () {
  118440. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  118441. },
  118442. set: function (value) {
  118443. this.scene.animationPropertiesOverride.enableBlending = value;
  118444. },
  118445. enumerable: true,
  118446. configurable: true
  118447. });
  118448. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  118449. get: function () {
  118450. return this._observablesManager;
  118451. },
  118452. enumerable: true,
  118453. configurable: true
  118454. });
  118455. Object.defineProperty(SceneManager.prototype, "processShadows", {
  118456. /**
  118457. * The flag defining whether shadows are rendered constantly or once.
  118458. */
  118459. get: function () {
  118460. return this._processShadows;
  118461. },
  118462. /**
  118463. * Should shadows be rendered every frame, or only once and stop.
  118464. * This can be used to optimize a scene.
  118465. *
  118466. * Not that the shadows will NOT disapear but will remain in place.
  118467. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  118468. */
  118469. set: function (process) {
  118470. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  118471. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  118472. var light = _a[_i];
  118473. var generator = light.getShadowGenerator();
  118474. if (generator) {
  118475. var shadowMap = generator.getShadowMap();
  118476. if (shadowMap) {
  118477. shadowMap.refreshRate = refreshType;
  118478. }
  118479. }
  118480. }
  118481. this._processShadows = process;
  118482. },
  118483. enumerable: true,
  118484. configurable: true
  118485. });
  118486. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  118487. get: function () {
  118488. return this._groundEnabled;
  118489. },
  118490. set: function (newValue) {
  118491. if (newValue === this._groundEnabled)
  118492. return;
  118493. this._groundEnabled = newValue;
  118494. if (this.environmentHelper && this.environmentHelper.ground) {
  118495. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  118496. }
  118497. },
  118498. enumerable: true,
  118499. configurable: true
  118500. });
  118501. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  118502. /**
  118503. * gets wether the reflection is disabled.
  118504. */
  118505. get: function () {
  118506. return this._groundMirrorEnabled;
  118507. },
  118508. /**
  118509. * sets wether the reflection is disabled.
  118510. */
  118511. set: function (value) {
  118512. if (this._groundMirrorEnabled === value) {
  118513. return;
  118514. }
  118515. this._groundMirrorEnabled = value;
  118516. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  118517. if (!value) {
  118518. this.environmentHelper.groundMaterial.reflectionTexture = null;
  118519. }
  118520. else {
  118521. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  118522. }
  118523. }
  118524. },
  118525. enumerable: true,
  118526. configurable: true
  118527. });
  118528. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  118529. get: function () {
  118530. return this._defaultRenderingPipelineEnabled;
  118531. },
  118532. set: function (value) {
  118533. if (value === this._defaultRenderingPipelineEnabled) {
  118534. return;
  118535. }
  118536. this._defaultRenderingPipelineEnabled = value;
  118537. this._rebuildPostprocesses();
  118538. if (this._defaultRenderingPipeline) {
  118539. this._defaultRenderingPipelineShouldBuild = false;
  118540. this._defaultRenderingPipeline.prepare();
  118541. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  118542. }
  118543. },
  118544. enumerable: true,
  118545. configurable: true
  118546. });
  118547. /**
  118548. * Sets the engine flags to unlock all babylon features.
  118549. * Can also be configured using the scene.flags configuration object
  118550. */
  118551. SceneManager.prototype.unlockBabylonFeatures = function () {
  118552. this.scene.shadowsEnabled = true;
  118553. this.scene.particlesEnabled = true;
  118554. this.scene.postProcessesEnabled = true;
  118555. this.scene.collisionsEnabled = true;
  118556. this.scene.lightsEnabled = true;
  118557. this.scene.texturesEnabled = true;
  118558. this.scene.lensFlaresEnabled = true;
  118559. this.scene.proceduralTexturesEnabled = true;
  118560. this.scene.renderTargetsEnabled = true;
  118561. this.scene.spritesEnabled = true;
  118562. this.scene.skeletonsEnabled = true;
  118563. this.scene.audioEnabled = true;
  118564. };
  118565. /**
  118566. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  118567. */
  118568. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  118569. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  118570. // if the scen exists, dispose it.
  118571. if (this.scene) {
  118572. this.scene.dispose();
  118573. }
  118574. // create a new scene
  118575. this.scene = new babylonjs_1.Scene(this._engine);
  118576. this._configurationContainer.scene = this.scene;
  118577. // set a default PBR material
  118578. if (!sceneConfiguration.defaultMaterial) {
  118579. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  118580. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  118581. defaultMaterial.microSurface = 0.6;
  118582. if (this.scene.defaultMaterial) {
  118583. this.scene.defaultMaterial.dispose();
  118584. }
  118585. this.scene.defaultMaterial = defaultMaterial;
  118586. }
  118587. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  118588. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  118589. /*if (sceneConfiguration.glow) {
  118590. let options: Partial<IGlowLayerOptions> = {
  118591. mainTextureFixedSize: 512
  118592. };
  118593. if (typeof sceneConfiguration.glow === 'object') {
  118594. options = sceneConfiguration.glow
  118595. }
  118596. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  118597. }*/
  118598. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  118599. };
  118600. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  118601. if (clearModels === void 0) { clearModels = true; }
  118602. if (clearLights === void 0) { clearLights = false; }
  118603. if (clearModels) {
  118604. this.models.forEach(function (m) { return m.dispose(); });
  118605. this.models.length = 0;
  118606. }
  118607. if (clearLights) {
  118608. this.scene.lights.forEach(function (l) { return l.dispose(); });
  118609. }
  118610. };
  118611. /**
  118612. * This will update the scene's configuration, including camera, lights, environment.
  118613. * @param newConfiguration the delta that should be configured. This includes only the changes
  118614. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  118615. */
  118616. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  118617. var _this = this;
  118618. if (this._configurationContainer) {
  118619. this._globalConfiguration = this._configurationContainer.configuration;
  118620. }
  118621. else {
  118622. this._globalConfiguration = newConfiguration;
  118623. }
  118624. if (newConfiguration.lab) {
  118625. if (newConfiguration.lab.assetsRootURL) {
  118626. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  118627. }
  118628. }
  118629. // update scene configuration
  118630. if (newConfiguration.scene) {
  118631. this._configureScene(newConfiguration.scene);
  118632. }
  118633. // optimizer
  118634. if (newConfiguration.optimizer !== undefined) {
  118635. this._configureOptimizer(newConfiguration.optimizer);
  118636. }
  118637. // configure model
  118638. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  118639. this._configureModel(newConfiguration.model);
  118640. }*/
  118641. // lights
  118642. this._configureLights(newConfiguration.lights);
  118643. // environment
  118644. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  118645. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  118646. }
  118647. // camera
  118648. this._configureCamera(newConfiguration.camera);
  118649. if (newConfiguration.vr !== undefined) {
  118650. this._configureVR(newConfiguration.vr);
  118651. }
  118652. if (newConfiguration.lab) {
  118653. if (newConfiguration.lab.environmentMap) {
  118654. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  118655. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  118656. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  118657. });
  118658. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  118659. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  118660. }
  118661. }
  118662. // rendering piplines
  118663. if (newConfiguration.lab.defaultRenderingPipelines) {
  118664. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  118665. if (typeof pipelineConfig === 'boolean') {
  118666. this.defaultRenderingPipelineEnabled = pipelineConfig;
  118667. }
  118668. else {
  118669. this.defaultRenderingPipelineEnabled = true;
  118670. }
  118671. }
  118672. if (this.environmentHelper && newConfiguration.lab.environmentMainColor) {
  118673. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  118674. this.environmentHelper.setMainColor(mainColor);
  118675. }
  118676. if (newConfiguration.lab.globalLightRotation !== undefined) {
  118677. // rotate all lights that are shadow lights
  118678. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  118679. // casting and '!' are safe, due to the constraints tested before
  118680. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  118681. });
  118682. this._forceShadowUpdate = true;
  118683. }
  118684. }
  118685. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  118686. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  118687. }
  118688. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  118689. this._defaultRenderingPipelineShouldBuild = false;
  118690. this._defaultRenderingPipeline.prepare();
  118691. }
  118692. };
  118693. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  118694. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  118695. if (this._defaultRenderingPipeline) {
  118696. this._defaultRenderingPipeline.dispose();
  118697. this._defaultRenderingPipeline = null;
  118698. this.scene.autoClearDepthAndStencil = true;
  118699. this.scene.autoClear = true;
  118700. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  118701. }
  118702. return;
  118703. }
  118704. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  118705. if (pipelineConfig) {
  118706. if (!this._defaultRenderingPipeline) {
  118707. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  118708. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  118709. }
  118710. this.scene.autoClear = false;
  118711. this.scene.autoClearDepthAndStencil = false;
  118712. this._defaultRenderingPipelineShouldBuild = true;
  118713. var bloomEnabled = this._bloomEnabled;
  118714. if (typeof pipelineConfig !== 'boolean') {
  118715. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  118716. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  118717. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  118718. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  118719. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  118720. }
  118721. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  118722. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  118723. }
  118724. };
  118725. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  118726. get: function () {
  118727. return this._bloomEnabled;
  118728. },
  118729. set: function (value) {
  118730. if (this._bloomEnabled === value) {
  118731. return;
  118732. }
  118733. this._bloomEnabled = value;
  118734. this._rebuildPostprocesses();
  118735. if (this._defaultRenderingPipeline) {
  118736. this._defaultRenderingPipelineShouldBuild = false;
  118737. this._defaultRenderingPipeline.prepare();
  118738. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  118739. }
  118740. },
  118741. enumerable: true,
  118742. configurable: true
  118743. });
  118744. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  118745. get: function () {
  118746. return this._fxaaEnabled;
  118747. },
  118748. set: function (value) {
  118749. if (this._fxaaEnabled === value) {
  118750. return;
  118751. }
  118752. this._fxaaEnabled = value;
  118753. this._rebuildPostprocesses();
  118754. if (this._defaultRenderingPipeline) {
  118755. this._defaultRenderingPipelineShouldBuild = false;
  118756. this._defaultRenderingPipeline.prepare();
  118757. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  118758. }
  118759. },
  118760. enumerable: true,
  118761. configurable: true
  118762. });
  118763. /**
  118764. * internally configure the scene using the provided configuration.
  118765. * The scene will not be recreated, but just updated.
  118766. * @param sceneConfig the (new) scene configuration
  118767. */
  118768. SceneManager.prototype._configureScene = function (sceneConfig) {
  118769. // sanity check!
  118770. if (!this.scene) {
  118771. return;
  118772. }
  118773. var cc = sceneConfig.clearColor;
  118774. var oldcc = this.scene.clearColor;
  118775. if (cc) {
  118776. if (cc.r !== undefined) {
  118777. oldcc.r = cc.r;
  118778. }
  118779. if (cc.g !== undefined) {
  118780. oldcc.g = cc.g;
  118781. }
  118782. if (cc.b !== undefined) {
  118783. oldcc.b = cc.b;
  118784. }
  118785. if (cc.a !== undefined) {
  118786. oldcc.a = cc.a;
  118787. }
  118788. }
  118789. // image processing configuration - optional.
  118790. if (sceneConfig.imageProcessingConfiguration) {
  118791. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  118792. }
  118793. //animation properties override
  118794. if (sceneConfig.animationPropertiesOverride) {
  118795. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  118796. }
  118797. if (sceneConfig.environmentTexture) {
  118798. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  118799. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  118800. this.scene.environmentTexture.dispose();
  118801. }
  118802. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  118803. this.scene.environmentTexture = environmentTexture;
  118804. }
  118805. }
  118806. if (sceneConfig.debug === true) {
  118807. this.scene.debugLayer.show();
  118808. }
  118809. else if (sceneConfig.debug === false) {
  118810. if (this.scene.debugLayer.isVisible()) {
  118811. this.scene.debugLayer.hide();
  118812. }
  118813. }
  118814. if (sceneConfig.disableHdr) {
  118815. this._handleHardwareLimitations(false);
  118816. }
  118817. else {
  118818. this._handleHardwareLimitations(true);
  118819. }
  118820. if (sceneConfig.renderInBackground !== undefined) {
  118821. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  118822. }
  118823. var canvas = this._engine.getRenderingCanvas();
  118824. if (canvas) {
  118825. if (this.camera && sceneConfig.disableCameraControl) {
  118826. this.camera.detachControl(canvas);
  118827. }
  118828. else if (this.camera && sceneConfig.disableCameraControl === false) {
  118829. this.camera.attachControl(canvas);
  118830. }
  118831. }
  118832. // process mainColor changes:
  118833. if (sceneConfig.mainColor) {
  118834. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  118835. var mc = sceneConfig.mainColor;
  118836. if (mc.r !== undefined) {
  118837. this.mainColor.r = mc.r;
  118838. }
  118839. if (mc.g !== undefined) {
  118840. this.mainColor.g = mc.g;
  118841. }
  118842. if (mc.b !== undefined) {
  118843. this.mainColor.b = mc.b;
  118844. }
  118845. this.reflectionColor.copyFrom(this.mainColor);
  118846. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  118847. // reflection color
  118848. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  118849. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  118850. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  118851. this.reflectionColor.copyFrom(tmpColor3);
  118852. //update the environment, if exists
  118853. if (this.environmentHelper) {
  118854. if (this.environmentHelper.groundMaterial) {
  118855. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  118856. }
  118857. if (this.environmentHelper.skyboxMaterial) {
  118858. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  118859. }
  118860. }
  118861. }
  118862. if (sceneConfig.defaultMaterial) {
  118863. var conf = sceneConfig.defaultMaterial;
  118864. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  118865. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  118866. this.scene.defaultMaterial.dispose();
  118867. if (conf.materialType === 'standard') {
  118868. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  118869. }
  118870. else {
  118871. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  118872. }
  118873. }
  118874. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  118875. }
  118876. if (sceneConfig.flags) {
  118877. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  118878. }
  118879. this.onSceneConfiguredObservable.notifyObservers({
  118880. sceneManager: this,
  118881. object: this.scene,
  118882. newConfiguration: sceneConfig
  118883. });
  118884. };
  118885. /**
  118886. * Configure the scene optimizer.
  118887. * The existing scene optimizer will be disposed and a new one will be created.
  118888. * @param optimizerConfig the (new) optimizer configuration
  118889. */
  118890. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  118891. var _this = this;
  118892. if (typeof optimizerConfig === 'boolean') {
  118893. if (this.sceneOptimizer) {
  118894. this.sceneOptimizer.stop();
  118895. this.sceneOptimizer.dispose();
  118896. delete this.sceneOptimizer;
  118897. }
  118898. if (optimizerConfig) {
  118899. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  118900. this.sceneOptimizer.start();
  118901. }
  118902. }
  118903. else {
  118904. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  118905. // check for degradation
  118906. if (optimizerConfig.degradation) {
  118907. switch (optimizerConfig.degradation) {
  118908. case "low":
  118909. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  118910. break;
  118911. case "moderate":
  118912. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  118913. break;
  118914. case "hight":
  118915. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  118916. break;
  118917. }
  118918. }
  118919. if (this.sceneOptimizer) {
  118920. this.sceneOptimizer.stop();
  118921. this.sceneOptimizer.dispose();
  118922. }
  118923. if (optimizerConfig.custom) {
  118924. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  118925. if (customOptimizer_1) {
  118926. optimizerOptions.addCustomOptimization(function () {
  118927. return customOptimizer_1(_this);
  118928. }, function () {
  118929. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  118930. });
  118931. }
  118932. }
  118933. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  118934. this.sceneOptimizer.start();
  118935. }
  118936. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  118937. sceneManager: this,
  118938. object: this.sceneOptimizer,
  118939. newConfiguration: optimizerConfig
  118940. });
  118941. };
  118942. /**
  118943. * configure all models using the configuration.
  118944. * @param modelConfiguration the configuration to use to reconfigure the models
  118945. */
  118946. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  118947. this.models.forEach(model => {
  118948. model.updateConfiguration(modelConfiguration);
  118949. });
  118950. this.onModelsConfiguredObservable.notifyObservers({
  118951. sceneManager: this,
  118952. object: this.models,
  118953. newConfiguration: modelConfiguration
  118954. });
  118955. }*/
  118956. SceneManager.prototype._configureVR = function (vrConfig) {
  118957. var _this = this;
  118958. if (vrConfig.disabled) {
  118959. if (this._vrHelper) {
  118960. if (this._vrHelper.isInVRMode) {
  118961. this._vrHelper.exitVR();
  118962. }
  118963. this._vrHelper.dispose();
  118964. this._vrHelper = undefined;
  118965. }
  118966. return;
  118967. }
  118968. var vrOptions = vrConfig.vrOptions || {
  118969. useCustomVRButton: true,
  118970. createDeviceOrientationCamera: false,
  118971. trackPosition: true
  118972. };
  118973. this._vrHelper = this.scene.createDefaultVRExperience(vrOptions);
  118974. if (!vrConfig.disableInteractions) {
  118975. this._vrHelper.enableInteractions();
  118976. }
  118977. if (!vrConfig.disableTeleportation) {
  118978. var floorMeshName = vrConfig.overrideFloorMeshName || "BackgroundPlane";
  118979. this._vrHelper.enableTeleportation({
  118980. floorMeshName: floorMeshName
  118981. });
  118982. }
  118983. if (vrConfig.rotateUsingControllers) {
  118984. var rotationOffset_1;
  118985. this._vrHelper.onControllerMeshLoadedObservable.add(function (controller) {
  118986. controller.onTriggerStateChangedObservable.add(function (data) {
  118987. if (controller.mesh && controller.mesh.rotationQuaternion) {
  118988. if (data.pressed) {
  118989. if (!rotationOffset_1) {
  118990. _this.models[0].rootMesh.rotationQuaternion = _this.models[0].rootMesh.rotationQuaternion || new babylonjs_1.Quaternion();
  118991. rotationOffset_1 = controller.mesh.rotationQuaternion.conjugate().multiply(_this.models[0].rootMesh.rotationQuaternion);
  118992. }
  118993. }
  118994. else {
  118995. rotationOffset_1 = null;
  118996. }
  118997. }
  118998. });
  118999. _this.scene.registerBeforeRender(function () {
  119000. if (_this.models[0]) {
  119001. if (rotationOffset_1 && controller.mesh && controller.mesh.rotationQuaternion) {
  119002. _this.models[0].rootMesh.rotationQuaternion.copyFrom(controller.mesh.rotationQuaternion).multiplyInPlace(rotationOffset_1);
  119003. }
  119004. else {
  119005. _this.models[0].rootMesh.rotationQuaternion = null;
  119006. }
  119007. }
  119008. });
  119009. });
  119010. }
  119011. this.onVRConfiguredObservable.notifyObservers({
  119012. sceneManager: this,
  119013. object: this._vrHelper,
  119014. newConfiguration: vrConfig
  119015. });
  119016. };
  119017. /**
  119018. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  119019. * @param cameraConfig the new camera configuration
  119020. * @param model optionally use the model to configure the camera.
  119021. */
  119022. SceneManager.prototype._configureCamera = function (cameraConfig) {
  119023. var _this = this;
  119024. if (cameraConfig === void 0) { cameraConfig = {}; }
  119025. if (!this.scene.activeCamera) {
  119026. var attachControl = true;
  119027. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  119028. attachControl = false;
  119029. }
  119030. this.scene.createDefaultCamera(true, true, attachControl);
  119031. this.camera = this.scene.activeCamera;
  119032. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  119033. }
  119034. if (!this.camera) {
  119035. this.camera = this.scene.activeCamera;
  119036. }
  119037. if (cameraConfig.position) {
  119038. var newPosition = this.camera.position.clone();
  119039. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  119040. this.camera.setPosition(newPosition);
  119041. }
  119042. if (cameraConfig.target) {
  119043. var newTarget = this.camera.target.clone();
  119044. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  119045. this.camera.setTarget(newTarget);
  119046. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  119047. this._focusOnModel(this.models[0]);
  119048. }*/
  119049. if (cameraConfig.rotation) {
  119050. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  119051. }
  119052. if (cameraConfig.behaviors) {
  119053. for (var name_1 in cameraConfig.behaviors) {
  119054. if (cameraConfig.behaviors[name_1] !== undefined) {
  119055. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  119056. }
  119057. }
  119058. }
  119059. ;
  119060. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  119061. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  119062. });
  119063. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  119064. var sceneDiagonalLength = sceneDiagonal.length();
  119065. if (isFinite(sceneDiagonalLength)) {
  119066. this.camera.upperRadiusLimit = sceneDiagonalLength * 4;
  119067. }
  119068. // sanity check!
  119069. if (this.scene.imageProcessingConfiguration) {
  119070. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  119071. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  119072. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  119073. }
  119074. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  119075. this.onCameraConfiguredObservable.notifyObservers({
  119076. sceneManager: this,
  119077. object: this.camera,
  119078. newConfiguration: cameraConfig
  119079. });
  119080. };
  119081. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  119082. var _this = this;
  119083. if (!skyboxConifguration && !groundConfiguration) {
  119084. if (this.environmentHelper) {
  119085. this.environmentHelper.dispose();
  119086. this.environmentHelper = undefined;
  119087. }
  119088. ;
  119089. }
  119090. else {
  119091. var options = {
  119092. createGround: !!groundConfiguration && this._groundEnabled,
  119093. createSkybox: !!skyboxConifguration,
  119094. setupImageProcessing: false,
  119095. };
  119096. // will that cause problems with model ground configuration?
  119097. /*if (model) {
  119098. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  119099. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  119100. const halfSizeVec = sizeVec.scale(0.5);
  119101. const center = boundingInfo.min.add(halfSizeVec);
  119102. options.groundYBias = -center.y;
  119103. }*/
  119104. if (groundConfiguration) {
  119105. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  119106. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  119107. if (groundSize) {
  119108. options.groundSize = groundSize;
  119109. }
  119110. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  119111. if (groundConfig_1.shadowLevel !== undefined) {
  119112. options.groundShadowLevel = groundConfig_1.shadowLevel;
  119113. }
  119114. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  119115. if (groundConfig_1.texture) {
  119116. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  119117. }
  119118. if (groundConfig_1.color) {
  119119. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  119120. }
  119121. if (groundConfig_1.opacity !== undefined) {
  119122. options.groundOpacity = groundConfig_1.opacity;
  119123. }
  119124. if (groundConfig_1.mirror) {
  119125. options.enableGroundMirror = true;
  119126. // to prevent undefines
  119127. if (typeof groundConfig_1.mirror === "object") {
  119128. if (groundConfig_1.mirror.amount !== undefined)
  119129. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  119130. if (groundConfig_1.mirror.sizeRatio !== undefined)
  119131. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  119132. if (groundConfig_1.mirror.blurKernel !== undefined)
  119133. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  119134. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  119135. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  119136. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  119137. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  119138. if (this._defaultPipelineTextureType !== undefined)
  119139. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  119140. }
  119141. }
  119142. }
  119143. var postInitSkyboxMaterial = false;
  119144. if (skyboxConifguration) {
  119145. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  119146. if (conf.material && conf.material.imageProcessingConfiguration) {
  119147. options.setupImageProcessing = false; // will be configured later manually.
  119148. }
  119149. var skyboxSize = conf.scale;
  119150. if (skyboxSize) {
  119151. options.skyboxSize = skyboxSize;
  119152. }
  119153. options.sizeAuto = !options.skyboxSize;
  119154. if (conf.color) {
  119155. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  119156. }
  119157. if (conf.cubeTexture && conf.cubeTexture.url) {
  119158. if (typeof conf.cubeTexture.url === "string") {
  119159. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  119160. }
  119161. else {
  119162. // init later!
  119163. postInitSkyboxMaterial = true;
  119164. }
  119165. }
  119166. if (conf.material) {
  119167. postInitSkyboxMaterial = true;
  119168. }
  119169. }
  119170. options.setupImageProcessing = false; // TMP
  119171. if (!this.environmentHelper) {
  119172. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  119173. }
  119174. else {
  119175. // unlikely, but there might be a new scene! we need to dispose.
  119176. // get the scene used by the envHelper
  119177. var scene = this.environmentHelper.rootMesh.getScene();
  119178. // is it a different scene? Oh no!
  119179. if (scene !== this.scene) {
  119180. this.environmentHelper.dispose();
  119181. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  119182. }
  119183. else {
  119184. // recreate the ground
  119185. if (this.environmentHelper.ground) {
  119186. this.environmentHelper.ground.dispose();
  119187. }
  119188. // recreate the skybox
  119189. if (this.environmentHelper.skybox) {
  119190. this.environmentHelper.skybox.dispose();
  119191. }
  119192. this.environmentHelper.updateOptions(options);
  119193. // update doesn't change the size of the skybox and ground, so we have to recreate!
  119194. //this.environmentHelper.dispose();
  119195. //this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  119196. }
  119197. }
  119198. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  119199. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  119200. }
  119201. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  119202. if (this.environmentHelper.groundMaterial && groundConfig) {
  119203. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  119204. if (groundConfig.material) {
  119205. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  119206. }
  119207. if (this.environmentHelper.groundMirror) {
  119208. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  119209. // TODO user camera exposure value to set the mirror clear color
  119210. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  119211. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  119212. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  119213. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  119214. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  119215. this.environmentHelper.groundMirror.clearColor.a = 1;
  119216. if (!this.groundMirrorEnabled) {
  119217. this.environmentHelper.groundMaterial.reflectionTexture = null;
  119218. }
  119219. }
  119220. }
  119221. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  119222. if (skyboxMaterial) {
  119223. skyboxMaterial._perceptualColor = this.mainColor;
  119224. if (postInitSkyboxMaterial) {
  119225. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  119226. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  119227. }
  119228. }
  119229. }
  119230. }
  119231. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  119232. _this._updateGroundMirrorRenderList(model);
  119233. });
  119234. this.onEnvironmentConfiguredObservable.notifyObservers({
  119235. sceneManager: this,
  119236. object: this.environmentHelper,
  119237. newConfiguration: {
  119238. skybox: skyboxConifguration,
  119239. ground: groundConfiguration
  119240. }
  119241. });
  119242. };
  119243. /**
  119244. * configure the lights.
  119245. *
  119246. * @param lightsConfiguration the (new) light(s) configuration
  119247. * @param model optionally use the model to configure the camera.
  119248. */
  119249. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  119250. var _this = this;
  119251. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  119252. // sanity check!
  119253. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  119254. if (!lightKeys.length) {
  119255. if (!this.scene.lights.length)
  119256. this.scene.createDefaultLight(true);
  119257. }
  119258. else {
  119259. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  119260. // compare to the global (!) configuration object and dispose unneeded:
  119261. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  119262. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  119263. lightsAvailable_1.forEach(function (lName) {
  119264. if (lightsToConfigure_1.indexOf(lName) === -1) {
  119265. _this.scene.getLightByName(lName).dispose();
  119266. }
  119267. });
  119268. }
  119269. lightKeys.forEach(function (name, idx) {
  119270. var lightConfig = { type: 0 };
  119271. if (typeof lightsConfiguration[name] === 'object') {
  119272. lightConfig = lightsConfiguration[name];
  119273. }
  119274. if (typeof lightsConfiguration[name] === 'number') {
  119275. lightConfig.type = lightsConfiguration[name];
  119276. }
  119277. lightConfig.name = name;
  119278. var light;
  119279. // light is not already available
  119280. if (lightsAvailable_1.indexOf(name) === -1) {
  119281. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  119282. if (!constructor)
  119283. return;
  119284. light = constructor();
  119285. }
  119286. else {
  119287. // available? get it from the scene
  119288. light = _this.scene.getLightByName(name);
  119289. if (typeof lightsConfiguration[name] === 'boolean') {
  119290. lightConfig.type = light.getTypeID();
  119291. }
  119292. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  119293. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  119294. light.dispose();
  119295. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  119296. if (!constructor)
  119297. return;
  119298. light = constructor();
  119299. }
  119300. }
  119301. // if config set the light to false, dispose it.
  119302. if (lightsConfiguration[name] === false) {
  119303. light.dispose();
  119304. return;
  119305. }
  119306. //enabled
  119307. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  119308. light.setEnabled(enabled);
  119309. helper_1.extendClassWithConfig(light, lightConfig);
  119310. //position. Some lights don't support shadows
  119311. if (light instanceof babylonjs_1.ShadowLight) {
  119312. // set default values
  119313. light.shadowMinZ = light.shadowMinZ || 0.2;
  119314. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  119315. if (lightConfig.target) {
  119316. if (light.setDirectionToTarget) {
  119317. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  119318. light.setDirectionToTarget(target);
  119319. }
  119320. }
  119321. else if (lightConfig.direction) {
  119322. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  119323. light.direction = direction;
  119324. }
  119325. var isShadowEnabled = false;
  119326. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  119327. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  119328. isShadowEnabled = true;
  119329. }
  119330. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  119331. var spotLight = light;
  119332. if (lightConfig.spotAngle !== undefined) {
  119333. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  119334. }
  119335. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  119336. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  119337. }
  119338. isShadowEnabled = true;
  119339. }
  119340. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  119341. if (lightConfig.shadowFieldOfView) {
  119342. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  119343. }
  119344. isShadowEnabled = true;
  119345. }
  119346. var shadowGenerator_1 = light.getShadowGenerator();
  119347. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  119348. var bufferSize = lightConfig.shadowBufferSize || 256;
  119349. if (!shadowGenerator_1) {
  119350. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  119351. }
  119352. var blurKernel = _this.getBlurKernel(light, bufferSize);
  119353. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  119354. shadowGenerator_1.blurKernel = blurKernel;
  119355. //override defaults
  119356. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  119357. // add the focues meshes to the shadow list
  119358. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  119359. _this._updateShadowRenderList(shadowGenerator_1, model);
  119360. });
  119361. //if (model) {
  119362. _this._updateShadowRenderList(shadowGenerator_1);
  119363. //}
  119364. }
  119365. else if (shadowGenerator_1) {
  119366. shadowGenerator_1.dispose();
  119367. }
  119368. }
  119369. });
  119370. // render priority
  119371. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  119372. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  119373. var configuration = globalLightsConfiguration_1[name];
  119374. var light = _this.scene.getLightByName(name);
  119375. // sanity check
  119376. if (!light)
  119377. return;
  119378. light.renderPriority = -idx;
  119379. });
  119380. }
  119381. this.onLightsConfiguredObservable.notifyObservers({
  119382. sceneManager: this,
  119383. object: this.scene.lights,
  119384. newConfiguration: lightsConfiguration
  119385. });
  119386. };
  119387. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  119388. var focusMeshes = model ? model.meshes : this.scene.meshes;
  119389. // add the focues meshes to the shadow list
  119390. var shadownMap = shadowGenerator.getShadowMap();
  119391. if (!shadownMap)
  119392. return;
  119393. if (resetList && shadownMap.renderList) {
  119394. shadownMap.renderList.length = 0;
  119395. }
  119396. else {
  119397. shadownMap.renderList = shadownMap.renderList || [];
  119398. }
  119399. for (var index = 0; index < focusMeshes.length; index++) {
  119400. var mesh = focusMeshes[index];
  119401. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  119402. shadownMap.renderList.push(mesh);
  119403. }
  119404. }
  119405. if (!this._shadowGroundPlane) {
  119406. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  119407. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  119408. shadowGroundPlane.useVertexColors = false;
  119409. //material isn't ever used in rendering, just used to set back face culling
  119410. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  119411. shadowGroundPlane.material.backFaceCulling = false;
  119412. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  119413. shadowGroundPlane.freezeWorldMatrix();
  119414. this._shadowGroundPlane = shadowGroundPlane;
  119415. this.scene.removeMesh(shadowGroundPlane);
  119416. }
  119417. }
  119418. else {
  119419. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  119420. this._shadowGroundPlane.dispose();
  119421. this._shadowGroundPlane = null;
  119422. }
  119423. }
  119424. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  119425. shadownMap.renderList.push(this._shadowGroundPlane);
  119426. }
  119427. };
  119428. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  119429. if (this.environmentHelper && this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  119430. var focusMeshes = model ? model.meshes : this.scene.meshes;
  119431. var renderList = this.environmentHelper.groundMirror.renderList;
  119432. if (resetList) {
  119433. renderList.length = 0;
  119434. }
  119435. for (var index = 0; index < focusMeshes.length; index++) {
  119436. var mesh = focusMeshes[index];
  119437. if (renderList.indexOf(mesh) === -1) {
  119438. renderList.push(mesh);
  119439. }
  119440. }
  119441. }
  119442. };
  119443. /**
  119444. * Gets the shadow map blur kernel according to the light configuration.
  119445. * @param light The light used to generate the shadows
  119446. * @param bufferSize The size of the shadow map
  119447. * @return the kernel blur size
  119448. */
  119449. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  119450. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  119451. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  119452. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  119453. }
  119454. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  119455. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  119456. }
  119457. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  119458. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  119459. }
  119460. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  119461. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  119462. return blurKernel;
  119463. };
  119464. /**
  119465. * Alters render settings to reduce features based on hardware feature limitations
  119466. * @param enableHDR Allows the viewer to run in HDR mode.
  119467. */
  119468. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  119469. if (enableHDR === void 0) { enableHDR = true; }
  119470. //flip rendering settings switches based on hardware support
  119471. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  119472. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  119473. //shadows are disabled if there's not enough varyings for a single shadow
  119474. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  119475. this._maxShadows = 0;
  119476. }
  119477. else {
  119478. this._maxShadows = 3;
  119479. }
  119480. //can we render to any >= 16-bit targets (required for HDR)
  119481. var caps = this._engine.getCaps();
  119482. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  119483. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  119484. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  119485. if (linearHalfFloatTargets) {
  119486. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  119487. this._shadowGeneratorBias = 0.002;
  119488. }
  119489. else if (linearFloatTargets) {
  119490. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  119491. this._shadowGeneratorBias = 0.001;
  119492. }
  119493. else {
  119494. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  119495. this._shadowGeneratorBias = 0.001;
  119496. }
  119497. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  119498. };
  119499. /**
  119500. * Dispoe the entire viewer including the scene and the engine
  119501. */
  119502. SceneManager.prototype.dispose = function () {
  119503. // this.onCameraConfiguredObservable.clear();
  119504. this.onEnvironmentConfiguredObservable.clear();
  119505. this.onLightsConfiguredObservable.clear();
  119506. this.onModelsConfiguredObservable.clear();
  119507. this.onSceneConfiguredObservable.clear();
  119508. this.onSceneInitObservable.clear();
  119509. this.onSceneOptimizerConfiguredObservable.clear();
  119510. this.onVRConfiguredObservable.clear();
  119511. if (this.sceneOptimizer) {
  119512. this.sceneOptimizer.stop();
  119513. this.sceneOptimizer.dispose();
  119514. }
  119515. if (this.environmentHelper) {
  119516. this.environmentHelper.dispose();
  119517. }
  119518. this.models.forEach(function (model) {
  119519. model.dispose();
  119520. });
  119521. if (this._defaultRenderingPipeline) {
  119522. this._defaultRenderingPipeline.dispose();
  119523. }
  119524. this.models.length = 0;
  119525. if (this.scene) {
  119526. this.scene.dispose();
  119527. }
  119528. };
  119529. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  119530. var behavior;
  119531. var type;
  119532. if (typeof behaviorConfig === 'object') {
  119533. type = behaviorConfig.type;
  119534. }
  119535. else if (typeof behaviorConfig === 'number') {
  119536. type = behaviorConfig;
  119537. }
  119538. else {
  119539. type = this._cameraBehaviorMapping[name];
  119540. }
  119541. if (type === undefined)
  119542. return;
  119543. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  119544. var enabled = true;
  119545. if (typeof behaviorConfig === 'boolean') {
  119546. enabled = behaviorConfig;
  119547. }
  119548. // constructing behavior
  119549. switch (type) {
  119550. case 0 /* AUTOROTATION */:
  119551. this.camera.useAutoRotationBehavior = enabled;
  119552. behavior = this.camera.autoRotationBehavior;
  119553. break;
  119554. case 1 /* BOUNCING */:
  119555. this.camera.useBouncingBehavior = enabled;
  119556. behavior = this.camera.bouncingBehavior;
  119557. break;
  119558. case 2 /* FRAMING */:
  119559. this.camera.useFramingBehavior = enabled;
  119560. behavior = this.camera.framingBehavior;
  119561. break;
  119562. default:
  119563. behavior = null;
  119564. break;
  119565. }
  119566. if (behavior) {
  119567. this._cameraBehaviorMapping[name] = type;
  119568. if (typeof behaviorConfig === "object") {
  119569. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  119570. }
  119571. }
  119572. // post attach configuration. Some functionalities require the attached camera.
  119573. switch (type) {
  119574. case 0 /* AUTOROTATION */:
  119575. break;
  119576. case 1 /* BOUNCING */:
  119577. break;
  119578. case 2 /* FRAMING */:
  119579. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  119580. if (config.zoomOnBoundingInfo) {
  119581. behavior.zoomOnMeshHierarchy(model.rootMesh);
  119582. }
  119583. });
  119584. break;
  119585. }
  119586. };
  119587. return SceneManager;
  119588. }());
  119589. exports.SceneManager = SceneManager;
  119590. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4bUI7QUFDOW1CLGtEQUFxUztBQUNyUyxvREFBK0Q7QUFDL0Qsb0NBQWtEO0FBRWxELGlEQUFnRDtBQUNoRCx5Q0FBZ0U7QUFnQmhFO0lBa0dJLHNCQUFvQixPQUFlLEVBQVUsdUJBQStDLEVBQVUsbUJBQXdDO1FBQTlJLGl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U7WUFDVjtnQkFDSSxNQUFNO1lBQ1Y7Z0JBQ0ksTUFBTTtZQUNWO2dCQUNJLElBQUksQ0FBQyxtQkFBbUIsSUFBSSxJQUFJLENBQUMsbUJBQW1CLENBQUMsdUJBQXVCLENBQUMsR0FBRyxDQUFDLFVBQUMsS0FBSztvQkFDbkYsSUFBSSxNQUFNLENBQUMsa0JBQWtCLEVBQUU7d0JBQ1QsUUFBUyxDQUFDLG1CQUFtQixDQUFDLEtBQUssQ0FBQyxRQUFRLENBQUMsQ0FBQztxQkFDbkU7Z0JBQ0wsQ0FBQyxDQUFDLENBQUM7Z0JBQ0gsTUFBTTtTQUNiO0lBQ0wsQ0FBQztJQUNMLG1CQUFDO0FBQUQsQ0FBQyxBQTU4Q0QsSUE0OENDO0FBNThDWSxvQ0FBWSJ9
  119591. /***/ }),
  119592. /* 60 */
  119593. /***/ (function(module, exports, __webpack_require__) {
  119594. "use strict";
  119595. Object.defineProperty(exports, "__esModule", { value: true });
  119596. var environmentSerializer_1 = __webpack_require__(61);
  119597. var babylonjs_1 = __webpack_require__(0);
  119598. var texture_1 = __webpack_require__(15);
  119599. /**
  119600. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  119601. * The APIs in all labs-related classes and configuration might change.
  119602. * Once stable, lab features will be moved to the publis API and configuration object.
  119603. */
  119604. var ViewerLabs = /** @class */ (function () {
  119605. function ViewerLabs(_scene) {
  119606. this._scene = _scene;
  119607. this.environment = {
  119608. //irradiance
  119609. irradiancePolynomialCoefficients: {
  119610. x: new babylonjs_1.Vector3(0, 0, 0),
  119611. y: new babylonjs_1.Vector3(0, 0, 0),
  119612. z: new babylonjs_1.Vector3(0, 0, 0),
  119613. xx: new babylonjs_1.Vector3(0, 0, 0),
  119614. yy: new babylonjs_1.Vector3(0, 0, 0),
  119615. zz: new babylonjs_1.Vector3(0, 0, 0),
  119616. yz: new babylonjs_1.Vector3(0, 0, 0),
  119617. zx: new babylonjs_1.Vector3(0, 0, 0),
  119618. xy: new babylonjs_1.Vector3(0, 0, 0)
  119619. },
  119620. textureIntensityScale: 1.0
  119621. };
  119622. }
  119623. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  119624. var _this = this;
  119625. //@! todo: should loadEnvironment cancel any currently loading environments?
  119626. if (data instanceof ArrayBuffer) {
  119627. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  119628. if (onSuccess)
  119629. onSuccess(this.environment);
  119630. }
  119631. else if (typeof data === 'string') {
  119632. var url = this.getAssetUrl(data);
  119633. this._scene._loadFile(url, function (arrayBuffer) {
  119634. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  119635. if (onSuccess)
  119636. onSuccess(_this.environment);
  119637. }, function (progressEvent) { if (onProgress)
  119638. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  119639. if (onError) {
  119640. onError(e);
  119641. }
  119642. });
  119643. }
  119644. else {
  119645. //data assumed to be PBREnvironment object
  119646. this.environment = data;
  119647. if (onSuccess)
  119648. onSuccess(data);
  119649. }
  119650. };
  119651. /**
  119652. * Applies an `EnvironmentMapConfiguration` to the scene
  119653. * @param environmentMapConfiguration Environment map configuration to apply
  119654. */
  119655. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  119656. if (!this.environment)
  119657. return;
  119658. //set orientation
  119659. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  119660. // Add env texture to the scene.
  119661. if (this.environment.specularTexture) {
  119662. // IE crashes when disposing the old texture and setting a new one
  119663. if (!this._scene.environmentTexture) {
  119664. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  119665. }
  119666. if (this._scene.environmentTexture) {
  119667. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  119668. this._scene.environmentTexture.invertZ = true;
  119669. this._scene.environmentTexture.lodLevelInAlpha = true;
  119670. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  119671. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  119672. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  119673. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  119674. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  119675. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  119676. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  119677. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  119678. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  119679. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  119680. this._scene.environmentTexture.sphericalPolynomial = poly;
  119681. //set orientation
  119682. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  119683. }
  119684. }
  119685. };
  119686. /**
  119687. * Get an environment asset url by using the configuration if the path is not absolute.
  119688. * @param url Asset url
  119689. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  119690. */
  119691. ViewerLabs.prototype.getAssetUrl = function (url) {
  119692. var returnUrl = url;
  119693. if (url && url.toLowerCase().indexOf("//") === -1) {
  119694. if (!this.assetsRootURL) {
  119695. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  119696. return url;
  119697. }
  119698. returnUrl = this.assetsRootURL + returnUrl;
  119699. }
  119700. return returnUrl;
  119701. };
  119702. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  119703. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  119704. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  119705. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  119706. axis.normalize();
  119707. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  119708. 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]);
  119709. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  119710. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  119711. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  119712. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  119713. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  119714. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  119715. shadowLight.setDirectionToTarget(target);
  119716. };
  119717. return ViewerLabs;
  119718. }());
  119719. exports.ViewerLabs = ViewerLabs;
  119720. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBa0Y7QUFFbEYsdUNBQW1IO0FBQ25ILHFDQUF5QztBQUV6Qzs7OztHQUlHO0FBQ0g7SUFFSSxvQkFBb0IsTUFBYTtRQUFiLFdBQU0sR0FBTixNQUFNLENBQU87UUFHMUIsZ0JBQVcsR0FBbUI7WUFDakMsWUFBWTtZQUNaLGdDQUFnQyxFQUFFO2dCQUM5QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxt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DLGtCQUFNLENBQUMsaUJBQWlCLENBQUMsSUFBSSxFQUFFLE1BQU0sRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDdEQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxTQUFTLENBQUMsZUFBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxFQUFFLGVBQUcsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUUzRSxXQUFXLENBQUMsUUFBUSxDQUFDLFVBQVUsQ0FBQyxlQUFHLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFaEQsV0FBVyxDQUFDLG9CQUFvQixDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzdDLENBQUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ==
  119721. /***/ }),
  119722. /* 61 */
  119723. /***/ (function(module, exports, __webpack_require__) {
  119724. "use strict";
  119725. Object.defineProperty(exports, "__esModule", { value: true });
  119726. var babylonjs_1 = __webpack_require__(0);
  119727. var texture_1 = __webpack_require__(15);
  119728. /**
  119729. * A static class proving methods to aid parsing Spectre environment files
  119730. */
  119731. var EnvironmentDeserializer = /** @class */ (function () {
  119732. function EnvironmentDeserializer() {
  119733. }
  119734. /**
  119735. * Parses an arraybuffer into a new PBREnvironment object
  119736. * @param arrayBuffer The arraybuffer of the Spectre environment file
  119737. * @return a PBREnvironment object
  119738. */
  119739. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  119740. var environment = {
  119741. //irradiance
  119742. irradiancePolynomialCoefficients: {
  119743. x: new babylonjs_1.Vector3(0, 0, 0),
  119744. y: new babylonjs_1.Vector3(0, 0, 0),
  119745. z: new babylonjs_1.Vector3(0, 0, 0),
  119746. xx: new babylonjs_1.Vector3(0, 0, 0),
  119747. yy: new babylonjs_1.Vector3(0, 0, 0),
  119748. zz: new babylonjs_1.Vector3(0, 0, 0),
  119749. yz: new babylonjs_1.Vector3(0, 0, 0),
  119750. zx: new babylonjs_1.Vector3(0, 0, 0),
  119751. xy: new babylonjs_1.Vector3(0, 0, 0)
  119752. },
  119753. //specular
  119754. textureIntensityScale: 1.0,
  119755. };
  119756. //read .env
  119757. var littleEndian = false;
  119758. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  119759. var dataView = new DataView(arrayBuffer);
  119760. var pos = 0;
  119761. for (var i = 0; i < magicBytes.length; i++) {
  119762. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  119763. babylonjs_1.Tools.Error('Not a Spectre environment map');
  119764. }
  119765. }
  119766. var version = dataView.getUint16(pos, littleEndian);
  119767. pos += 2;
  119768. if (version !== 1) {
  119769. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  119770. }
  119771. //read json descriptor - collect characters up to null terminator
  119772. var descriptorString = '';
  119773. var charCode = 0x00;
  119774. while ((charCode = dataView.getUint8(pos++))) {
  119775. descriptorString += String.fromCharCode(charCode);
  119776. }
  119777. var descriptor = JSON.parse(descriptorString);
  119778. var payloadPos = pos;
  119779. //irradiance
  119780. switch (descriptor.irradiance.type) {
  119781. case 'irradiance_sh_coefficients_9':
  119782. //irradiance
  119783. var harmonics = descriptor.irradiance;
  119784. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  119785. //harmonics now represent radiance
  119786. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  119787. break;
  119788. default:
  119789. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  119790. }
  119791. //specular
  119792. switch (descriptor.specular.type) {
  119793. case 'cubemap_faces':
  119794. var specularDescriptor = descriptor.specular;
  119795. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  119796. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  119797. var mipmaps = specularDescriptor.mipmaps;
  119798. var imageType = specularDescriptor.imageType;
  119799. for (var l = 0; l < mipmaps.length; l++) {
  119800. var faceRanges = mipmaps[l];
  119801. specularTexture.source[l] = [];
  119802. for (var i = 0; i < 6; i++) {
  119803. var range = faceRanges[i];
  119804. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  119805. switch (imageType) {
  119806. case 'png':
  119807. //construct image element from bytes
  119808. var image = new Image();
  119809. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  119810. image.src = src;
  119811. specularTexture.source[l][i] = image;
  119812. break;
  119813. default:
  119814. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  119815. }
  119816. }
  119817. }
  119818. break;
  119819. default:
  119820. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  119821. }
  119822. return environment;
  119823. };
  119824. /**
  119825. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  119826. * L = (1/pi) * E * rho
  119827. *
  119828. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  119829. * @param harmonics Spherical harmonic coefficients (9)
  119830. */
  119831. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  119832. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  119833. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  119834. // (The pixel shader must apply albedo after texture fetches, etc).
  119835. };
  119836. /**
  119837. * Convert spherical harmonics to spherical polynomial coefficients
  119838. * @param harmonics Spherical harmonic coefficients (9)
  119839. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  119840. */
  119841. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  119842. var rPi = 1 / Math.PI;
  119843. //x
  119844. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  119845. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  119846. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  119847. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  119848. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  119849. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  119850. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  119851. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  119852. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  119853. //xx
  119854. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  119855. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  119856. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  119857. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  119858. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  119859. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  119860. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  119861. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  119862. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  119863. //yz
  119864. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  119865. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  119866. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  119867. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  119868. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  119869. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  119870. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  119871. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  119872. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  119873. };
  119874. /**
  119875. * Multiplies harmonic coefficients in place
  119876. * @param harmonics Spherical harmonic coefficients (9)
  119877. * @param scaleFactor Value to multiply by
  119878. */
  119879. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  119880. harmonics.l00[0] *= scaleFactor;
  119881. harmonics.l00[1] *= scaleFactor;
  119882. harmonics.l00[2] *= scaleFactor;
  119883. harmonics.l1_1[0] *= scaleFactor;
  119884. harmonics.l1_1[1] *= scaleFactor;
  119885. harmonics.l1_1[2] *= scaleFactor;
  119886. harmonics.l10[0] *= scaleFactor;
  119887. harmonics.l10[1] *= scaleFactor;
  119888. harmonics.l10[2] *= scaleFactor;
  119889. harmonics.l11[0] *= scaleFactor;
  119890. harmonics.l11[1] *= scaleFactor;
  119891. harmonics.l11[2] *= scaleFactor;
  119892. harmonics.l2_2[0] *= scaleFactor;
  119893. harmonics.l2_2[1] *= scaleFactor;
  119894. harmonics.l2_2[2] *= scaleFactor;
  119895. harmonics.l2_1[0] *= scaleFactor;
  119896. harmonics.l2_1[1] *= scaleFactor;
  119897. harmonics.l2_1[2] *= scaleFactor;
  119898. harmonics.l20[0] *= scaleFactor;
  119899. harmonics.l20[1] *= scaleFactor;
  119900. harmonics.l20[2] *= scaleFactor;
  119901. harmonics.l21[0] *= scaleFactor;
  119902. harmonics.l21[1] *= scaleFactor;
  119903. harmonics.l21[2] *= scaleFactor;
  119904. harmonics.l22[0] *= scaleFactor;
  119905. harmonics.l22[1] *= scaleFactor;
  119906. harmonics.l22[2] *= scaleFactor;
  119907. };
  119908. return EnvironmentDeserializer;
  119909. }());
  119910. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  119911. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2xhYnMvZW52aXJvbm1lbnRTZXJpYWxpemVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTJDO0FBQzNDLHFDQUFnRTtBQW1IaEU7O0dBRUc7QUFDSDtJQUFBO0lBcU5BLENBQUM7SUFuTkc7Ozs7T0FJRztJQUNXLDZCQUFLLEd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UFTLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNqQyxTQUFTLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNqQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9
  119912. /***/ }),
  119913. /* 62 */
  119914. /***/ (function(module, exports, __webpack_require__) {
  119915. "use strict";
  119916. Object.defineProperty(exports, "__esModule", { value: true });
  119917. var babylonjs_1 = __webpack_require__(0);
  119918. /**
  119919. * A custom upgrade-oriented function configuration for the scene optimizer.
  119920. *
  119921. * @param viewer the viewer to optimize
  119922. */
  119923. function extendedUpgrade(sceneManager) {
  119924. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  119925. // if (!this.Scene.BackgroundHelper) {
  119926. // this.Scene.EngineScene.autoClear = false;
  119927. // this.Scene.BackgroundHelper = true;
  119928. // Would require a dedicated clear color;
  119929. // return false;
  119930. // }
  119931. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  119932. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  119933. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  119934. return false;
  119935. }
  119936. if (!sceneManager.scene.postProcessesEnabled) {
  119937. sceneManager.scene.postProcessesEnabled = true;
  119938. return false;
  119939. }
  119940. if (!sceneManager.groundEnabled) {
  119941. sceneManager.groundEnabled = true;
  119942. return false;
  119943. }
  119944. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  119945. sceneManager.fxaaEnabled = true;
  119946. return false;
  119947. }
  119948. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  119949. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  119950. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  119951. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  119952. return false;
  119953. }
  119954. if (!sceneManager.processShadows) {
  119955. sceneManager.processShadows = true;
  119956. return false;
  119957. }
  119958. if (defaultPipeline && !sceneManager.bloomEnabled) {
  119959. sceneManager.bloomEnabled = true;
  119960. return false;
  119961. }
  119962. if (!sceneManager.groundMirrorEnabled) {
  119963. sceneManager.groundMirrorEnabled = true;
  119964. return false;
  119965. }
  119966. return true;
  119967. }
  119968. exports.extendedUpgrade = extendedUpgrade;
  119969. /**
  119970. * A custom degrade-oriented function configuration for the scene optimizer.
  119971. *
  119972. * @param viewer the viewer to optimize
  119973. */
  119974. function extendedDegrade(sceneManager) {
  119975. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  119976. if (sceneManager.groundMirrorEnabled) {
  119977. sceneManager.groundMirrorEnabled = false;
  119978. return false;
  119979. }
  119980. if (defaultPipeline && sceneManager.bloomEnabled) {
  119981. sceneManager.bloomEnabled = false;
  119982. return false;
  119983. }
  119984. if (sceneManager.processShadows) {
  119985. sceneManager.processShadows = false;
  119986. return false;
  119987. }
  119988. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  119989. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  119990. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  119991. return false;
  119992. }
  119993. if (defaultPipeline && sceneManager.fxaaEnabled) {
  119994. sceneManager.fxaaEnabled = false;
  119995. return false;
  119996. }
  119997. if (sceneManager.groundEnabled) {
  119998. sceneManager.groundEnabled = false;
  119999. return false;
  120000. }
  120001. if (sceneManager.scene.postProcessesEnabled) {
  120002. sceneManager.scene.postProcessesEnabled = false;
  120003. return false;
  120004. }
  120005. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  120006. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  120007. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  120008. return false;
  120009. }
  120010. // if (this.Scene.BackgroundHelper) {
  120011. // this.Scene.EngineScene.autoClear = true;
  120012. // this.Scene.BackgroundHelper = false;
  120013. // Would require a dedicated clear color;
  120014. // return false;
  120015. // }
  120016. return true;
  120017. }
  120018. exports.extendedDegrade = extendedDegrade;
  120019. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUF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RQUM1QixZQUFZLENBQUMsYUFBYSxHQUFHLEtBQUssQ0FBQztRQUNuQyxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxvQkFBb0IsRUFBRTtRQUN6QyxZQUFZLENBQUMsS0FBSyxDQUFDLG9CQUFvQixHQUFHLEtBQUssQ0FBQztRQUNoRCxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxTQUFTLEVBQUUsQ0FBQyx1QkFBdUIsRUFBRSxHQUFHLElBQUksRUFBRTtRQUNqRSxJQUFJLE9BQU8sR0FBRyxrQkFBTSxDQUFDLEtBQUssQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  120020. /***/ }),
  120021. /* 63 */
  120022. /***/ (function(module, exports, __webpack_require__) {
  120023. "use strict";
  120024. Object.defineProperty(exports, "__esModule", { value: true });
  120025. var babylonjs_1 = __webpack_require__(0);
  120026. var helper_1 = __webpack_require__(1);
  120027. var Handlebars = __webpack_require__(17);
  120028. var eventManager_1 = __webpack_require__(64);
  120029. var _1 = __webpack_require__(1);
  120030. /**
  120031. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  120032. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  120033. */
  120034. var TemplateManager = /** @class */ (function () {
  120035. function TemplateManager(containerElement) {
  120036. this.containerElement = containerElement;
  120037. this.templates = {};
  120038. this.onTemplateInit = new babylonjs_1.Observable();
  120039. this.onTemplateLoaded = new babylonjs_1.Observable();
  120040. this.onTemplateStateChange = new babylonjs_1.Observable();
  120041. this.onAllLoaded = new babylonjs_1.Observable();
  120042. this.onEventTriggered = new babylonjs_1.Observable();
  120043. this.eventManager = new eventManager_1.EventManager(this);
  120044. }
  120045. /**
  120046. * Initialize the template(s) for the viewer. Called bay the Viewer class
  120047. * @param templates the templates to be used to initialize the main template
  120048. */
  120049. TemplateManager.prototype.initTemplate = function (templates) {
  120050. var _this = this;
  120051. var internalInit = function (dependencyMap, name, parentTemplate) {
  120052. //init template
  120053. var template = _this.templates[name];
  120054. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  120055. return internalInit(dependencyMap[childName], childName, template);
  120056. });
  120057. // register the observers
  120058. //template.onLoaded.add(() => {
  120059. var addToParent = function () {
  120060. var lastElements = parentTemplate && parentTemplate.parent.querySelectorAll(helper_1.camelToKebab(name));
  120061. var containingElement = (lastElements && lastElements.length && lastElements.item(lastElements.length - 1)) || _this.containerElement;
  120062. template.appendTo(containingElement);
  120063. _this._checkLoadedState();
  120064. };
  120065. if (parentTemplate && !parentTemplate.parent) {
  120066. parentTemplate.onAppended.add(function () {
  120067. addToParent();
  120068. });
  120069. }
  120070. else {
  120071. addToParent();
  120072. }
  120073. //});
  120074. return template;
  120075. };
  120076. //build the html tree
  120077. return this._buildHTMLTree(templates).then(function (htmlTree) {
  120078. if (_this.templates['main']) {
  120079. internalInit(htmlTree, 'main');
  120080. }
  120081. else {
  120082. _this._checkLoadedState();
  120083. }
  120084. return;
  120085. });
  120086. };
  120087. /**
  120088. *
  120089. * This function will create a simple map with child-dependencies of the template html tree.
  120090. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  120091. * It is expected that the main template will be called main!
  120092. *
  120093. * @param templates
  120094. */
  120095. TemplateManager.prototype._buildHTMLTree = function (templates) {
  120096. var _this = this;
  120097. var promises = Object.keys(templates).map(function (name) {
  120098. // if the template was overridden
  120099. if (!templates[name])
  120100. return Promise.resolve(false);
  120101. // else - we have a template, let's do our job!
  120102. var template = new Template(name, templates[name]);
  120103. template.onLoaded.add(function () {
  120104. _this.onTemplateLoaded.notifyObservers(template);
  120105. });
  120106. template.onStateChange.add(function () {
  120107. _this.onTemplateStateChange.notifyObservers(template);
  120108. });
  120109. _this.onTemplateInit.notifyObservers(template);
  120110. // make sure the global onEventTriggered is called as well
  120111. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  120112. _this.templates[name] = template;
  120113. return template.initPromise;
  120114. });
  120115. return Promise.all(promises).then(function () {
  120116. var templateStructure = {};
  120117. // now iterate through all templates and check for children:
  120118. var buildTree = function (parentObject, name) {
  120119. _this.templates[name].isInHtmlTree = true;
  120120. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  120121. childNodes.forEach(function (element) {
  120122. parentObject[element] = {};
  120123. buildTree(parentObject[element], element);
  120124. });
  120125. };
  120126. if (_this.templates['main']) {
  120127. buildTree(templateStructure, "main");
  120128. }
  120129. return templateStructure;
  120130. });
  120131. };
  120132. /**
  120133. * Get the canvas in the template tree.
  120134. * There must be one and only one canvas inthe template.
  120135. */
  120136. TemplateManager.prototype.getCanvas = function () {
  120137. return this.containerElement.querySelector('canvas');
  120138. };
  120139. /**
  120140. * Get a specific template from the template tree
  120141. * @param name the name of the template to load
  120142. */
  120143. TemplateManager.prototype.getTemplate = function (name) {
  120144. return this.templates[name];
  120145. };
  120146. TemplateManager.prototype._checkLoadedState = function () {
  120147. var _this = this;
  120148. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  120149. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  120150. });
  120151. if (done) {
  120152. this.onAllLoaded.notifyObservers(this);
  120153. }
  120154. };
  120155. /**
  120156. * Dispose the template manager
  120157. */
  120158. TemplateManager.prototype.dispose = function () {
  120159. var _this = this;
  120160. // dispose all templates
  120161. Object.keys(this.templates).forEach(function (template) {
  120162. _this.templates[template].dispose();
  120163. });
  120164. this.templates = {};
  120165. this.eventManager.dispose();
  120166. this.onTemplateInit.clear();
  120167. this.onAllLoaded.clear();
  120168. this.onEventTriggered.clear();
  120169. this.onTemplateLoaded.clear();
  120170. this.onTemplateStateChange.clear();
  120171. };
  120172. return TemplateManager;
  120173. }());
  120174. exports.TemplateManager = TemplateManager;
  120175. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  120176. Handlebars.registerHelper('eachInMap', function (map, block) {
  120177. var out = '';
  120178. Object.keys(map).map(function (prop) {
  120179. var data = map[prop];
  120180. if (typeof data === 'object') {
  120181. data.id = data.id || prop;
  120182. out += block.fn(data);
  120183. }
  120184. else {
  120185. out += block.fn({ id: prop, value: data });
  120186. }
  120187. });
  120188. return out;
  120189. });
  120190. Handlebars.registerHelper('add', function (a, b) {
  120191. var out = a + b;
  120192. return out;
  120193. });
  120194. Handlebars.registerHelper('eq', function (a, b) {
  120195. var out = (a == b);
  120196. return out;
  120197. });
  120198. Handlebars.registerHelper('or', function (a, b) {
  120199. var out = a || b;
  120200. return out;
  120201. });
  120202. Handlebars.registerHelper('not', function (a) {
  120203. var out = !a;
  120204. return out;
  120205. });
  120206. Handlebars.registerHelper('count', function (map) {
  120207. return map.length;
  120208. });
  120209. Handlebars.registerHelper('gt', function (a, b) {
  120210. var out = a > b;
  120211. return out;
  120212. });
  120213. /**
  120214. * This class represents a single template in the viewer's template tree.
  120215. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  120216. * A template is injected using the template manager in the correct position.
  120217. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  120218. *
  120219. * For further information please refer to the documentation page, https://doc.babylonjs.com
  120220. */
  120221. var Template = /** @class */ (function () {
  120222. function Template(name, _configuration) {
  120223. var _this = this;
  120224. this.name = name;
  120225. this._configuration = _configuration;
  120226. this.onLoaded = new babylonjs_1.Observable();
  120227. this.onAppended = new babylonjs_1.Observable();
  120228. this.onStateChange = new babylonjs_1.Observable();
  120229. this.onEventTriggered = new babylonjs_1.Observable();
  120230. this.onParamsUpdated = new babylonjs_1.Observable();
  120231. this.onHTMLRendered = new babylonjs_1.Observable();
  120232. this.loadRequests = [];
  120233. this.isLoaded = false;
  120234. this.isShown = false;
  120235. this.isInHtmlTree = false;
  120236. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  120237. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  120238. if (htmlTemplate) {
  120239. _this._htmlTemplate = htmlTemplate;
  120240. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  120241. var config = _this._configuration.params || {};
  120242. _this._rawHtml = compiledTemplate(config);
  120243. try {
  120244. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  120245. }
  120246. catch (e) {
  120247. var test = document.createElement(_this.name);
  120248. test.innerHTML = _this._rawHtml;
  120249. _this._fragment = test;
  120250. }
  120251. _this.isLoaded = true;
  120252. _this.isShown = true;
  120253. _this.onLoaded.notifyObservers(_this);
  120254. }
  120255. return _this;
  120256. });
  120257. }
  120258. /**
  120259. * Some templates have parameters (like background color for example).
  120260. * The parameters are provided to Handlebars which in turn generates the template.
  120261. * This function will update the template with the new parameters
  120262. *
  120263. * Note that when updating parameters the events will be registered again (after being cleared).
  120264. *
  120265. * @param params the new template parameters
  120266. */
  120267. Template.prototype.updateParams = function (params, append) {
  120268. if (append === void 0) { append = true; }
  120269. if (append) {
  120270. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  120271. }
  120272. else {
  120273. this._configuration.params = params;
  120274. }
  120275. // update the template
  120276. if (this.isLoaded) {
  120277. // this.dispose();
  120278. }
  120279. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  120280. var config = this._configuration.params || {};
  120281. this._rawHtml = compiledTemplate(config);
  120282. try {
  120283. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  120284. }
  120285. catch (e) {
  120286. var test = document.createElement(this.name);
  120287. test.innerHTML = this._rawHtml;
  120288. this._fragment = test;
  120289. }
  120290. if (this.parent) {
  120291. this.appendTo(this.parent, true);
  120292. }
  120293. };
  120294. Template.prototype.redraw = function () {
  120295. this.updateParams({});
  120296. };
  120297. Object.defineProperty(Template.prototype, "configuration", {
  120298. /**
  120299. * Get the template'S configuration
  120300. */
  120301. get: function () {
  120302. return this._configuration;
  120303. },
  120304. enumerable: true,
  120305. configurable: true
  120306. });
  120307. /**
  120308. * A template can be a parent element for other templates or HTML elements.
  120309. * This function will deliver all child HTML elements of this template.
  120310. */
  120311. Template.prototype.getChildElements = function () {
  120312. var childrenArray = [];
  120313. //Edge and IE don't support frage,ent.children
  120314. var children = this._fragment && this._fragment.children;
  120315. if (!this._fragment) {
  120316. var fragment = this.parent.querySelector(this.name);
  120317. if (fragment) {
  120318. children = fragment.querySelectorAll('*');
  120319. }
  120320. }
  120321. if (!children) {
  120322. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  120323. children = this._fragment.querySelectorAll('*');
  120324. }
  120325. for (var i = 0; i < children.length; ++i) {
  120326. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  120327. }
  120328. return childrenArray;
  120329. };
  120330. /**
  120331. * Appending the template to a parent HTML element.
  120332. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  120333. * @param parent the parent to which the template is added
  120334. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  120335. */
  120336. Template.prototype.appendTo = function (parent, forceRemove) {
  120337. var _this = this;
  120338. if (this.parent) {
  120339. if (forceRemove && this._addedFragment) {
  120340. /*let fragement = this.parent.querySelector(this.name)
  120341. if (fragement)
  120342. this.parent.removeChild(fragement);*/
  120343. this.parent.innerHTML = '';
  120344. }
  120345. else {
  120346. return;
  120347. }
  120348. }
  120349. this.parent = parent;
  120350. if (this._configuration.id) {
  120351. this.parent.id = this._configuration.id;
  120352. }
  120353. if (this._fragment) {
  120354. this.parent.appendChild(this._fragment);
  120355. this._addedFragment = this._fragment;
  120356. }
  120357. else {
  120358. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  120359. }
  120360. this.onHTMLRendered.notifyObservers(this);
  120361. // appended only one frame after.
  120362. setTimeout(function () {
  120363. _this._registerEvents();
  120364. _this.onAppended.notifyObservers(_this);
  120365. });
  120366. };
  120367. /**
  120368. * Show the template using the provided visibilityFunction, or natively using display: flex.
  120369. * The provided function returns a promise that should be fullfilled when the element is shown.
  120370. * Since it is a promise async operations are more than possible.
  120371. * See the default viewer for an opacity example.
  120372. * @param visibilityFunction The function to execute to show the template.
  120373. */
  120374. Template.prototype.show = function (visibilityFunction) {
  120375. var _this = this;
  120376. if (this._isHiding)
  120377. return Promise.resolve(this);
  120378. return Promise.resolve().then(function () {
  120379. _this._isShowing = true;
  120380. if (visibilityFunction) {
  120381. return visibilityFunction(_this);
  120382. }
  120383. else {
  120384. // flex? box? should this be configurable easier than the visibilityFunction?
  120385. _this.parent.style.display = 'flex';
  120386. // support old browsers with no flex:
  120387. if (_this.parent.style.display !== 'flex') {
  120388. _this.parent.style.display = '';
  120389. }
  120390. return _this;
  120391. }
  120392. }).then(function () {
  120393. _this.isShown = true;
  120394. _this._isShowing = false;
  120395. _this.onStateChange.notifyObservers(_this);
  120396. return _this;
  120397. });
  120398. };
  120399. /**
  120400. * Hide the template using the provided visibilityFunction, or natively using display: none.
  120401. * The provided function returns a promise that should be fullfilled when the element is hidden.
  120402. * Since it is a promise async operations are more than possible.
  120403. * See the default viewer for an opacity example.
  120404. * @param visibilityFunction The function to execute to show the template.
  120405. */
  120406. Template.prototype.hide = function (visibilityFunction) {
  120407. var _this = this;
  120408. if (this._isShowing)
  120409. return Promise.resolve(this);
  120410. return Promise.resolve().then(function () {
  120411. _this._isHiding = true;
  120412. if (visibilityFunction) {
  120413. return visibilityFunction(_this);
  120414. }
  120415. else {
  120416. // flex? box? should this be configurable easier than the visibilityFunction?
  120417. _this.parent.style.display = 'none';
  120418. return _this;
  120419. }
  120420. }).then(function () {
  120421. _this.isShown = false;
  120422. _this._isHiding = false;
  120423. _this.onStateChange.notifyObservers(_this);
  120424. return _this;
  120425. });
  120426. };
  120427. /**
  120428. * Dispose this template
  120429. */
  120430. Template.prototype.dispose = function () {
  120431. this.onAppended.clear();
  120432. this.onEventTriggered.clear();
  120433. this.onLoaded.clear();
  120434. this.onStateChange.clear();
  120435. this.isLoaded = false;
  120436. // remove from parent
  120437. try {
  120438. this.parent.removeChild(this._fragment);
  120439. }
  120440. catch (e) {
  120441. //noop
  120442. }
  120443. this.loadRequests.forEach(function (request) {
  120444. request.abort();
  120445. });
  120446. if (this._registeredEvents) {
  120447. this._registeredEvents.forEach(function (evt) {
  120448. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  120449. });
  120450. }
  120451. delete this._fragment;
  120452. };
  120453. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  120454. var _this = this;
  120455. if (!templateConfig) {
  120456. return Promise.reject('No templateConfig provided');
  120457. }
  120458. else if (templateConfig.html && !templateConfig.location) {
  120459. return Promise.resolve(templateConfig.html);
  120460. }
  120461. else {
  120462. var location_1 = this._getTemplateLocation(templateConfig);
  120463. if (helper_1.isUrl(location_1)) {
  120464. return new Promise(function (resolve, reject) {
  120465. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  120466. resolve(data);
  120467. }, undefined, undefined, false, function (request, error) {
  120468. reject(error);
  120469. });
  120470. _this.loadRequests.push(fileRequest);
  120471. });
  120472. }
  120473. else {
  120474. location_1 = location_1.replace('#', '');
  120475. var element = document.getElementById(location_1);
  120476. if (element) {
  120477. return Promise.resolve(element.innerHTML);
  120478. }
  120479. else {
  120480. return Promise.reject('Template ID not found');
  120481. }
  120482. }
  120483. }
  120484. };
  120485. Template.prototype._registerEvents = function () {
  120486. var _this = this;
  120487. this._registeredEvents = this._registeredEvents || [];
  120488. if (this._registeredEvents.length) {
  120489. // first remove the registered events
  120490. this._registeredEvents.forEach(function (evt) {
  120491. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  120492. });
  120493. }
  120494. if (this._configuration.events) {
  120495. var _loop_1 = function (eventName) {
  120496. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  120497. var functionToFire_1 = function (selector, event) {
  120498. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  120499. };
  120500. // if boolean, set the parent as the event listener
  120501. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  120502. var selector = this_1.parent.id;
  120503. if (selector) {
  120504. selector = '#' + selector;
  120505. }
  120506. else {
  120507. selector = this_1.parent.tagName;
  120508. }
  120509. var binding = functionToFire_1.bind(this_1, selector);
  120510. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  120511. this_1._registeredEvents.push({
  120512. htmlElement: this_1.parent,
  120513. eventName: eventName,
  120514. function: binding
  120515. });
  120516. }
  120517. else if (typeof this_1._configuration.events[eventName] === 'object') {
  120518. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  120519. // strict null checl is working incorrectly, must override:
  120520. var event_1 = this_1._configuration.events[eventName] || {};
  120521. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  120522. var htmlElement = _this.parent.querySelector(selector);
  120523. if (!htmlElement) {
  120524. // backcompat, fallback to id
  120525. if (selector && selector.indexOf('#') !== 0) {
  120526. selector = '#' + selector;
  120527. }
  120528. try {
  120529. htmlElement = _this.parent.querySelector(selector);
  120530. }
  120531. catch (e) { }
  120532. }
  120533. if (htmlElement) {
  120534. var binding = functionToFire_1.bind(_this, selector);
  120535. htmlElement.addEventListener(eventName, binding, false);
  120536. _this._registeredEvents.push({
  120537. htmlElement: htmlElement,
  120538. eventName: eventName,
  120539. function: binding
  120540. });
  120541. }
  120542. });
  120543. }
  120544. }
  120545. };
  120546. var this_1 = this;
  120547. for (var eventName in this._configuration.events) {
  120548. _loop_1(eventName);
  120549. }
  120550. }
  120551. };
  120552. Template.prototype._getTemplateLocation = function (templateConfig) {
  120553. if (!templateConfig || typeof templateConfig === 'string') {
  120554. return templateConfig;
  120555. }
  120556. else {
  120557. return templateConfig.location;
  120558. }
  120559. };
  120560. return Template;
  120561. }());
  120562. exports.Template = Template;
  120563. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvdGVtcGxhdGVNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsdUNBQTREO0FBQzVELG9DQUE4RDtBQUU5RCx1REFBeUQ7QUFDekQsK0NBQThDO0FBRTlDLCtCQUF1QztBQVl2Qzs7O0dBR0c7QUFDSDtJQThCSSx5QkFBbUIsZ0JBQTZCO1FBQTdCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQUM1QyxJQUFJLENBQUMsU0FBUyxHQUFHLEVBQUUsQ0FBQztRQUVwQixJQUFJLENBQUMsY0FBYyxHQUFHLElBQUksc0JBQVUsRUFBWSxDQUFDO1FBQ2pELElBQUksQ0FBQyxnQkFBZ0IsR0FBRyxJQUFJLHNCQUFVLEVBQVksQ0FBQztRQUNuRCxJQUFJLENBQUMscUJBQXFCLEdBQUcsSUFBSSxzQkFBVSxFQUFZLENBQUM7UUFDeEQsSUFBSSxDQUFDLFdBQVcsR0FBRyxJQUFJLHNCQUFVLEVBQW1CLENBQUM7UUFDckQsSUFBSSxDQUFDLGdCQUFnQixHQUFHLElBQUksc0JBQVUsRUFBaUIsQ0FBQztR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SSxDQUFDLEtBQUksRUFBRSxRQUFRLENBQUMsQ0FBQztnQ0FDbEQsV0FBVyxDQUFDLGdCQUFnQixDQUFDLFNBQVMsRUFBRSxPQUFPLEVBQUUsS0FBSyxDQUFDLENBQUM7Z0NBQ3hELEtBQUksQ0FBQyxpQkFBaUIsQ0FBQyxJQUFJLENBQUM7b0NBQ3hCLFdBQVcsRUFBRSxXQUFXO29DQUN4QixTQUFTLEVBQUUsU0FBUztvQ0FDcEIsUUFBUSxFQUFFLE9BQU87aUNBQ3BCLENBQUMsQ0FBQzs2QkFDTjt3QkFDTCxDQUFDLENBQUMsQ0FBQztxQkFDTjtpQkFDSjtZQUNMLENBQUM7O1lBaERELEtBQUssSUFBSSxTQUFTLElBQUksSUFBSSxDQUFDLGNBQWMsQ0FBQyxNQUFNO3dCQUF2QyxTQUFTO2FBZ0RqQjtTQUNKO0lBQ0wsQ0FBQztJQUVPLHVDQUFvQixHQUE1QixVQUE2QixjQUFjO1FBQ3ZDLElBQUksQ0FBQyxjQUFjLElBQUksT0FBTyxjQUFjLEtBQUssUUFBUSxFQUFFO1lBQ3ZELE9BQU8sY0FBYyxDQUFDO1NBQ3pCO2FBQU07WUFDSCxPQUFPLGNBQWMsQ0FBQyxRQUFRLENBQUM7U0FDbEM7SUFDTCxDQUFDO0lBQ0wsZUFBQztBQUFELENBQUMsQUFsWUQsSUFrWUM7QUFsWVksNEJBQVEifQ==
  120564. /***/ }),
  120565. /* 64 */
  120566. /***/ (function(module, exports, __webpack_require__) {
  120567. "use strict";
  120568. Object.defineProperty(exports, "__esModule", { value: true });
  120569. /**
  120570. * The EventManager is in charge of registering user interctions with the viewer.
  120571. * It is used in the TemplateManager
  120572. */
  120573. var EventManager = /** @class */ (function () {
  120574. function EventManager(_templateManager) {
  120575. var _this = this;
  120576. this._templateManager = _templateManager;
  120577. this._callbacksContainer = {};
  120578. this._templateManager.onEventTriggered.add(function (eventData) {
  120579. _this._eventTriggered(eventData);
  120580. });
  120581. }
  120582. /**
  120583. * Register a new callback to a specific template.
  120584. * The best example for the usage can be found in the DefaultViewer
  120585. *
  120586. * @param templateName the templateName to register the event to
  120587. * @param callback The callback to be executed
  120588. * @param eventType the type of event to register
  120589. * @param selector an optional selector. if not defined the parent object in the template will be selected
  120590. */
  120591. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  120592. if (!this._callbacksContainer[templateName]) {
  120593. this._callbacksContainer[templateName] = [];
  120594. }
  120595. this._callbacksContainer[templateName].push({
  120596. eventType: eventType,
  120597. callback: callback,
  120598. selector: selector
  120599. });
  120600. };
  120601. /**
  120602. * This will remove a registered event from the defined template.
  120603. * Each one of the variables apart from the template name are optional, but one must be provided.
  120604. *
  120605. * @param templateName the templateName
  120606. * @param callback the callback to remove (optional)
  120607. * @param eventType the event type to remove (optional)
  120608. * @param selector the selector from which to remove the event (optional)
  120609. */
  120610. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  120611. var callbackDefs = this._callbacksContainer[templateName] || [];
  120612. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  120613. };
  120614. EventManager.prototype._eventTriggered = function (data) {
  120615. var templateName = data.template.name;
  120616. var eventType = data.event.type;
  120617. var selector = data.selector;
  120618. var callbackDefs = this._callbacksContainer[templateName] || [];
  120619. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  120620. callbackDef.callback(data);
  120621. });
  120622. };
  120623. /**
  120624. * Dispose the event manager
  120625. */
  120626. EventManager.prototype.dispose = function () {
  120627. this._callbacksContainer = {};
  120628. };
  120629. return EventManager;
  120630. }());
  120631. exports.EventManager = EventManager;
  120632. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlU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FDO0lBRUQ7O09BRUc7SUFDSSw4QkFBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztJQUNsQyxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOURELElBOERDO0FBOURZLG9DQUFZIn0=
  120633. /***/ }),
  120634. /* 65 */
  120635. /***/ (function(module, exports, __webpack_require__) {
  120636. "use strict";
  120637. var __extends = (this && this.__extends) || (function () {
  120638. var extendStatics = Object.setPrototypeOf ||
  120639. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  120640. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  120641. return function (d, b) {
  120642. extendStatics(d, b);
  120643. function __() { this.constructor = d; }
  120644. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  120645. };
  120646. })();
  120647. Object.defineProperty(exports, "__esModule", { value: true });
  120648. var viewerTemplatePlugin_1 = __webpack_require__(18);
  120649. var HDButtonPlugin = /** @class */ (function (_super) {
  120650. __extends(HDButtonPlugin, _super);
  120651. function HDButtonPlugin(_viewer) {
  120652. var _this = _super.call(this) || this;
  120653. _this._viewer = _viewer;
  120654. _this._buttonClass = "hd-button";
  120655. _this._htmlTemplate = "\n{{#unless hideHd}}\n<style>\n.hd-icon:after {\n font-size: 16px;\n content: \"\\F765\";\n}\n\n.hd-toggled span.hd-icon:after {\n content: \"\\F766\";\n}\n</style>\n<button class=\"hd-button\" title=\"{{text.hdButton}}\">\n <span class=\"icon hd-icon\"></span>\n </button>\n {{/unless}}\n";
  120656. return _this;
  120657. }
  120658. HDButtonPlugin.prototype.onEvent = function (event) {
  120659. var button = event.template.parent.querySelector(".hd-button");
  120660. if (button) {
  120661. button.classList.contains("hd-toggled") ? button.classList.remove("hd-toggled") : button.classList.add("hd-toggled");
  120662. }
  120663. this._viewer.toggleHD();
  120664. };
  120665. return HDButtonPlugin;
  120666. }(viewerTemplatePlugin_1.A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MifQ==
  120669. /***/ }),
  120670. /* 66 */
  120671. /***/ (function(module, exports, __webpack_require__) {
  120672. /*!
  120673. * PEP v0.4.3 | https://github.com/jquery/PEP
  120674. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  120675. */
  120676. (function (global, factory) {
  120677. true ? module.exports = factory() :
  120678. typeof define === 'function' && define.amd ? define(factory) :
  120679. (global.PointerEventsPolyfill = factory());
  120680. }(this, function () { 'use strict';
  120681. /**
  120682. * This is the constructor for new PointerEvents.
  120683. *
  120684. * New Pointer Events must be given a type, and an optional dictionary of
  120685. * initialization properties.
  120686. *
  120687. * Due to certain platform requirements, events returned from the constructor
  120688. * identify as MouseEvents.
  120689. *
  120690. * @constructor
  120691. * @param {String} inType The type of the event to create.
  120692. * @param {Object} [inDict] An optional dictionary of initial event properties.
  120693. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  120694. */
  120695. var MOUSE_PROPS = [
  120696. 'bubbles',
  120697. 'cancelable',
  120698. 'view',
  120699. 'detail',
  120700. 'screenX',
  120701. 'screenY',
  120702. 'clientX',
  120703. 'clientY',
  120704. 'ctrlKey',
  120705. 'altKey',
  120706. 'shiftKey',
  120707. 'metaKey',
  120708. 'button',
  120709. 'relatedTarget',
  120710. 'pageX',
  120711. 'pageY'
  120712. ];
  120713. var MOUSE_DEFAULTS = [
  120714. false,
  120715. false,
  120716. null,
  120717. null,
  120718. 0,
  120719. 0,
  120720. 0,
  120721. 0,
  120722. false,
  120723. false,
  120724. false,
  120725. false,
  120726. 0,
  120727. null,
  120728. 0,
  120729. 0
  120730. ];
  120731. function PointerEvent(inType, inDict) {
  120732. inDict = inDict || Object.create(null);
  120733. var e = document.createEvent('Event');
  120734. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  120735. // define inherited MouseEvent properties
  120736. // skip bubbles and cancelable since they're set above in initEvent()
  120737. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  120738. p = MOUSE_PROPS[i];
  120739. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  120740. }
  120741. e.buttons = inDict.buttons || 0;
  120742. // Spec requires that pointers without pressure specified use 0.5 for down
  120743. // state and 0 for up state.
  120744. var pressure = 0;
  120745. if (inDict.pressure && e.buttons) {
  120746. pressure = inDict.pressure;
  120747. } else {
  120748. pressure = e.buttons ? 0.5 : 0;
  120749. }
  120750. // add x/y properties aliased to clientX/Y
  120751. e.x = e.clientX;
  120752. e.y = e.clientY;
  120753. // define the properties of the PointerEvent interface
  120754. e.pointerId = inDict.pointerId || 0;
  120755. e.width = inDict.width || 0;
  120756. e.height = inDict.height || 0;
  120757. e.pressure = pressure;
  120758. e.tiltX = inDict.tiltX || 0;
  120759. e.tiltY = inDict.tiltY || 0;
  120760. e.twist = inDict.twist || 0;
  120761. e.tangentialPressure = inDict.tangentialPressure || 0;
  120762. e.pointerType = inDict.pointerType || '';
  120763. e.hwTimestamp = inDict.hwTimestamp || 0;
  120764. e.isPrimary = inDict.isPrimary || false;
  120765. return e;
  120766. }
  120767. /**
  120768. * This module implements a map of pointer states
  120769. */
  120770. var USE_MAP = window.Map && window.Map.prototype.forEach;
  120771. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  120772. function SparseArrayMap() {
  120773. this.array = [];
  120774. this.size = 0;
  120775. }
  120776. SparseArrayMap.prototype = {
  120777. set: function(k, v) {
  120778. if (v === undefined) {
  120779. return this.delete(k);
  120780. }
  120781. if (!this.has(k)) {
  120782. this.size++;
  120783. }
  120784. this.array[k] = v;
  120785. },
  120786. has: function(k) {
  120787. return this.array[k] !== undefined;
  120788. },
  120789. delete: function(k) {
  120790. if (this.has(k)) {
  120791. delete this.array[k];
  120792. this.size--;
  120793. }
  120794. },
  120795. get: function(k) {
  120796. return this.array[k];
  120797. },
  120798. clear: function() {
  120799. this.array.length = 0;
  120800. this.size = 0;
  120801. },
  120802. // return value, key, map
  120803. forEach: function(callback, thisArg) {
  120804. return this.array.forEach(function(v, k) {
  120805. callback.call(thisArg, v, k, this);
  120806. }, this);
  120807. }
  120808. };
  120809. var CLONE_PROPS = [
  120810. // MouseEvent
  120811. 'bubbles',
  120812. 'cancelable',
  120813. 'view',
  120814. 'detail',
  120815. 'screenX',
  120816. 'screenY',
  120817. 'clientX',
  120818. 'clientY',
  120819. 'ctrlKey',
  120820. 'altKey',
  120821. 'shiftKey',
  120822. 'metaKey',
  120823. 'button',
  120824. 'relatedTarget',
  120825. // DOM Level 3
  120826. 'buttons',
  120827. // PointerEvent
  120828. 'pointerId',
  120829. 'width',
  120830. 'height',
  120831. 'pressure',
  120832. 'tiltX',
  120833. 'tiltY',
  120834. 'pointerType',
  120835. 'hwTimestamp',
  120836. 'isPrimary',
  120837. // event instance
  120838. 'type',
  120839. 'target',
  120840. 'currentTarget',
  120841. 'which',
  120842. 'pageX',
  120843. 'pageY',
  120844. 'timeStamp'
  120845. ];
  120846. var CLONE_DEFAULTS = [
  120847. // MouseEvent
  120848. false,
  120849. false,
  120850. null,
  120851. null,
  120852. 0,
  120853. 0,
  120854. 0,
  120855. 0,
  120856. false,
  120857. false,
  120858. false,
  120859. false,
  120860. 0,
  120861. null,
  120862. // DOM Level 3
  120863. 0,
  120864. // PointerEvent
  120865. 0,
  120866. 0,
  120867. 0,
  120868. 0,
  120869. 0,
  120870. 0,
  120871. '',
  120872. 0,
  120873. false,
  120874. // event instance
  120875. '',
  120876. null,
  120877. null,
  120878. 0,
  120879. 0,
  120880. 0,
  120881. 0
  120882. ];
  120883. var BOUNDARY_EVENTS = {
  120884. 'pointerover': 1,
  120885. 'pointerout': 1,
  120886. 'pointerenter': 1,
  120887. 'pointerleave': 1
  120888. };
  120889. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  120890. /**
  120891. * This module is for normalizing events. Mouse and Touch events will be
  120892. * collected here, and fire PointerEvents that have the same semantics, no
  120893. * matter the source.
  120894. * Events fired:
  120895. * - pointerdown: a pointing is added
  120896. * - pointerup: a pointer is removed
  120897. * - pointermove: a pointer is moved
  120898. * - pointerover: a pointer crosses into an element
  120899. * - pointerout: a pointer leaves an element
  120900. * - pointercancel: a pointer will no longer generate events
  120901. */
  120902. var dispatcher = {
  120903. pointermap: new PointerMap(),
  120904. eventMap: Object.create(null),
  120905. captureInfo: Object.create(null),
  120906. // Scope objects for native events.
  120907. // This exists for ease of testing.
  120908. eventSources: Object.create(null),
  120909. eventSourceList: [],
  120910. /**
  120911. * Add a new event source that will generate pointer events.
  120912. *
  120913. * `inSource` must contain an array of event names named `events`, and
  120914. * functions with the names specified in the `events` array.
  120915. * @param {string} name A name for the event source
  120916. * @param {Object} source A new source of platform events.
  120917. */
  120918. registerSource: function(name, source) {
  120919. var s = source;
  120920. var newEvents = s.events;
  120921. if (newEvents) {
  120922. newEvents.forEach(function(e) {
  120923. if (s[e]) {
  120924. this.eventMap[e] = s[e].bind(s);
  120925. }
  120926. }, this);
  120927. this.eventSources[name] = s;
  120928. this.eventSourceList.push(s);
  120929. }
  120930. },
  120931. register: function(element) {
  120932. var l = this.eventSourceList.length;
  120933. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  120934. // call eventsource register
  120935. es.register.call(es, element);
  120936. }
  120937. },
  120938. unregister: function(element) {
  120939. var l = this.eventSourceList.length;
  120940. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  120941. // call eventsource register
  120942. es.unregister.call(es, element);
  120943. }
  120944. },
  120945. contains: /*scope.external.contains || */function(container, contained) {
  120946. try {
  120947. return container.contains(contained);
  120948. } catch (ex) {
  120949. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  120950. return false;
  120951. }
  120952. },
  120953. // EVENTS
  120954. down: function(inEvent) {
  120955. inEvent.bubbles = true;
  120956. this.fireEvent('pointerdown', inEvent);
  120957. },
  120958. move: function(inEvent) {
  120959. inEvent.bubbles = true;
  120960. this.fireEvent('pointermove', inEvent);
  120961. },
  120962. up: function(inEvent) {
  120963. inEvent.bubbles = true;
  120964. this.fireEvent('pointerup', inEvent);
  120965. },
  120966. enter: function(inEvent) {
  120967. inEvent.bubbles = false;
  120968. this.fireEvent('pointerenter', inEvent);
  120969. },
  120970. leave: function(inEvent) {
  120971. inEvent.bubbles = false;
  120972. this.fireEvent('pointerleave', inEvent);
  120973. },
  120974. over: function(inEvent) {
  120975. inEvent.bubbles = true;
  120976. this.fireEvent('pointerover', inEvent);
  120977. },
  120978. out: function(inEvent) {
  120979. inEvent.bubbles = true;
  120980. this.fireEvent('pointerout', inEvent);
  120981. },
  120982. cancel: function(inEvent) {
  120983. inEvent.bubbles = true;
  120984. this.fireEvent('pointercancel', inEvent);
  120985. },
  120986. leaveOut: function(event) {
  120987. this.out(event);
  120988. this.propagate(event, this.leave, false);
  120989. },
  120990. enterOver: function(event) {
  120991. this.over(event);
  120992. this.propagate(event, this.enter, true);
  120993. },
  120994. // LISTENER LOGIC
  120995. eventHandler: function(inEvent) {
  120996. // This is used to prevent multiple dispatch of pointerevents from
  120997. // platform events. This can happen when two elements in different scopes
  120998. // are set up to create pointer events, which is relevant to Shadow DOM.
  120999. if (inEvent._handledByPE) {
  121000. return;
  121001. }
  121002. var type = inEvent.type;
  121003. var fn = this.eventMap && this.eventMap[type];
  121004. if (fn) {
  121005. fn(inEvent);
  121006. }
  121007. inEvent._handledByPE = true;
  121008. },
  121009. // set up event listeners
  121010. listen: function(target, events) {
  121011. events.forEach(function(e) {
  121012. this.addEvent(target, e);
  121013. }, this);
  121014. },
  121015. // remove event listeners
  121016. unlisten: function(target, events) {
  121017. events.forEach(function(e) {
  121018. this.removeEvent(target, e);
  121019. }, this);
  121020. },
  121021. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  121022. target.addEventListener(eventName, this.boundHandler);
  121023. },
  121024. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  121025. target.removeEventListener(eventName, this.boundHandler);
  121026. },
  121027. // EVENT CREATION AND TRACKING
  121028. /**
  121029. * Creates a new Event of type `inType`, based on the information in
  121030. * `inEvent`.
  121031. *
  121032. * @param {string} inType A string representing the type of event to create
  121033. * @param {Event} inEvent A platform event with a target
  121034. * @return {Event} A PointerEvent of type `inType`
  121035. */
  121036. makeEvent: function(inType, inEvent) {
  121037. // relatedTarget must be null if pointer is captured
  121038. if (this.captureInfo[inEvent.pointerId]) {
  121039. inEvent.relatedTarget = null;
  121040. }
  121041. var e = new PointerEvent(inType, inEvent);
  121042. if (inEvent.preventDefault) {
  121043. e.preventDefault = inEvent.preventDefault;
  121044. }
  121045. e._target = e._target || inEvent.target;
  121046. return e;
  121047. },
  121048. // make and dispatch an event in one call
  121049. fireEvent: function(inType, inEvent) {
  121050. var e = this.makeEvent(inType, inEvent);
  121051. return this.dispatchEvent(e);
  121052. },
  121053. /**
  121054. * Returns a snapshot of inEvent, with writable properties.
  121055. *
  121056. * @param {Event} inEvent An event that contains properties to copy.
  121057. * @return {Object} An object containing shallow copies of `inEvent`'s
  121058. * properties.
  121059. */
  121060. cloneEvent: function(inEvent) {
  121061. var eventCopy = Object.create(null);
  121062. var p;
  121063. for (var i = 0; i < CLONE_PROPS.length; i++) {
  121064. p = CLONE_PROPS[i];
  121065. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  121066. // Work around SVGInstanceElement shadow tree
  121067. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  121068. // This is the behavior implemented by Firefox.
  121069. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  121070. if (eventCopy[p] instanceof SVGElementInstance) {
  121071. eventCopy[p] = eventCopy[p].correspondingUseElement;
  121072. }
  121073. }
  121074. }
  121075. // keep the semantics of preventDefault
  121076. if (inEvent.preventDefault) {
  121077. eventCopy.preventDefault = function() {
  121078. inEvent.preventDefault();
  121079. };
  121080. }
  121081. return eventCopy;
  121082. },
  121083. getTarget: function(inEvent) {
  121084. var capture = this.captureInfo[inEvent.pointerId];
  121085. if (!capture) {
  121086. return inEvent._target;
  121087. }
  121088. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  121089. return capture;
  121090. }
  121091. },
  121092. propagate: function(event, fn, propagateDown) {
  121093. var target = event.target;
  121094. var targets = [];
  121095. // Order of conditions due to document.contains() missing in IE.
  121096. while (target !== document && !target.contains(event.relatedTarget)) {
  121097. targets.push(target);
  121098. target = target.parentNode;
  121099. // Touch: Do not propagate if node is detached.
  121100. if (!target) {
  121101. return;
  121102. }
  121103. }
  121104. if (propagateDown) {
  121105. targets.reverse();
  121106. }
  121107. targets.forEach(function(target) {
  121108. event.target = target;
  121109. fn.call(this, event);
  121110. }, this);
  121111. },
  121112. setCapture: function(inPointerId, inTarget, skipDispatch) {
  121113. if (this.captureInfo[inPointerId]) {
  121114. this.releaseCapture(inPointerId, skipDispatch);
  121115. }
  121116. this.captureInfo[inPointerId] = inTarget;
  121117. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  121118. document.addEventListener('pointerup', this.implicitRelease);
  121119. document.addEventListener('pointercancel', this.implicitRelease);
  121120. var e = new PointerEvent('gotpointercapture');
  121121. e.pointerId = inPointerId;
  121122. e._target = inTarget;
  121123. if (!skipDispatch) {
  121124. this.asyncDispatchEvent(e);
  121125. }
  121126. },
  121127. releaseCapture: function(inPointerId, skipDispatch) {
  121128. var t = this.captureInfo[inPointerId];
  121129. if (!t) {
  121130. return;
  121131. }
  121132. this.captureInfo[inPointerId] = undefined;
  121133. document.removeEventListener('pointerup', this.implicitRelease);
  121134. document.removeEventListener('pointercancel', this.implicitRelease);
  121135. var e = new PointerEvent('lostpointercapture');
  121136. e.pointerId = inPointerId;
  121137. e._target = t;
  121138. if (!skipDispatch) {
  121139. this.asyncDispatchEvent(e);
  121140. }
  121141. },
  121142. /**
  121143. * Dispatches the event to its target.
  121144. *
  121145. * @param {Event} inEvent The event to be dispatched.
  121146. * @return {Boolean} True if an event handler returns true, false otherwise.
  121147. */
  121148. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  121149. var t = this.getTarget(inEvent);
  121150. if (t) {
  121151. return t.dispatchEvent(inEvent);
  121152. }
  121153. },
  121154. asyncDispatchEvent: function(inEvent) {
  121155. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  121156. }
  121157. };
  121158. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  121159. var targeting = {
  121160. shadow: function(inEl) {
  121161. if (inEl) {
  121162. return inEl.shadowRoot || inEl.webkitShadowRoot;
  121163. }
  121164. },
  121165. canTarget: function(shadow) {
  121166. return shadow && Boolean(shadow.elementFromPoint);
  121167. },
  121168. targetingShadow: function(inEl) {
  121169. var s = this.shadow(inEl);
  121170. if (this.canTarget(s)) {
  121171. return s;
  121172. }
  121173. },
  121174. olderShadow: function(shadow) {
  121175. var os = shadow.olderShadowRoot;
  121176. if (!os) {
  121177. var se = shadow.querySelector('shadow');
  121178. if (se) {
  121179. os = se.olderShadowRoot;
  121180. }
  121181. }
  121182. return os;
  121183. },
  121184. allShadows: function(element) {
  121185. var shadows = [];
  121186. var s = this.shadow(element);
  121187. while (s) {
  121188. shadows.push(s);
  121189. s = this.olderShadow(s);
  121190. }
  121191. return shadows;
  121192. },
  121193. searchRoot: function(inRoot, x, y) {
  121194. if (inRoot) {
  121195. var t = inRoot.elementFromPoint(x, y);
  121196. var st, sr;
  121197. // is element a shadow host?
  121198. sr = this.targetingShadow(t);
  121199. while (sr) {
  121200. // find the the element inside the shadow root
  121201. st = sr.elementFromPoint(x, y);
  121202. if (!st) {
  121203. // check for older shadows
  121204. sr = this.olderShadow(sr);
  121205. } else {
  121206. // shadowed element may contain a shadow root
  121207. var ssr = this.targetingShadow(st);
  121208. return this.searchRoot(ssr, x, y) || st;
  121209. }
  121210. }
  121211. // light dom element is the target
  121212. return t;
  121213. }
  121214. },
  121215. owner: function(element) {
  121216. var s = element;
  121217. // walk up until you hit the shadow root or document
  121218. while (s.parentNode) {
  121219. s = s.parentNode;
  121220. }
  121221. // the owner element is expected to be a Document or ShadowRoot
  121222. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  121223. s = document;
  121224. }
  121225. return s;
  121226. },
  121227. findTarget: function(inEvent) {
  121228. var x = inEvent.clientX;
  121229. var y = inEvent.clientY;
  121230. // if the listener is in the shadow root, it is much faster to start there
  121231. var s = this.owner(inEvent.target);
  121232. // if x, y is not in this root, fall back to document search
  121233. if (!s.elementFromPoint(x, y)) {
  121234. s = document;
  121235. }
  121236. return this.searchRoot(s, x, y);
  121237. }
  121238. };
  121239. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  121240. var map = Array.prototype.map.call.bind(Array.prototype.map);
  121241. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  121242. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  121243. var MO = window.MutationObserver || window.WebKitMutationObserver;
  121244. var SELECTOR = '[touch-action]';
  121245. var OBSERVER_INIT = {
  121246. subtree: true,
  121247. childList: true,
  121248. attributes: true,
  121249. attributeOldValue: true,
  121250. attributeFilter: ['touch-action']
  121251. };
  121252. function Installer(add, remove, changed, binder) {
  121253. this.addCallback = add.bind(binder);
  121254. this.removeCallback = remove.bind(binder);
  121255. this.changedCallback = changed.bind(binder);
  121256. if (MO) {
  121257. this.observer = new MO(this.mutationWatcher.bind(this));
  121258. }
  121259. }
  121260. Installer.prototype = {
  121261. watchSubtree: function(target) {
  121262. // Only watch scopes that can target find, as these are top-level.
  121263. // Otherwise we can see duplicate additions and removals that add noise.
  121264. //
  121265. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  121266. // a removal without an insertion when a node is redistributed among
  121267. // shadows. Since it all ends up correct in the document, watching only
  121268. // the document will yield the correct mutations to watch.
  121269. if (this.observer && targeting.canTarget(target)) {
  121270. this.observer.observe(target, OBSERVER_INIT);
  121271. }
  121272. },
  121273. enableOnSubtree: function(target) {
  121274. this.watchSubtree(target);
  121275. if (target === document && document.readyState !== 'complete') {
  121276. this.installOnLoad();
  121277. } else {
  121278. this.installNewSubtree(target);
  121279. }
  121280. },
  121281. installNewSubtree: function(target) {
  121282. forEach(this.findElements(target), this.addElement, this);
  121283. },
  121284. findElements: function(target) {
  121285. if (target.querySelectorAll) {
  121286. return target.querySelectorAll(SELECTOR);
  121287. }
  121288. return [];
  121289. },
  121290. removeElement: function(el) {
  121291. this.removeCallback(el);
  121292. },
  121293. addElement: function(el) {
  121294. this.addCallback(el);
  121295. },
  121296. elementChanged: function(el, oldValue) {
  121297. this.changedCallback(el, oldValue);
  121298. },
  121299. concatLists: function(accum, list) {
  121300. return accum.concat(toArray(list));
  121301. },
  121302. // register all touch-action = none nodes on document load
  121303. installOnLoad: function() {
  121304. document.addEventListener('readystatechange', function() {
  121305. if (document.readyState === 'complete') {
  121306. this.installNewSubtree(document);
  121307. }
  121308. }.bind(this));
  121309. },
  121310. isElement: function(n) {
  121311. return n.nodeType === Node.ELEMENT_NODE;
  121312. },
  121313. flattenMutationTree: function(inNodes) {
  121314. // find children with touch-action
  121315. var tree = map(inNodes, this.findElements, this);
  121316. // make sure the added nodes are accounted for
  121317. tree.push(filter(inNodes, this.isElement));
  121318. // flatten the list
  121319. return tree.reduce(this.concatLists, []);
  121320. },
  121321. mutationWatcher: function(mutations) {
  121322. mutations.forEach(this.mutationHandler, this);
  121323. },
  121324. mutationHandler: function(m) {
  121325. if (m.type === 'childList') {
  121326. var added = this.flattenMutationTree(m.addedNodes);
  121327. added.forEach(this.addElement, this);
  121328. var removed = this.flattenMutationTree(m.removedNodes);
  121329. removed.forEach(this.removeElement, this);
  121330. } else if (m.type === 'attributes') {
  121331. this.elementChanged(m.target, m.oldValue);
  121332. }
  121333. }
  121334. };
  121335. function shadowSelector(v) {
  121336. return 'body /shadow-deep/ ' + selector(v);
  121337. }
  121338. function selector(v) {
  121339. return '[touch-action="' + v + '"]';
  121340. }
  121341. function rule(v) {
  121342. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  121343. }
  121344. var attrib2css = [
  121345. 'none',
  121346. 'auto',
  121347. 'pan-x',
  121348. 'pan-y',
  121349. {
  121350. rule: 'pan-x pan-y',
  121351. selectors: [
  121352. 'pan-x pan-y',
  121353. 'pan-y pan-x'
  121354. ]
  121355. }
  121356. ];
  121357. var styles = '';
  121358. // only install stylesheet if the browser has touch action support
  121359. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  121360. // only add shadow selectors if shadowdom is supported
  121361. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  121362. function applyAttributeStyles() {
  121363. if (hasNativePE) {
  121364. attrib2css.forEach(function(r) {
  121365. if (String(r) === r) {
  121366. styles += selector(r) + rule(r) + '\n';
  121367. if (hasShadowRoot) {
  121368. styles += shadowSelector(r) + rule(r) + '\n';
  121369. }
  121370. } else {
  121371. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  121372. if (hasShadowRoot) {
  121373. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  121374. }
  121375. }
  121376. });
  121377. var el = document.createElement('style');
  121378. el.textContent = styles;
  121379. document.head.appendChild(el);
  121380. }
  121381. }
  121382. var pointermap = dispatcher.pointermap;
  121383. // radius around touchend that swallows mouse events
  121384. var DEDUP_DIST = 25;
  121385. // left, middle, right, back, forward
  121386. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  121387. var HAS_BUTTONS = false;
  121388. try {
  121389. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  121390. } catch (e) {}
  121391. // handler block for native mouse events
  121392. var mouseEvents = {
  121393. POINTER_ID: 1,
  121394. POINTER_TYPE: 'mouse',
  121395. events: [
  121396. 'mousedown',
  121397. 'mousemove',
  121398. 'mouseup',
  121399. 'mouseover',
  121400. 'mouseout'
  121401. ],
  121402. register: function(target) {
  121403. dispatcher.listen(target, this.events);
  121404. },
  121405. unregister: function(target) {
  121406. dispatcher.unlisten(target, this.events);
  121407. },
  121408. lastTouches: [],
  121409. // collide with the global mouse listener
  121410. isEventSimulatedFromTouch: function(inEvent) {
  121411. var lts = this.lastTouches;
  121412. var x = inEvent.clientX;
  121413. var y = inEvent.clientY;
  121414. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  121415. // simulated mouse events will be swallowed near a primary touchend
  121416. var dx = Math.abs(x - t.x);
  121417. var dy = Math.abs(y - t.y);
  121418. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  121419. return true;
  121420. }
  121421. }
  121422. },
  121423. prepareEvent: function(inEvent) {
  121424. var e = dispatcher.cloneEvent(inEvent);
  121425. // forward mouse preventDefault
  121426. var pd = e.preventDefault;
  121427. e.preventDefault = function() {
  121428. inEvent.preventDefault();
  121429. pd();
  121430. };
  121431. e.pointerId = this.POINTER_ID;
  121432. e.isPrimary = true;
  121433. e.pointerType = this.POINTER_TYPE;
  121434. return e;
  121435. },
  121436. prepareButtonsForMove: function(e, inEvent) {
  121437. var p = pointermap.get(this.POINTER_ID);
  121438. // Update buttons state after possible out-of-document mouseup.
  121439. if (inEvent.which === 0 || !p) {
  121440. e.buttons = 0;
  121441. } else {
  121442. e.buttons = p.buttons;
  121443. }
  121444. inEvent.buttons = e.buttons;
  121445. },
  121446. mousedown: function(inEvent) {
  121447. if (!this.isEventSimulatedFromTouch(inEvent)) {
  121448. var p = pointermap.get(this.POINTER_ID);
  121449. var e = this.prepareEvent(inEvent);
  121450. if (!HAS_BUTTONS) {
  121451. e.buttons = BUTTON_TO_BUTTONS[e.button];
  121452. if (p) { e.buttons |= p.buttons; }
  121453. inEvent.buttons = e.buttons;
  121454. }
  121455. pointermap.set(this.POINTER_ID, inEvent);
  121456. if (!p || p.buttons === 0) {
  121457. dispatcher.down(e);
  121458. } else {
  121459. dispatcher.move(e);
  121460. }
  121461. }
  121462. },
  121463. mousemove: function(inEvent) {
  121464. if (!this.isEventSimulatedFromTouch(inEvent)) {
  121465. var e = this.prepareEvent(inEvent);
  121466. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  121467. e.button = -1;
  121468. pointermap.set(this.POINTER_ID, inEvent);
  121469. dispatcher.move(e);
  121470. }
  121471. },
  121472. mouseup: function(inEvent) {
  121473. if (!this.isEventSimulatedFromTouch(inEvent)) {
  121474. var p = pointermap.get(this.POINTER_ID);
  121475. var e = this.prepareEvent(inEvent);
  121476. if (!HAS_BUTTONS) {
  121477. var up = BUTTON_TO_BUTTONS[e.button];
  121478. // Produces wrong state of buttons in Browsers without `buttons` support
  121479. // when a mouse button that was pressed outside the document is released
  121480. // inside and other buttons are still pressed down.
  121481. e.buttons = p ? p.buttons & ~up : 0;
  121482. inEvent.buttons = e.buttons;
  121483. }
  121484. pointermap.set(this.POINTER_ID, inEvent);
  121485. // Support: Firefox <=44 only
  121486. // FF Ubuntu includes the lifted button in the `buttons` property on
  121487. // mouseup.
  121488. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  121489. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  121490. if (e.buttons === 0) {
  121491. dispatcher.up(e);
  121492. } else {
  121493. dispatcher.move(e);
  121494. }
  121495. }
  121496. },
  121497. mouseover: function(inEvent) {
  121498. if (!this.isEventSimulatedFromTouch(inEvent)) {
  121499. var e = this.prepareEvent(inEvent);
  121500. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  121501. e.button = -1;
  121502. pointermap.set(this.POINTER_ID, inEvent);
  121503. dispatcher.enterOver(e);
  121504. }
  121505. },
  121506. mouseout: function(inEvent) {
  121507. if (!this.isEventSimulatedFromTouch(inEvent)) {
  121508. var e = this.prepareEvent(inEvent);
  121509. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  121510. e.button = -1;
  121511. dispatcher.leaveOut(e);
  121512. }
  121513. },
  121514. cancel: function(inEvent) {
  121515. var e = this.prepareEvent(inEvent);
  121516. dispatcher.cancel(e);
  121517. this.deactivateMouse();
  121518. },
  121519. deactivateMouse: function() {
  121520. pointermap.delete(this.POINTER_ID);
  121521. }
  121522. };
  121523. var captureInfo = dispatcher.captureInfo;
  121524. var findTarget = targeting.findTarget.bind(targeting);
  121525. var allShadows = targeting.allShadows.bind(targeting);
  121526. var pointermap$1 = dispatcher.pointermap;
  121527. // This should be long enough to ignore compat mouse events made by touch
  121528. var DEDUP_TIMEOUT = 2500;
  121529. var CLICK_COUNT_TIMEOUT = 200;
  121530. var ATTRIB = 'touch-action';
  121531. var INSTALLER;
  121532. // handler block for native touch events
  121533. var touchEvents = {
  121534. events: [
  121535. 'touchstart',
  121536. 'touchmove',
  121537. 'touchend',
  121538. 'touchcancel'
  121539. ],
  121540. register: function(target) {
  121541. INSTALLER.enableOnSubtree(target);
  121542. },
  121543. unregister: function() {
  121544. // TODO(dfreedman): is it worth it to disconnect the MO?
  121545. },
  121546. elementAdded: function(el) {
  121547. var a = el.getAttribute(ATTRIB);
  121548. var st = this.touchActionToScrollType(a);
  121549. if (st) {
  121550. el._scrollType = st;
  121551. dispatcher.listen(el, this.events);
  121552. // set touch-action on shadows as well
  121553. allShadows(el).forEach(function(s) {
  121554. s._scrollType = st;
  121555. dispatcher.listen(s, this.events);
  121556. }, this);
  121557. }
  121558. },
  121559. elementRemoved: function(el) {
  121560. el._scrollType = undefined;
  121561. dispatcher.unlisten(el, this.events);
  121562. // remove touch-action from shadow
  121563. allShadows(el).forEach(function(s) {
  121564. s._scrollType = undefined;
  121565. dispatcher.unlisten(s, this.events);
  121566. }, this);
  121567. },
  121568. elementChanged: function(el, oldValue) {
  121569. var a = el.getAttribute(ATTRIB);
  121570. var st = this.touchActionToScrollType(a);
  121571. var oldSt = this.touchActionToScrollType(oldValue);
  121572. // simply update scrollType if listeners are already established
  121573. if (st && oldSt) {
  121574. el._scrollType = st;
  121575. allShadows(el).forEach(function(s) {
  121576. s._scrollType = st;
  121577. }, this);
  121578. } else if (oldSt) {
  121579. this.elementRemoved(el);
  121580. } else if (st) {
  121581. this.elementAdded(el);
  121582. }
  121583. },
  121584. scrollTypes: {
  121585. EMITTER: 'none',
  121586. XSCROLLER: 'pan-x',
  121587. YSCROLLER: 'pan-y',
  121588. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  121589. },
  121590. touchActionToScrollType: function(touchAction) {
  121591. var t = touchAction;
  121592. var st = this.scrollTypes;
  121593. if (t === 'none') {
  121594. return 'none';
  121595. } else if (t === st.XSCROLLER) {
  121596. return 'X';
  121597. } else if (t === st.YSCROLLER) {
  121598. return 'Y';
  121599. } else if (st.SCROLLER.exec(t)) {
  121600. return 'XY';
  121601. }
  121602. },
  121603. POINTER_TYPE: 'touch',
  121604. firstTouch: null,
  121605. isPrimaryTouch: function(inTouch) {
  121606. return this.firstTouch === inTouch.identifier;
  121607. },
  121608. setPrimaryTouch: function(inTouch) {
  121609. // set primary touch if there no pointers, or the only pointer is the mouse
  121610. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  121611. this.firstTouch = inTouch.identifier;
  121612. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  121613. this.scrolling = false;
  121614. this.cancelResetClickCount();
  121615. }
  121616. },
  121617. removePrimaryPointer: function(inPointer) {
  121618. if (inPointer.isPrimary) {
  121619. this.firstTouch = null;
  121620. this.firstXY = null;
  121621. this.resetClickCount();
  121622. }
  121623. },
  121624. clickCount: 0,
  121625. resetId: null,
  121626. resetClickCount: function() {
  121627. var fn = function() {
  121628. this.clickCount = 0;
  121629. this.resetId = null;
  121630. }.bind(this);
  121631. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  121632. },
  121633. cancelResetClickCount: function() {
  121634. if (this.resetId) {
  121635. clearTimeout(this.resetId);
  121636. }
  121637. },
  121638. typeToButtons: function(type) {
  121639. var ret = 0;
  121640. if (type === 'touchstart' || type === 'touchmove') {
  121641. ret = 1;
  121642. }
  121643. return ret;
  121644. },
  121645. touchToPointer: function(inTouch) {
  121646. var cte = this.currentTouchEvent;
  121647. var e = dispatcher.cloneEvent(inTouch);
  121648. // We reserve pointerId 1 for Mouse.
  121649. // Touch identifiers can start at 0.
  121650. // Add 2 to the touch identifier for compatibility.
  121651. var id = e.pointerId = inTouch.identifier + 2;
  121652. e.target = captureInfo[id] || findTarget(e);
  121653. e.bubbles = true;
  121654. e.cancelable = true;
  121655. e.detail = this.clickCount;
  121656. e.button = 0;
  121657. e.buttons = this.typeToButtons(cte.type);
  121658. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  121659. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  121660. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  121661. e.isPrimary = this.isPrimaryTouch(inTouch);
  121662. e.pointerType = this.POINTER_TYPE;
  121663. // forward modifier keys
  121664. e.altKey = cte.altKey;
  121665. e.ctrlKey = cte.ctrlKey;
  121666. e.metaKey = cte.metaKey;
  121667. e.shiftKey = cte.shiftKey;
  121668. // forward touch preventDefaults
  121669. var self = this;
  121670. e.preventDefault = function() {
  121671. self.scrolling = false;
  121672. self.firstXY = null;
  121673. cte.preventDefault();
  121674. };
  121675. return e;
  121676. },
  121677. processTouches: function(inEvent, inFunction) {
  121678. var tl = inEvent.changedTouches;
  121679. this.currentTouchEvent = inEvent;
  121680. for (var i = 0, t; i < tl.length; i++) {
  121681. t = tl[i];
  121682. inFunction.call(this, this.touchToPointer(t));
  121683. }
  121684. },
  121685. // For single axis scrollers, determines whether the element should emit
  121686. // pointer events or behave as a scroller
  121687. shouldScroll: function(inEvent) {
  121688. if (this.firstXY) {
  121689. var ret;
  121690. var scrollAxis = inEvent.currentTarget._scrollType;
  121691. if (scrollAxis === 'none') {
  121692. // this element is a touch-action: none, should never scroll
  121693. ret = false;
  121694. } else if (scrollAxis === 'XY') {
  121695. // this element should always scroll
  121696. ret = true;
  121697. } else {
  121698. var t = inEvent.changedTouches[0];
  121699. // check the intended scroll axis, and other axis
  121700. var a = scrollAxis;
  121701. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  121702. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  121703. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  121704. // if delta in the scroll axis > delta other axis, scroll instead of
  121705. // making events
  121706. ret = da >= doa;
  121707. }
  121708. this.firstXY = null;
  121709. return ret;
  121710. }
  121711. },
  121712. findTouch: function(inTL, inId) {
  121713. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  121714. if (t.identifier === inId) {
  121715. return true;
  121716. }
  121717. }
  121718. },
  121719. // In some instances, a touchstart can happen without a touchend. This
  121720. // leaves the pointermap in a broken state.
  121721. // Therefore, on every touchstart, we remove the touches that did not fire a
  121722. // touchend event.
  121723. // To keep state globally consistent, we fire a
  121724. // pointercancel for this "abandoned" touch
  121725. vacuumTouches: function(inEvent) {
  121726. var tl = inEvent.touches;
  121727. // pointermap.size should be < tl.length here, as the touchstart has not
  121728. // been processed yet.
  121729. if (pointermap$1.size >= tl.length) {
  121730. var d = [];
  121731. pointermap$1.forEach(function(value, key) {
  121732. // Never remove pointerId == 1, which is mouse.
  121733. // Touch identifiers are 2 smaller than their pointerId, which is the
  121734. // index in pointermap.
  121735. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  121736. var p = value.out;
  121737. d.push(p);
  121738. }
  121739. }, this);
  121740. d.forEach(this.cancelOut, this);
  121741. }
  121742. },
  121743. touchstart: function(inEvent) {
  121744. this.vacuumTouches(inEvent);
  121745. this.setPrimaryTouch(inEvent.changedTouches[0]);
  121746. this.dedupSynthMouse(inEvent);
  121747. if (!this.scrolling) {
  121748. this.clickCount++;
  121749. this.processTouches(inEvent, this.overDown);
  121750. }
  121751. },
  121752. overDown: function(inPointer) {
  121753. pointermap$1.set(inPointer.pointerId, {
  121754. target: inPointer.target,
  121755. out: inPointer,
  121756. outTarget: inPointer.target
  121757. });
  121758. dispatcher.enterOver(inPointer);
  121759. dispatcher.down(inPointer);
  121760. },
  121761. touchmove: function(inEvent) {
  121762. if (!this.scrolling) {
  121763. if (this.shouldScroll(inEvent)) {
  121764. this.scrolling = true;
  121765. this.touchcancel(inEvent);
  121766. } else {
  121767. inEvent.preventDefault();
  121768. this.processTouches(inEvent, this.moveOverOut);
  121769. }
  121770. }
  121771. },
  121772. moveOverOut: function(inPointer) {
  121773. var event = inPointer;
  121774. var pointer = pointermap$1.get(event.pointerId);
  121775. // a finger drifted off the screen, ignore it
  121776. if (!pointer) {
  121777. return;
  121778. }
  121779. var outEvent = pointer.out;
  121780. var outTarget = pointer.outTarget;
  121781. dispatcher.move(event);
  121782. if (outEvent && outTarget !== event.target) {
  121783. outEvent.relatedTarget = event.target;
  121784. event.relatedTarget = outTarget;
  121785. // recover from retargeting by shadow
  121786. outEvent.target = outTarget;
  121787. if (event.target) {
  121788. dispatcher.leaveOut(outEvent);
  121789. dispatcher.enterOver(event);
  121790. } else {
  121791. // clean up case when finger leaves the screen
  121792. event.target = outTarget;
  121793. event.relatedTarget = null;
  121794. this.cancelOut(event);
  121795. }
  121796. }
  121797. pointer.out = event;
  121798. pointer.outTarget = event.target;
  121799. },
  121800. touchend: function(inEvent) {
  121801. this.dedupSynthMouse(inEvent);
  121802. this.processTouches(inEvent, this.upOut);
  121803. },
  121804. upOut: function(inPointer) {
  121805. if (!this.scrolling) {
  121806. dispatcher.up(inPointer);
  121807. dispatcher.leaveOut(inPointer);
  121808. }
  121809. this.cleanUpPointer(inPointer);
  121810. },
  121811. touchcancel: function(inEvent) {
  121812. this.processTouches(inEvent, this.cancelOut);
  121813. },
  121814. cancelOut: function(inPointer) {
  121815. dispatcher.cancel(inPointer);
  121816. dispatcher.leaveOut(inPointer);
  121817. this.cleanUpPointer(inPointer);
  121818. },
  121819. cleanUpPointer: function(inPointer) {
  121820. pointermap$1.delete(inPointer.pointerId);
  121821. this.removePrimaryPointer(inPointer);
  121822. },
  121823. // prevent synth mouse events from creating pointer events
  121824. dedupSynthMouse: function(inEvent) {
  121825. var lts = mouseEvents.lastTouches;
  121826. var t = inEvent.changedTouches[0];
  121827. // only the primary finger will synth mouse events
  121828. if (this.isPrimaryTouch(t)) {
  121829. // remember x/y of last touch
  121830. var lt = { x: t.clientX, y: t.clientY };
  121831. lts.push(lt);
  121832. var fn = (function(lts, lt) {
  121833. var i = lts.indexOf(lt);
  121834. if (i > -1) {
  121835. lts.splice(i, 1);
  121836. }
  121837. }).bind(null, lts, lt);
  121838. setTimeout(fn, DEDUP_TIMEOUT);
  121839. }
  121840. }
  121841. };
  121842. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  121843. touchEvents.elementChanged, touchEvents);
  121844. var pointermap$2 = dispatcher.pointermap;
  121845. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  121846. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  121847. var msEvents = {
  121848. events: [
  121849. 'MSPointerDown',
  121850. 'MSPointerMove',
  121851. 'MSPointerUp',
  121852. 'MSPointerOut',
  121853. 'MSPointerOver',
  121854. 'MSPointerCancel',
  121855. 'MSGotPointerCapture',
  121856. 'MSLostPointerCapture'
  121857. ],
  121858. register: function(target) {
  121859. dispatcher.listen(target, this.events);
  121860. },
  121861. unregister: function(target) {
  121862. dispatcher.unlisten(target, this.events);
  121863. },
  121864. POINTER_TYPES: [
  121865. '',
  121866. 'unavailable',
  121867. 'touch',
  121868. 'pen',
  121869. 'mouse'
  121870. ],
  121871. prepareEvent: function(inEvent) {
  121872. var e = inEvent;
  121873. if (HAS_BITMAP_TYPE) {
  121874. e = dispatcher.cloneEvent(inEvent);
  121875. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  121876. }
  121877. return e;
  121878. },
  121879. cleanup: function(id) {
  121880. pointermap$2.delete(id);
  121881. },
  121882. MSPointerDown: function(inEvent) {
  121883. pointermap$2.set(inEvent.pointerId, inEvent);
  121884. var e = this.prepareEvent(inEvent);
  121885. dispatcher.down(e);
  121886. },
  121887. MSPointerMove: function(inEvent) {
  121888. var e = this.prepareEvent(inEvent);
  121889. dispatcher.move(e);
  121890. },
  121891. MSPointerUp: function(inEvent) {
  121892. var e = this.prepareEvent(inEvent);
  121893. dispatcher.up(e);
  121894. this.cleanup(inEvent.pointerId);
  121895. },
  121896. MSPointerOut: function(inEvent) {
  121897. var e = this.prepareEvent(inEvent);
  121898. dispatcher.leaveOut(e);
  121899. },
  121900. MSPointerOver: function(inEvent) {
  121901. var e = this.prepareEvent(inEvent);
  121902. dispatcher.enterOver(e);
  121903. },
  121904. MSPointerCancel: function(inEvent) {
  121905. var e = this.prepareEvent(inEvent);
  121906. dispatcher.cancel(e);
  121907. this.cleanup(inEvent.pointerId);
  121908. },
  121909. MSLostPointerCapture: function(inEvent) {
  121910. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  121911. dispatcher.dispatchEvent(e);
  121912. },
  121913. MSGotPointerCapture: function(inEvent) {
  121914. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  121915. dispatcher.dispatchEvent(e);
  121916. }
  121917. };
  121918. function applyPolyfill() {
  121919. // only activate if this platform does not have pointer events
  121920. if (!window.PointerEvent) {
  121921. window.PointerEvent = PointerEvent;
  121922. if (window.navigator.msPointerEnabled) {
  121923. var tp = window.navigator.msMaxTouchPoints;
  121924. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  121925. value: tp,
  121926. enumerable: true
  121927. });
  121928. dispatcher.registerSource('ms', msEvents);
  121929. } else {
  121930. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  121931. value: 0,
  121932. enumerable: true
  121933. });
  121934. dispatcher.registerSource('mouse', mouseEvents);
  121935. if (window.ontouchstart !== undefined) {
  121936. dispatcher.registerSource('touch', touchEvents);
  121937. }
  121938. }
  121939. dispatcher.register(document);
  121940. }
  121941. }
  121942. var n = window.navigator;
  121943. var s;
  121944. var r;
  121945. var h;
  121946. function assertActive(id) {
  121947. if (!dispatcher.pointermap.has(id)) {
  121948. var error = new Error('InvalidPointerId');
  121949. error.name = 'InvalidPointerId';
  121950. throw error;
  121951. }
  121952. }
  121953. function assertConnected(elem) {
  121954. var parent = elem.parentNode;
  121955. while (parent && parent !== elem.ownerDocument) {
  121956. parent = parent.parentNode;
  121957. }
  121958. if (!parent) {
  121959. var error = new Error('InvalidStateError');
  121960. error.name = 'InvalidStateError';
  121961. throw error;
  121962. }
  121963. }
  121964. function inActiveButtonState(id) {
  121965. var p = dispatcher.pointermap.get(id);
  121966. return p.buttons !== 0;
  121967. }
  121968. if (n.msPointerEnabled) {
  121969. s = function(pointerId) {
  121970. assertActive(pointerId);
  121971. assertConnected(this);
  121972. if (inActiveButtonState(pointerId)) {
  121973. dispatcher.setCapture(pointerId, this, true);
  121974. this.msSetPointerCapture(pointerId);
  121975. }
  121976. };
  121977. r = function(pointerId) {
  121978. assertActive(pointerId);
  121979. dispatcher.releaseCapture(pointerId, true);
  121980. this.msReleasePointerCapture(pointerId);
  121981. };
  121982. } else {
  121983. s = function setPointerCapture(pointerId) {
  121984. assertActive(pointerId);
  121985. assertConnected(this);
  121986. if (inActiveButtonState(pointerId)) {
  121987. dispatcher.setCapture(pointerId, this);
  121988. }
  121989. };
  121990. r = function releasePointerCapture(pointerId) {
  121991. assertActive(pointerId);
  121992. dispatcher.releaseCapture(pointerId);
  121993. };
  121994. }
  121995. h = function hasPointerCapture(pointerId) {
  121996. return !!dispatcher.captureInfo[pointerId];
  121997. };
  121998. function applyPolyfill$1() {
  121999. if (window.Element && !Element.prototype.setPointerCapture) {
  122000. Object.defineProperties(Element.prototype, {
  122001. 'setPointerCapture': {
  122002. value: s
  122003. },
  122004. 'releasePointerCapture': {
  122005. value: r
  122006. },
  122007. 'hasPointerCapture': {
  122008. value: h
  122009. }
  122010. });
  122011. }
  122012. }
  122013. applyAttributeStyles();
  122014. applyPolyfill();
  122015. applyPolyfill$1();
  122016. var pointerevents = {
  122017. dispatcher: dispatcher,
  122018. Installer: Installer,
  122019. PointerEvent: PointerEvent,
  122020. PointerMap: PointerMap,
  122021. targetFinding: targeting
  122022. };
  122023. return pointerevents;
  122024. }));
  122025. /***/ }),
  122026. /* 67 */
  122027. /***/ (function(module, exports, __webpack_require__) {
  122028. "use strict";
  122029. Object.defineProperty(exports, "__esModule", { value: true });
  122030. var defaultViewer_1 = __webpack_require__(8);
  122031. var mappers_1 = __webpack_require__(3);
  122032. var globals_1 = __webpack_require__(4);
  122033. /**
  122034. * Will attach an init function the the DOMContentLoaded event.
  122035. * The init function will be removed automatically after the event was triggered.
  122036. */
  122037. function initListeners() {
  122038. document.addEventListener("DOMContentLoaded", init);
  122039. function init(event) {
  122040. document.removeEventListener("DOMContentLoaded", init);
  122041. if (globals_1.viewerGlobals.disableInit)
  122042. return;
  122043. InitTags();
  122044. }
  122045. }
  122046. exports.initListeners = initListeners;
  122047. /**
  122048. * Select all HTML tags on the page that match the selector and initialize a viewer
  122049. *
  122050. * @param selector the selector to initialize the viewer on (default is 'babylon')
  122051. */
  122052. function InitTags(selector) {
  122053. if (selector === void 0) { selector = 'babylon'; }
  122054. var elements = document.querySelectorAll(selector);
  122055. for (var i = 0; i < elements.length; ++i) {
  122056. var element = elements.item(i);
  122057. // get the html configuration
  122058. var configMapper = mappers_1.mapperManager.getMapper('dom');
  122059. var config = configMapper.map(element);
  122060. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  122061. }
  122062. }
  122063. exports.InitTags = InitTags;
  122064. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5pdGlhbGl6ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5pdGlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx3REFBdUQ7QUFDdkQsbURBQXdEO0FBQ3hELG1EQUF3RDtBQUd4RDs7O0dBR0c7QUFDSDtJQUNJLFFBQVEsQ0FBQyxnQkFBZ0IsQ0FBQyxrQkFBa0IsRUFBRSxJQUFJLENBQUMsQ0FBQztJQUNwRCxjQUFjLEtBQUs7UUFDZixRQUFRLENBQUMsbUJBQW1CLENBQUMsa0JBQWtCLEVBQUUsSUFBS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